diff --git a/capabilities/11-recording-privacy-and-proof/0105-model-calls-fail-closed-a-component-with-no.md b/capabilities/11-recording-privacy-and-proof/0105-model-calls-fail-closed-a-component-with-no.md new file mode 100644 index 0000000000..6f688a0433 --- /dev/null +++ b/capabilities/11-recording-privacy-and-proof/0105-model-calls-fail-closed-a-component-with-no.md @@ -0,0 +1 @@ +| Model calls fail closed: a component with no `MAY_EGRESS` marker counts as sending frames off the box and needs the egress opt-in; a model "yes" from the drift oracle is a hint for the person reviewing the halt, never a pass; identity-VLM calls count as model calls, split by placement (off-box into `model_calls`, in process into `local_model_calls`), so off-box identity crops never report no external calls; every frame sent off the box is first written to a local append-only ledger (`egress-ledger.jsonl` beside the run directory, hashes and sizes only) and is not sent if that write fails; a signed record that counts off-box model calls must say external calls were observed, while in-process calls never require it; the regulated profile refuses a cleartext appliance or grounding endpoint that is not loopback; a pinned grounding model that can't be wired, or names no model, never falls back to a default model or to the appliance | Branch ([#2497](https://github.com/OpenAdaptAI/OpenAdapt/pull/2497)) | Unit tests (`tests/test_model_failclosed.py`, `tests/test_drift_oracle.py`) | `runtime/model_egress.py`, `model_transport.py`, `model_call_evidence.py`, [ON_PREM_VLM.md](packages/flow/docs/deployment/ON_PREM_VLM.md) | diff --git a/packages/flow/docs/deployment/ON_PREM_VLM.md b/packages/flow/docs/deployment/ON_PREM_VLM.md index d0177bbe55..11a5eac05a 100644 --- a/packages/flow/docs/deployment/ON_PREM_VLM.md +++ b/packages/flow/docs/deployment/ON_PREM_VLM.md @@ -62,9 +62,10 @@ unqualified**: the appliance validation measured it non-functional at native frames are downscaled below ~1024px first) and ~12.5% false-rescue on genuinely-ambiguous in-progress screens (a `"Saving…"` read as saved). See [docs/LIMITS.md](../LIMITS.md) for the measured trap-set numbers before -relying on it. Because of that false-rescue rate, the replayer never asks the -oracle about a step that can change a record (see the drift-oracle entry -below). +relying on it. Because of that false-rescue rate, a "yes" never clears a +failed postcondition: it is a hint shown to the person who reviews the halt, +and the replayer doesn't ask at all about a step that can change a record (see +the drift-oracle entry below). ## Fail-safe behaviour (mandatory) @@ -199,9 +200,11 @@ handles into the `Replayer`. tier can only veto; a down appliance means more halts, never a wrong click. - **Drift-oracle postcondition** (`RemoteStateVerifier`): after deterministic checks and one settle retry fail, the replayer asks the verifier only about - render-drift-sensitive `text_present` and `region_stable` conditions. Only a - confident `yes` rescues the condition. A `no`, `uncertain`, error, or appliance - outage keeps the failure. Every call and rescue is recorded in the run result. + render-drift-sensitive `text_present` and `region_stable` conditions. The + answer never clears the failure: the step halts and goes to a person, and a + confident `yes` is recorded on the step (`postcondition_drift_rescues`) and + printed as a hint that the failure may be render drift. Every call is + recorded in the run result and counted as a model call. The replayer does not ask at all on an irreversible or effect-bearing step (the same steps the run gate treats as consequential, plus steps waiting for risk review). There a failed check stays failed. Unless the workflow has its @@ -243,7 +246,25 @@ through. Scrubbing here would **defeat the safety check**, not add safety. 3. **In-flight PHI, treated as such.** The crop is PHI moving inside the trust boundary. Run the appliance HTTPS-only on the LAN, gate it with the bearer token (`VLM_SERVICE_TOKEN`), and keep it inside the same network zone as the - runners. + runners. Under the `regulated` execution profile the runner enforces the + transport: it wires an appliance or a grounding model only over `https`, or + over `http` to loopback, and prints why it refused any other URL. It checks + the URL the built client sends to, including one the client library reads + from its own environment. +4. **Every frame sent off the box is on a local ledger.** Before each off-box + call the runner appends one line to `egress-ledger.jsonl` beside the run + directory (or the file `OPENADAPT_FLOW_EGRESS_LEDGER` names). The line holds + the frame's SHA-256 and size, the component, the destination host, the run, + the step and the time, and never pixels or text. The file is append-only, + mode `0600` and fsynced per line. If the line can't be written, or no + ledger is set (a replayer driven outside a run), the frame is not sent and the component gives its fail-safe answer, so the step halts. + Halted runs are on the ledger too, because each line is written when its + frame is sent. +5. **No fallback to another model.** When `grounding_model` is pinned and + can't be wired, the appliance grounder does not stand in for it. A pinned + section must name its `model`; an empty one is refused, never given a + default. The grounding rung stays off, and a target the deterministic rungs + can't resolve halts for a person. An operator auditing the appliance should confirm no reverse proxy, WSGI, or model-server logs the request body — that is the only way a crop could persist. diff --git a/packages/flow/docs/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index fe49f559b3..52690a10da 100644 --- a/packages/flow/docs/design/DECOMPOSITION.md +++ b/packages/flow/docs/design/DECOMPOSITION.md @@ -612,7 +612,7 @@ The encryption-at-rest default lowered `__main__.py`: the `at-rest` command, `-- | `packages/flow/openadapt_flow/runtime/replayer.py` | 18693 | | `packages/flow/openadapt_flow/__main__.py` | 14237 | | `packages/flow/openadapt_flow/qualification/__init__.py` | 4891 | -| `packages/flow/openadapt_flow/ir.py` | 6830 | +| `packages/flow/openadapt_flow/ir.py` | 6829 | | `packages/desktop/openadapt_desktop/dispatch.py` | 6524 | | `packages/capture/openadapt_capture/recorder.py` | 4836 | | `packages/flow/openadapt_flow/interactive_recorder.py` | 4808 | diff --git a/packages/flow/import_layers.json b/packages/flow/import_layers.json index 71f8fce6f0..f1172063cf 100644 --- a/packages/flow/import_layers.json +++ b/packages/flow/import_layers.json @@ -67,6 +67,8 @@ "openadapt_flow.form_tx.receipt", "openadapt_flow.key_rotation", "openadapt_flow.local_state_sources", + "openadapt_flow.model_call_evidence", + "openadapt_flow.model_transport", "openadapt_flow.offline_seal", "openadapt_flow.policy", "openadapt_flow.production_qualification", diff --git a/packages/flow/openadapt_flow/deployment.py b/packages/flow/openadapt_flow/deployment.py index 11f57767a8..eeee8dadce 100644 --- a/packages/flow/openadapt_flow/deployment.py +++ b/packages/flow/openadapt_flow/deployment.py @@ -823,8 +823,8 @@ class GroundingModelConfig(BaseModel): #: Root URL of an ``openai_compatible`` endpoint (``/chat/completions`` is #: appended). Required for ``openai_compatible``; ignored for ``anthropic``. base_url: str = "" - #: The vision-capable model id to request. For ``anthropic`` an empty value - #: uses the shipped default; for ``openai_compatible`` it is required. + #: The vision-capable model id to request. Required for both providers: an + #: enabled section with no model is refused, never given a default. model: str = "" #: NAME of the environment variable holding the API key (never the key #: itself). Empty => no auth header sent (a loopback vLLM/Ollama needs none); @@ -1707,15 +1707,23 @@ def build_model_grounder(cfg: GroundingModelConfig) -> Optional[Any]: api_key = os.environ.get(cfg.api_key_env, "") if cfg.api_key_env else "" if provider == "anthropic": - from openadapt_flow.runtime.grounder import _DEFAULT_MODEL, AnthropicGrounder + from openadapt_flow.runtime.grounder import AnthropicGrounder - model = (cfg.model or "").strip() or _DEFAULT_MODEL + model = (cfg.model or "").strip() + if not model: + # A pinned grounding model must name its model: an empty value + # never silently becomes the shipped default. + print( + "grounding_model.provider 'anthropic' requires a model; " + "replaying FULLY LOCAL." + ) + return None try: client = None if api_key: import anthropic - client = anthropic.Anthropic(api_key=api_key) + client = anthropic.Anthropic(api_key=api_key, max_retries=0) return AnthropicGrounder(model=model, client=client) except ImportError: print( @@ -1843,6 +1851,20 @@ def build_replayer( if not ok: print(f"PHI mode: {reason}; replaying FULLY LOCAL.") appliance = None + # Regulated if either the authorization or the deployment names it. + regulated = "regulated" in { + getattr(governed_authorization, "execution_profile", None), + getattr(runtime_config, "profile", None), + } + if appliance is not None and regulated: + from openadapt_flow.model_transport import regulated_transport_refusal + + # The URL the appliance client actually sends to. + sent_to = getattr(getattr(appliance, "client", None), "_base_url", "") + refusal = regulated_transport_refusal(sent_to or "") + if refusal is not None: + print(f"Regulated profile: {refusal}; the appliance is NOT wired.") + appliance = None if appliance is not None: print( "Using on-prem VLM appliance at " @@ -1875,18 +1897,38 @@ def build_replayer( wire = False if wire: model_grounder = build_model_grounder(grounding_cfg) - if model_grounder is not None: - print( - "Model grounder wired: " - f"{type(model_grounder).__name__} " - f"(provider={grounding_cfg.provider}). WARNING: " - "screenshots WILL leave the box for this run." + if model_grounder is not None and (regulated or phi_on): + from openadapt_flow.model_transport import ( + built_endpoint, + regulated_transport_refusal, + ) + + # Check the URL the built client sends to, not the config. + sent_to = built_endpoint(model_grounder) + refusal = regulated_transport_refusal(sent_to) if regulated else None + if refusal is None and phi_on: + ok, reason = phi_grounding_endpoint_allowed( + _host_of(sent_to), allowlist=allowlist, attested=attested ) + refusal = None if ok else reason + if refusal is not None: + print(f"Model grounder refused: {refusal}; replaying FULLY LOCAL.") + model_grounder = None + if model_grounder is not None: + print( + "Model grounder wired: " + f"{type(model_grounder).__name__} " + f"(provider={grounding_cfg.provider}). WARNING: " + "screenshots WILL leave the box for this run." + ) # The configured model grounder takes precedence as the VLM fallback; the - # on-prem appliance grounder is used only when no model grounder is wired. + # on-prem appliance grounder is used only when no model is pinned. A pinned + # model that can't be wired (unavailable, refused) never falls back to + # another placement or model: the grounding rung stays off and a target + # the deterministic rungs can't resolve halts for a person. fallback = model_grounder - if fallback is None and appliance is not None: + if fallback is None and appliance is not None and not grounding_cfg.enabled: fallback = appliance.grounder local_model: Optional[Any] = None if runtime_config is not None and runtime_config.local_grounding: diff --git a/packages/flow/openadapt_flow/ir.py b/packages/flow/openadapt_flow/ir.py index 6ac7b28865..1348a3d055 100644 --- a/packages/flow/openadapt_flow/ir.py +++ b/packages/flow/openadapt_flow/ir.py @@ -5168,10 +5168,9 @@ class StepResult(BaseModel): # effects were declared with no verifier configured). None is also used for # an explicitly approved but unverified GUI write; the separate # ``effect_approved_unverified`` flag makes that risk acceptance visible. - # ``effect_results`` - # holds one human-readable verdict line per declared effect, for the - # audit trail (mirrors the identity check's report surface). ZERO model - # calls on this path — effect verification reads the system of record. + # ``effect_results`` holds one human-readable verdict line per declared + # effect for the audit trail. ZERO model calls on this path: effect + # verification reads the system of record. effect_verified: Optional[bool] = None effect_approved_unverified: bool = False # A governed identity/effect/postcondition refusal is not an ordinary @@ -5197,12 +5196,9 @@ class StepResult(BaseModel): "continuation_preempted", ] ] = None - # One stable, NON-secret-bearing SHA-256 digest per verified effect, taken - # AFTER the effect's ValueExpr contract was bound to THIS run's params - # (P0-3). Records THAT a parameterized run verified against its own resolved - # record/value/idempotency-key (and lets an auditor confirm two runs - # resolved differently) without persisting the underlying value (e.g. a - # patient identifier). Empty when the step declared no effects. + # One NON-secret SHA-256 digest per verified effect, taken AFTER its + # ValueExpr contract was bound to THIS run's params (P0-3): proof a run + # verified its own record/value/idempotency key, without the value. effect_contract_hashes: list[str] = Field(default_factory=list) # How this step's write was PERFORMED: "api" when actuated via an # ApiBinding (GUI resolve/act skipped), None when it went through the GUI @@ -5241,11 +5237,14 @@ class StepResult(BaseModel): "as proof that settled-state detection ran." ), ) - # Drift-oracle: postconditions that deterministically FAILED but were - # confirmed by the optional on-prem VLM state-verifier under render drift - # (recorded for audit; empty unless an appliance is configured). + # Drift-oracle hints: FAILED postconditions the optional VLM state-verifier + # said hold. A hint only: they stay failed and the step halts for a person. postcondition_drift_rescues: list[str] = Field(default_factory=list) drift_oracle_calls: int = 0 # VLM state-verifier calls this step + # Model calls by placement (runtime.model_egress); omitted when zero. + identity_vlm_calls: int = Field(default=0, ge=0, exclude_if=lambda v: v == 0) + local_identity_vlm_calls: int = Field(default=0, ge=0, exclude_if=lambda v: v == 0) + grounder_calls: int = Field(default=0, ge=0, exclude_if=lambda v: v == 0) #: The uniform page scale (for example 1.25 under 125% zoom) at which a #: ``region_stable`` check found its recorded content, when it was found #: only there. Set only when this step's own click showed the same scale. diff --git a/packages/flow/openadapt_flow/model_call_evidence.py b/packages/flow/openadapt_flow/model_call_evidence.py new file mode 100644 index 0000000000..8a024b49ec --- /dev/null +++ b/packages/flow/openadapt_flow/model_call_evidence.py @@ -0,0 +1,39 @@ +"""The receipt rule for model calls, split by where the frame went. + +A signed record's ``model_calls`` counts only calls that may have sent a frame +off the box: drift-oracle calls, off-box identity-VLM calls and off-box +grounder calls (:func:`openadapt_flow.runtime.model_egress.model_calls_off_box`). +Calls that ran in process are counted on the run report as +``local_model_calls`` and never enter ``model_calls``. + +The two placements carry different rules: + +* **Off the box.** Any off-box call is model evidence, and the record must say + ``external_network_calls == "observed"``. A record that counts off-box calls + and says ``"none"`` is refused, so off-box identity crops can never be + reported as a run with no external calls. +* **In process.** An in-process call sends nothing over the network, so it + never requires ``"observed"`` and never makes a record with no off-box calls + claim model evidence. + +The receipt (:class:`openadapt_flow.receipt.RunReceipt`) applies +:func:`model_call_evidence_error`; the terminal verification payload +checks the same two rules in its own validator. +""" + +from __future__ import annotations + +from collections.abc import Iterable +from typing import Optional + + +def model_call_evidence_error( + off_box_calls: int, evidence_classes: Iterable[str], network: str +) -> Optional[str]: + """Why a record's off-box model-call count contradicts it, or None.""" + + if (off_box_calls > 0) != ("model" in set(evidence_classes)): + return "model-call count and evidence class disagree" + if off_box_calls > 0 and network != "observed": + return "model calls require observed external network calls" + return None diff --git a/packages/flow/openadapt_flow/model_transport.py b/packages/flow/openadapt_flow/model_transport.py new file mode 100644 index 0000000000..d0229dff70 --- /dev/null +++ b/packages/flow/openadapt_flow/model_transport.py @@ -0,0 +1,56 @@ +"""Which model endpoints a regulated run may send frames to. + +Under the ``regulated`` execution profile a frame may leave the process only +over TLS (``https``), or over plain ``http`` to this machine's loopback +interface. Every other URL is refused: cleartext to another host, any other +scheme, and anything that doesn't parse. +""" + +from __future__ import annotations + +import ipaddress +from typing import Optional +from urllib.parse import urlsplit + + +def _loopback(host: str) -> bool: + if host == "localhost": + return True + try: + return ipaddress.ip_address(host).is_loopback + except ValueError: + return False + + +def regulated_transport_refusal(url: str) -> Optional[str]: + """Why a regulated run must not send frames to ``url``, or None if it may.""" + + try: + parts = urlsplit((url or "").strip()) + host = (parts.hostname or "").lower() + except ValueError: + return "the model endpoint URL does not parse" + if not host: + return "the model endpoint URL names no host" + if parts.scheme == "https": + return None + if parts.scheme == "http" and _loopback(host): + return None + if parts.scheme == "http": + return f"the model endpoint {host} is cleartext http off this machine" + return f"the model endpoint scheme {parts.scheme!r} is not https" + + +def built_endpoint(component: object) -> str: + """The URL a built model client actually sends to, or ``""`` if unknown. + + Reads the constructed object, not the configuration, so a URL the client + library takes from its own environment (``ANTHROPIC_BASE_URL``) is seen. + """ + + for holder in (component, getattr(component, "_client", None)): + for name in ("_url", "_base_url", "base_url"): + url = getattr(holder, name, None) + if url: + return str(url) + return "" diff --git a/packages/flow/openadapt_flow/receipt.py b/packages/flow/openadapt_flow/receipt.py index 91c8a7d324..a72bb38e5f 100644 --- a/packages/flow/openadapt_flow/receipt.py +++ b/packages/flow/openadapt_flow/receipt.py @@ -339,10 +339,13 @@ def _complete_verified_contract(self) -> "RunReceipt": and self.effect_assurance != _ASSURANCE_BY_TIER[self.effect_tier_reached] ): raise ValueError("effect assurance disagrees with the effect tier") - if (self.model_calls > 0) != ("model" in self.evidence_classes): - raise ValueError("model-call count and evidence class disagree") - if self.model_calls > 0 and self.external_network_calls != "observed": - raise ValueError("model calls require observed external network calls") + # ``model_calls`` is off-box calls only; in-process ones never count. + from openadapt_flow.model_call_evidence import model_call_evidence_error + + if error := model_call_evidence_error( + self.model_calls, self.evidence_classes, self.external_network_calls + ): + raise ValueError(error) expected = hashlib.sha256(self.canonical_json(include_digest=False)).hexdigest() if self.receipt_digest != expected: raise ValueError("receipt digest does not match its canonical payload") diff --git a/packages/flow/openadapt_flow/runtime/grounder.py b/packages/flow/openadapt_flow/runtime/grounder.py index c55325cfa4..cbaa95f9df 100644 --- a/packages/flow/openadapt_flow/runtime/grounder.py +++ b/packages/flow/openadapt_flow/runtime/grounder.py @@ -82,19 +82,21 @@ def locate( # appliance). The replayer refuses to wire an egress-capable component unless the # operator explicitly opts in (``allow_model_grounding``), and the run report # flags any run where a screenshot could leave the box. Local, in-process -# grounders (Null / OCR-anchoring) carry ``MAY_EGRESS = False``. +# grounders (Null / OCR-anchoring) carry ``MAY_EGRESS = False``; a component +# without the marker is unknown, and unknown counts as egress. def component_may_egress(component: object) -> bool: """Whether a grounder / identity-VLM / state-verifier can send a screenshot - off the box. Reads the component's ``MAY_EGRESS`` marker (default False for - an unmarked stub / local component); a :class:`FallbackGrounder` is egress - if ANY chained grounder is.""" + off the box. Reads the component's ``MAY_EGRESS`` marker. Only an explicit + ``MAY_EGRESS = False`` makes a component local; an unmarked one may egress + (fail closed). A :class:`FallbackGrounder` is egress if ANY chained + grounder is.""" if component is None: return False if isinstance(component, FallbackGrounder): return any(component_may_egress(g) for g in component._grounders) - return bool(getattr(component, "MAY_EGRESS", False)) + return getattr(component, "MAY_EGRESS", True) is not False class NullGrounder: @@ -599,7 +601,17 @@ def __init__(self, model: str = _DEFAULT_MODEL, client: object = None) -> None: "Install it with: pip install 'openadapt-flow[grounder]'" ) from exc self._model = model - self._client = client if client is not None else anthropic.Anthropic() + # One locate is one send: the SDK's own retries (two by default) would + # resend the frame behind one egress-ledger line and one counted call. + if client is None: + client = anthropic.Anthropic(max_retries=0) + else: + with_options = getattr(client, "with_options", None) + if callable(with_options) and isinstance( + getattr(client, "max_retries", None), int + ): + client = with_options(max_retries=0) + self._client = client self._outbound = _OutboundScreen(None) def locate( diff --git a/packages/flow/openadapt_flow/runtime/identity_vlm.py b/packages/flow/openadapt_flow/runtime/identity_vlm.py index dd6a0e79d8..29dad3425a 100644 --- a/packages/flow/openadapt_flow/runtime/identity_vlm.py +++ b/packages/flow/openadapt_flow/runtime/identity_vlm.py @@ -252,6 +252,9 @@ class MLXIdentityVLM: O/0 collapse surface, ~0.8s/call). The model loads lazily on first call. """ + # In process: the crops never leave this machine. + MAY_EGRESS = False + def __init__(self, model_name: str = DEFAULT_MODEL) -> None: self.model_name = model_name self._comparator: Optional[Any] = None diff --git a/packages/flow/openadapt_flow/runtime/model_egress.py b/packages/flow/openadapt_flow/runtime/model_egress.py new file mode 100644 index 0000000000..165a88ab2c --- /dev/null +++ b/packages/flow/openadapt_flow/runtime/model_egress.py @@ -0,0 +1,337 @@ +"""Count model calls by placement and record every frame sent off the box. + +The replayer wraps each model component it is given (grounder, identity VLM, +state verifier) with :meth:`EgressRecorder.wrap`. A wrapped component that may +send a frame off the box (see +:func:`openadapt_flow.runtime.grounder.component_may_egress`) writes one line +to the local egress ledger **before** each call. If that line can't be +written, the call is not made and the component returns its fail-safe answer +(the grounder abstains, the identity VLM says "different", the state verifier +says no), so the step halts. Nothing leaves the box unrecorded, and a halted +run's frames are on the ledger, since each line is written when the frame is +sent. + +The ledger is append-only JSON lines, mode 0600, fsynced per line. A line +holds the frame's SHA-256 and size, the component, the destination host, the +run and the step, and the time. It never holds pixels or screen text. By +default it is ``egress-ledger.jsonl`` next to the run directory, so it covers +every run written under the same runs root; ``OPENADAPT_FLOW_EGRESS_LEDGER`` +names another file. + +Calls are also counted, by placement, onto the step's +:class:`~openadapt_flow.ir.StepResult`: off-box identity-VLM calls in +``identity_vlm_calls``, in-process ones in ``local_identity_vlm_calls``, and +off-box grounder calls (including ones where the grounder abstained) in +``grounder_calls``. The replayer folds the off-box counts into +``RunReport.model_calls`` and the in-process ones into ``local_model_calls``. +""" + +from __future__ import annotations + +import hashlib +import json +import os +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Optional +from urllib.parse import urlsplit + +LEDGER_ENV = "OPENADAPT_FLOW_EGRESS_LEDGER" +LEDGER_NAME = "egress-ledger.jsonl" + + +def append_ledger_line(path: Path, entry: dict[str, Any]) -> None: + """Append one JSON line to ``path`` and fsync it. Raises ``OSError``.""" + + path.parent.mkdir(parents=True, exist_ok=True) + data = (json.dumps(entry, sort_keys=True, separators=(",", ":")) + "\n").encode() + from openadapt_flow.private_file import open_binary + + # Binary: on Windows a plain os.open would write CRLF into the ledger. + fd = open_binary(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600) + try: + while data: + written = os.write(fd, data) + if written <= 0: + raise OSError("the egress ledger append made no progress") + data = data[written:] + os.fsync(fd) + finally: + os.close(fd) + + +def _destination(component: Any) -> str: + """The host a component sends to, or ``"unknown"``. + + Reads the built client the same way the regulated-transport check does + (:func:`openadapt_flow.model_transport.built_endpoint`), so a ``_url`` or an + ``httpx.URL`` base is recorded too. + """ + + from openadapt_flow.model_transport import built_endpoint + + url = built_endpoint(component) + if url: + try: + host = urlsplit(url if "//" in url else f"//{url}").hostname + except ValueError: + host = None + if host: + return host + return "unknown" + + +class EgressRecorder: + """Per-replayer ledger writer and placement-aware call counter.""" + + def __init__(self) -> None: + self.ledger_path: Optional[Path] = None + self.run_ref: Optional[str] = None + self.step_id: Optional[str] = None + #: Every ledger line this recorder wrote. + self.entries: list[dict[str, Any]] = [] + self._pending = { + "identity_vlm_calls": 0, + "local_identity_vlm_calls": 0, + "grounder_calls": 0, + } + + def bind_run(self, run_dir: Path, run_id: Optional[str] = None) -> None: + """Point the ledger at this run (call before the run sends anything).""" + + override = os.environ.get(LEDGER_ENV, "").strip() + run_dir = Path(run_dir) + self.ledger_path = Path(override) if override else run_dir.parent / LEDGER_NAME + self.run_ref = run_id or run_dir.name + # Counts a raised step never drained belong to the aborted run (its + # frames are on the ledger); they never land on this run's first step. + self._pending = dict.fromkeys(self._pending, 0) + + def admit(self, kind: str, component: Any, *frames: bytes) -> bool: + """Record a frame about to leave the box. False means: don't send.""" + + entry = { + "at": datetime.now(timezone.utc).isoformat(), + "run": self.run_ref, + "step": self.step_id, + "component": kind, + "destination": _destination(component), + "frames": [ + {"sha256": hashlib.sha256(f).hexdigest(), "bytes": len(f)} + for f in frames + if isinstance(f, (bytes, bytearray)) + ], + } + # No run bound (a replayer driven outside ``run``): only the ledger + # ``OPENADAPT_FLOW_EGRESS_LEDGER`` names will do; with none, don't send. + path = self.ledger_path + if path is None and os.environ.get(LEDGER_ENV, "").strip(): + path = Path(os.environ[LEDGER_ENV].strip()) + if path is None: + return False + try: + append_ledger_line(path, entry) + except OSError: + return False + self.entries.append(entry) + return True + + def count(self, field: str) -> None: + self._pending[field] += 1 + + def drain(self, result: Any) -> None: + """Move the calls counted since the last drain onto ``result``.""" + + if result is None: + return + for field, n in self._pending.items(): + if n: + setattr(result, field, getattr(result, field) + n) + self._pending[field] = 0 + + def wrap(self, kind: str, component: Any) -> Any: + """``component`` wrapped for recording, or as is when nothing to do.""" + + from openadapt_flow.runtime.grounder import ( + FallbackGrounder, + component_may_egress, + ) + + if component is None: + return None + if isinstance(component, _Wrapped) and component._recorder is self: + return component # already wrapped here: never ledger a send twice + if isinstance(component, FallbackGrounder): + return FallbackGrounder([self.wrap(kind, g) for g in component._grounders]) + off_box = component_may_egress(component) + if kind == "identity_vlm": + return _IdentityVLM(self, component, off_box) + if not off_box: + return component + if kind == "grounder": + return _Grounder(self, component) + return _StateVerifier(self, component) + + +class _Wrapped: + MAY_EGRESS: bool + + def __init__(self, recorder: EgressRecorder, inner: Any) -> None: + self._recorder = recorder + self._inner = inner + + def __getattr__(self, name: str) -> Any: + return getattr(self._inner, name) + + +class _Grounder(_Wrapped): + MAY_EGRESS = True + + def locate(self, screen_png: bytes, intent: str, ocr_text: Optional[str] = None): + if not self._recorder.admit("grounder", self._inner, screen_png): + return None + self._recorder.count("grounder_calls") + return self._inner.locate(screen_png, intent, ocr_text) + + +class _IdentityVLM(_Wrapped): + def __init__(self, recorder: EgressRecorder, inner: Any, off_box: bool) -> None: + super().__init__(recorder, inner) + self.MAY_EGRESS = off_box + + def same_or_different(self, recorded_png: bytes, live_png: bytes) -> str: + if self.MAY_EGRESS: + if not self._recorder.admit( + "identity_vlm", self._inner, recorded_png, live_png + ): + return "different" + self._recorder.count("identity_vlm_calls") + else: + self._recorder.count("local_identity_vlm_calls") + return self._inner.same_or_different(recorded_png, live_png) + + +class _StateVerifier(_Wrapped): + MAY_EGRESS = True + + def holds(self, screenshot: bytes, expected_state: str) -> bool: + if not self._recorder.admit("state_verifier", self._inner, screenshot): + return False + return self._inner.holds(screenshot, expected_state) + + +def _grounder_resolution(result: Any, local: bool) -> bool: + res = getattr(result, "resolution", None) + return bool( + result.ok + and res is not None + and res.rung == "grounder" + and (res.grounder_model == "local") is local + ) + + +def model_calls_off_box(result: Any) -> int: + """Model calls on ``result`` that may have sent a frame off the box. + + Drift-oracle calls, off-box identity-VLM calls, and grounder calls. The + recorder counts every off-box grounder call, including abstentions and + calls on failed steps; a result built elsewhere (no recorder count) still + counts its grounder resolution, as before. + """ + + return int( + result.drift_oracle_calls + + result.identity_vlm_calls + + max(result.grounder_calls, int(_grounder_resolution(result, local=False))) + ) + + +def model_calls_in_process(result: Any) -> int: + """Model calls on ``result`` that ran in process (no frame left the box).""" + + return int( + _grounder_resolution(result, local=True) + result.local_identity_vlm_calls + ) + + +class ModelComponentMixin: + """Wrap model components on every assignment for fail-closed egress recording.""" + + @property + def _egress(self) -> EgressRecorder: + """The egress recorder, created on first use when ``__init__`` didn't run. + + Every assignment to ``grounder``, ``identity_vlm`` or + ``state_verifier`` goes through :meth:`_set_model_component`, which + wraps the component with this recorder. A replayer built without + ``__init__`` (``Replayer.__new__``, a stubbed constructor) therefore + gets its recorder here, at the first assignment or call. An unbound + recorder admits nothing unless ``OPENADAPT_FLOW_EGRESS_LEDGER`` names + a ledger, so an off-box call made outside ``run`` is refused. + """ + + recorder = self.__dict__.get("_egress_recorder") + if recorder is None: + recorder = EgressRecorder() + self.__dict__["_egress_recorder"] = recorder + return recorder + + def _get_model_component(self, kind: str) -> Any: + try: + return self.__dict__["_model_" + kind] + except KeyError: + raise AttributeError(kind) from None + + def _set_model_component(self, kind: str, component: Any) -> None: + """Wrap ``component`` for recording and store it, at any time. + + Assigning a component after construction gets the same treatment as + passing it to ``__init__``: one that may send a frame off the box + needs ``allow_model_grounding`` (else :class:`EgressNotPermitted`), + marks the run as one whose screenshots may leave the box, and is + ledgered and counted on every call. + """ + + from openadapt_flow.runtime.grounder import component_may_egress + from openadapt_flow.runtime.replay._shared import EgressNotPermitted + + if component_may_egress(component): + if not self.__dict__.get("allow_model_grounding", False): + raise EgressNotPermitted( + f"refusing to wire an egress-capable {kind} that could " + "send a screenshot off the box: pass " + "allow_model_grounding=True (CLI: --allow-model-grounding) " + "to opt in explicitly." + ) + self.__dict__["_screenshots_may_leave_box"] = True + self.__dict__["_model_" + kind] = self._egress.wrap(kind, component) + + @property + def grounder(self) -> Any: + """The grounder, wrapped for egress recording on every assignment.""" + + return self._get_model_component("grounder") + + @grounder.setter + def grounder(self, component: Any) -> None: + self._set_model_component("grounder", component) + + @property + def identity_vlm(self) -> Any: + """The identity VLM, wrapped for egress recording on every assignment.""" + + return self._get_model_component("identity_vlm") + + @identity_vlm.setter + def identity_vlm(self, component: Any) -> None: + self._set_model_component("identity_vlm", component) + + @property + def state_verifier(self) -> Any: + """The state verifier, wrapped for egress recording on every assignment.""" + + return self._get_model_component("state_verifier") + + @state_verifier.setter + def state_verifier(self, component: Any) -> None: + self._set_model_component("state_verifier", component) diff --git a/packages/flow/openadapt_flow/runtime/replayer.py b/packages/flow/openadapt_flow/runtime/replayer.py index 00bc0cfcb0..276192a8b1 100644 --- a/packages/flow/openadapt_flow/runtime/replayer.py +++ b/packages/flow/openadapt_flow/runtime/replayer.py @@ -246,6 +246,12 @@ from openadapt_flow.runtime.known_ids import ( lookalike_class as known_ids_lookalike_class, ) +from openadapt_flow.runtime.model_egress import ( + EgressRecorder, # noqa: F401 + ModelComponentMixin, + model_calls_in_process, + model_calls_off_box, +) from openadapt_flow.runtime.program_predicates import ( evaluate_program_predicate, exact_png_size, @@ -354,7 +360,10 @@ class Replayer( - QualificationFaultInjection, AssetsHealingAndEvidence, SettlingAndInterstitials + QualificationFaultInjection, + AssetsHealingAndEvidence, + SettlingAndInterstitials, + ModelComponentMixin, ): """Replays a Workflow against a Backend using injected vision. @@ -613,6 +622,8 @@ def __init__( # is always populated by the time replay runs; typed Any (a namespace-like # facade exposing find_template/ocr/wait_settled/...). self.vision: Any = vision + # Frames sent off the box are ledgered and counted by placement. + self.__dict__["_egress_recorder"] = EgressRecorder() self.grounder = grounder # Whether the deterministic structural ACTION rung (top of the ladder) # may run. True (default) = product behavior: on a structure-bearing @@ -818,11 +829,9 @@ def __init__( self._identity_input_looks = False self._identity_look_bindings: dict[str, looks_mod.LookBinding] = {} # Optional VLM drift-oracle (state-verifier), OFF by default. When set, - # it may CONFIRM a render-drift-sensitive postcondition that - # deterministically false-failed (the same heal-under-drift the - # resolution ladder does for click targets). VETO-SAFE: it only ever - # rescues on a confident "yes"; "no"/"uncertain"/outage keep the halt, - # and it never touches structural or text_absent postconditions. + # it is asked about a render-drift-sensitive postcondition that failed + # deterministically. Its "yes" is a hint for the person who reviews + # the halt; the postcondition stays failed. self.state_verifier = state_verifier self.poll_interval_s = poll_interval_s if not math.isfinite(settle_readiness_timeout_s) or ( @@ -1218,6 +1227,7 @@ def run( before they are written, and durable checkpoints use the same key. No plaintext of the bundle or of the live screen reaches the disk. """ + self._egress.bind_run(run_dir, run_id) return run_with_output( self, workflow, @@ -3610,28 +3620,11 @@ def _account_result( @staticmethod def _result_model_calls(result: StepResult) -> int: - return int( - result.drift_oracle_calls - + ( - 1 - if ( - result.ok - and result.resolution is not None - and result.resolution.rung == "grounder" - and result.resolution.grounder_model != "local" - ) - else 0 - ) - ) + return model_calls_off_box(result) @staticmethod def _result_local_model_calls(result: StepResult) -> int: - return int( - result.ok - and result.resolution is not None - and result.resolution.rung == "grounder" - and result.resolution.grounder_model == "local" - ) + return model_calls_in_process(result) def _initial_external_network_calls( self, prior: Literal["none", "observed", "unknown"] @@ -6949,11 +6942,13 @@ def _run_step(self, step: Step, **kwargs: Any) -> StepResult: timer, previous = step_timing.start_step() result: Optional[StepResult] = None + self._egress.step_id = step.id try: result = self._run_step_timed(step, **kwargs) return result finally: step_timing.end_step(previous) + self._egress.drain(result) if result is not None: result.timings = timer.result_ms(result.elapsed_ms or None) @@ -8310,10 +8305,10 @@ def _run_step_on_active_surface( for r in result.postcondition_drift_rescues ) print( - " drift-oracle: " + " drift-oracle hint: the VLM says " f"{len(result.postcondition_drift_rescues)}" - " postcondition(s) confirmed by VLM under render " - "drift — " + rescued + " failed postcondition(s) hold (render drift?); " + "they stay failed for a person to review — " + rescued ) if not postconditions_ok: if selection_error is not None: @@ -10099,6 +10094,7 @@ def _identity_gate_error( step, resolution, frame_png, params, workflow, bundle_dir ) ) + self._egress.drain(result) if ( check.status in {"verified", "mismatch"} and check.mode == "pixel" @@ -17758,9 +17754,9 @@ def _postcondition_confirms_a_write( :func:`transaction.classify_transaction_outcome` reports ``RECONCILIATION_REQUIRED`` for the halted run. - Read-only and navigation steps keep the drift-oracle rescue. A wrong - "yes" there lets the run reach the next step, which still runs its own - identity, risk, and postcondition checks before it acts. + On read-only and navigation steps the drift oracle is asked, but its + "yes" is only a hint for the person who reviews the halt (see + :meth:`_drift_oracle_rescue`): the postcondition stays failed. """ if step.risk_review_required: return True @@ -17772,23 +17768,21 @@ def _drift_oracle_rescue( frame_png: bytes, result: Optional[StepResult], ) -> list[Any]: - """Give each deterministically-failed, render-drift-sensitive - postcondition one confirmation pass through the VLM state-verifier. + """Ask the VLM state-verifier about each deterministically-failed, + render-drift-sensitive postcondition, as a hint for the reviewer. - VETO-SAFE by construction: + A model "yes" never clears a failed postcondition: every one stays + failed, so the step halts and goes to a person. A "yes" is recorded on + ``result.postcondition_drift_rescues`` (and printed) so the reviewer + sees that the failure may be render drift. * The caller never invokes this on an irreversible or effect-bearing step (see :meth:`_postcondition_confirms_a_write`). - * Only ``text_present`` and ``region_stable`` are eligible — the kinds - a theme/scale/font re-render can legitimately break. Structural - postconditions (``url_changed`` etc.) and ``text_absent`` are NEVER - rescued: those failures are real, not render drift. - * A postcondition is rescued ONLY on a confident ``"yes"``; ``"no"``, - ``"uncertain"``, and any appliance outage keep it failed (halt). - * Every call and every rescue is recorded on ``result`` for the report - (and counted as a model call), so a rescue is auditable, never silent. - - Returns the postconditions that remain failed after the pass. + * Only ``text_present`` and ``region_stable`` are asked about — the + kinds a theme/scale/font re-render can legitimately break. + * Every call is recorded on ``result`` and counted as a model call. + + Returns the postconditions that remain failed: all of ``failed_pcs``. """ assert self.state_verifier is not None # guaranteed by the caller (line ~2618) survivors: list[Any] = [] @@ -17803,13 +17797,11 @@ def _drift_oracle_rescue( confirmed = self.state_verifier.holds(frame_png, expected) except Exception: confirmed = False # fail-safe: any error keeps the halt - if confirmed: - if result is not None: - result.postcondition_drift_rescues.append( - self._describe_postcondition(pc) - ) - else: - survivors.append(pc) + if confirmed and result is not None: + result.postcondition_drift_rescues.append( + self._describe_postcondition(pc) + ) + survivors.append(pc) # a model "yes" is a hint, never a pass return survivors @staticmethod diff --git a/packages/flow/openadapt_flow/services/vlm_service/app.py b/packages/flow/openadapt_flow/services/vlm_service/app.py index c10ad6fdf1..dff3f39b24 100644 --- a/packages/flow/openadapt_flow/services/vlm_service/app.py +++ b/packages/flow/openadapt_flow/services/vlm_service/app.py @@ -102,7 +102,13 @@ def create_app( backend is constructed from ``config.backend`` and loaded on startup. """ cfg = config or ServiceConfig.from_env() - bk = backend if backend is not None else build_backend(cfg.backend, cfg.model) + if backend is not None: + bk = backend + elif (cfg.backend or "stub").lower() == "vllm": + # VLM_VLLM_URL names the vLLM server; only that backend takes it. + bk = build_backend(cfg.backend, cfg.model, base_url=cfg.vllm_url) + else: + bk = build_backend(cfg.backend, cfg.model) def _handle(payload: object) -> object: """Blocking per-request work; runs in the batcher's worker thread.""" diff --git a/packages/flow/tests/fixtures/schema_surface/openadapt_flow.ir.json b/packages/flow/tests/fixtures/schema_surface/openadapt_flow.ir.json index c3806dd5d9..57f9f32d65 100644 --- a/packages/flow/tests/fixtures/schema_surface/openadapt_flow.ir.json +++ b/packages/flow/tests/fixtures/schema_surface/openadapt_flow.ir.json @@ -33924,6 +33924,24 @@ "title": "Drift Oracle Calls", "type": "integer" }, + "identity_vlm_calls": { + "default": 0, + "minimum": 0, + "title": "Identity Vlm Calls", + "type": "integer" + }, + "local_identity_vlm_calls": { + "default": 0, + "minimum": 0, + "title": "Local Identity Vlm Calls", + "type": "integer" + }, + "grounder_calls": { + "default": 0, + "minimum": 0, + "title": "Grounder Calls", + "type": "integer" + }, "postcondition_page_scale": { "anyOf": [ { @@ -47739,6 +47757,24 @@ "title": "Drift Oracle Calls", "type": "integer" }, + "identity_vlm_calls": { + "default": 0, + "minimum": 0, + "title": "Identity Vlm Calls", + "type": "integer" + }, + "local_identity_vlm_calls": { + "default": 0, + "minimum": 0, + "title": "Local Identity Vlm Calls", + "type": "integer" + }, + "grounder_calls": { + "default": 0, + "minimum": 0, + "title": "Grounder Calls", + "type": "integer" + }, "postcondition_page_scale": { "anyOf": [ { diff --git a/packages/flow/tests/test_drift_oracle.py b/packages/flow/tests/test_drift_oracle.py index 7a38db90fe..9a2e1aef8d 100644 --- a/packages/flow/tests/test_drift_oracle.py +++ b/packages/flow/tests/test_drift_oracle.py @@ -1,14 +1,16 @@ -"""Drift-oracle: the optional VLM state-verifier that may CONFIRM a -render-drift-sensitive postcondition which deterministically false-failed. - -Veto-safe by construction — these tests pin that: -* only a confident "yes" rescues; "no"/"uncertain"/outage keep the halt, -* structural / text_absent postconditions are NEVER rescued, -* every call and rescue is recorded on the StepResult for the report, +"""Drift-oracle: the optional VLM state-verifier asked about a +render-drift-sensitive postcondition which failed deterministically. + +Its answer is a hint for the person who reviews the halt, never a pass. These +tests pin that: +* a confident "yes" is recorded as a hint, and the postcondition stays failed; + "no"/"uncertain"/outage record nothing, +* structural / text_absent postconditions are never asked about, +* every call and hint is recorded on the StepResult for the report, * with no verifier configured (the default) behaviour is unchanged, -* an irreversible or effect-bearing step is never rescued: its failed - postcondition stays failed (a run with no handler halts with transaction - outcome RECONCILIATION_REQUIRED), while a navigation step keeps the rescue. +* an irreversible or effect-bearing step never asks the oracle; a run with no + handler halts at a write with transaction outcome RECONCILIATION_REQUIRED, + and a navigation step halts too, with the hint on its result. """ from __future__ import annotations @@ -77,6 +79,8 @@ class _Verifier: """Scripted state-verifier. ``answer`` is 'yes'/'no'/'uncertain' or 'boom' to raise (simulate an outage the client failed to swallow).""" + MAY_EGRESS = True # an appliance verifier: the frame leaves the box + def __init__(self, answer: str): self.answer = answer self.calls = 0 @@ -119,8 +123,13 @@ def _text_present_pc(text: str = "Patient list") -> Postcondition: def _check(vision, verifier, pc, tmp_path, step=None): rp = Replayer( - _Backend(), vision=vision, state_verifier=verifier, poll_interval_s=0.0 + _Backend(), + vision=vision, + state_verifier=verifier, + allow_model_grounding=True, + poll_interval_s=0.0, ) + rp._egress.bind_run(tmp_path / "run") # off-box frames need a ledger step = step if step is not None else _step(pc) result = StepResult(step_id=step.id, intent=step.intent, ok=False) ok, _frame, failed = rp._check_postconditions(step, _png(), tmp_path, {}, result) @@ -130,11 +139,11 @@ def _check(vision, verifier, pc, tmp_path, step=None): # -------------------------------------------------------------------------- -def test_confident_yes_rescues_a_drifted_text_postcondition(tmp_path): +def test_confident_yes_is_a_hint_not_a_pass(tmp_path): vision = _Vision(present=set()) # "Patient list" not readable (drift) verifier = _Verifier("yes") ok, failed, result = _check(vision, verifier, _text_present_pc(), tmp_path) - assert ok is True and failed == [] + assert ok is False and failed == ["text_present 'Patient list'"] assert result.postcondition_drift_rescues == ["text_present 'Patient list'"] assert result.drift_oracle_calls == 1 assert verifier.calls == 1 @@ -179,7 +188,7 @@ def test_text_absent_is_never_rescued(tmp_path): assert result.drift_oracle_calls == 0 -def test_region_stable_is_rescuable(tmp_path): +def test_region_stable_yes_is_only_a_hint(tmp_path): pc = Postcondition( kind=PostconditionKind.REGION_STABLE, region=(10, 10, 40, 20), @@ -187,7 +196,8 @@ def test_region_stable_is_rescuable(tmp_path): timeout_s=0.0, ) ok, failed, result = _check(_Vision(set()), _Verifier("yes"), pc, tmp_path) - assert ok is True and failed == [] + assert ok is False and failed + assert len(result.postcondition_drift_rescues) == 1 assert result.drift_oracle_calls == 1 @@ -278,7 +288,11 @@ def _run(tmp_path, steps, verifier, workflow=None): ] backend = FakeBackend() report = Replayer( - backend, vision=vision, state_verifier=verifier, poll_interval_s=0.0 + backend, + vision=vision, + state_verifier=verifier, + allow_model_grounding=True, + poll_interval_s=0.0, ).run( workflow if workflow is not None else Workflow(name="wf", steps=steps), bundle_dir=bundle, @@ -289,7 +303,6 @@ def _run(tmp_path, steps, verifier, workflow=None): def test_run_halts_with_reconciliation_when_oracle_says_yes_on_a_write(tmp_path): verifier = _Verifier("yes") - navigate = _step(_text_present_pc("Claims"), step_id="nav") submit = _step( _text_present_pc("Claim submitted"), step_id="submit", @@ -298,13 +311,10 @@ def test_run_halts_with_reconciliation_when_oracle_says_yes_on_a_write(tmp_path) risk="irreversible", ) after = _step(_text_present_pc("Done"), step_id="after") - report, backend = _run(tmp_path, [navigate, submit, after], verifier) + report, backend = _run(tmp_path, [submit, after], verifier) assert report.success is False - nav_result, submit_result = report.results[:2] - # The navigation step was rescued as before. - assert nav_result.ok is True - assert nav_result.postcondition_drift_rescues == ["text_present 'Claims'"] + (submit_result,) = report.results # The write was delivered, its screen check failed, and the oracle was # never asked. assert submit_result.ok is False @@ -312,10 +322,10 @@ def test_run_halts_with_reconciliation_when_oracle_says_yes_on_a_write(tmp_path) assert submit_result.drift_oracle_calls == 0 assert submit_result.postcondition_drift_rescues == [] assert "Postconditions failed" in (submit_result.error or "") - assert verifier.calls == 1 # the navigation step only + assert verifier.calls == 0 # Fail-closed: the run stops at the write and never reaches the next step. - assert [r.step_id for r in report.results] == ["nav", "submit"] - assert len(backend.actions) == 2 + assert [r.step_id for r in report.results] == ["submit"] + assert len(backend.actions) == 1 # The write may have landed, so a person checks the record. The run never # says it stopped before saving. assert report.transaction_outcome == "RECONCILIATION_REQUIRED" @@ -325,7 +335,7 @@ def test_run_halts_with_reconciliation_when_oracle_says_yes_on_a_write(tmp_path) assert "Stopped before saving" not in plain.label + plain.meaning -def test_run_keeps_the_rescue_on_navigation_steps(tmp_path): +def test_run_halts_on_a_navigation_step_the_oracle_says_holds(tmp_path): verifier = _Verifier("yes") steps = [ _step(_text_present_pc("Patient list"), step_id="nav1"), @@ -338,14 +348,18 @@ def test_run_keeps_the_rescue_on_navigation_steps(tmp_path): ] report, backend = _run(tmp_path, steps, verifier) - assert report.success is True - assert [r.postcondition_drift_rescues for r in report.results] == [ - ["text_present 'Patient list'"], - ["text_present 'Search'"], + # The model's "yes" is a hint on the halted step, not a pass: the run + # stops at the first step for a person to review. + assert report.success is False + assert [r.step_id for r in report.results] == ["nav1"] + assert report.results[0].ok is False + assert report.results[0].postcondition_drift_rescues == [ + "text_present 'Patient list'" ] - assert [r.drift_oracle_calls for r in report.results] == [1, 1] - assert verifier.calls == 2 - assert len(backend.actions) == 2 + assert report.results[0].drift_oracle_calls == 1 + assert report.model_calls == 1 + assert verifier.calls == 1 + assert len(backend.actions) == 1 def _program_with_handler(step: Step) -> Workflow: diff --git a/packages/flow/tests/test_execution_profiles.py b/packages/flow/tests/test_execution_profiles.py index 5fb2e4eec2..741151ddbf 100644 --- a/packages/flow/tests/test_execution_profiles.py +++ b/packages/flow/tests/test_execution_profiles.py @@ -281,6 +281,9 @@ def wait_settled_result(self, backend, **kwargs): class _CountingStateVerifier: + # A remote verifier: its calls are the run's external network evidence. + MAY_EGRESS = True + def __init__(self, *, holds: bool) -> None: self.result = holds self.calls = 0 @@ -2873,6 +2876,7 @@ def test_resume_preserves_failed_leg_model_and_network_evidence(tmp_path): FakeBackend(), vision=_ReadyVision(), state_verifier=verifier, + allow_model_grounding=True, governed_authorization=authorization, durable=True, require_settled=True, diff --git a/packages/flow/tests/test_local_vlm_gold_crop.py b/packages/flow/tests/test_local_vlm_gold_crop.py index 8e33c0661a..57a61ae3d6 100644 --- a/packages/flow/tests/test_local_vlm_gold_crop.py +++ b/packages/flow/tests/test_local_vlm_gold_crop.py @@ -270,6 +270,8 @@ def compare(self, crop_a: bytes, crop_b: bytes) -> IdentityVerdict: class _FakeLocalIdentity: + MAY_EGRESS = False # in process: no frame leaves the box + def __init__(self, answer: str): self.answer = answer diff --git a/packages/flow/tests/test_model_failclosed.py b/packages/flow/tests/test_model_failclosed.py new file mode 100644 index 0000000000..bf8ebd7331 --- /dev/null +++ b/packages/flow/tests/test_model_failclosed.py @@ -0,0 +1,712 @@ +"""Remote-model offload review (Nov 21): fail-open and egress reproductions. + +Each test pins the fail-closed behaviour the review asks for. On origin/main +576f87b41 they fail; the fixes on ``claude/model-failclosed`` make them pass. + +1. A model "yes" must never clear a failed postcondition, on any step. +2. A model component with no ``MAY_EGRESS`` marker counts as egress. +3. Identity-VLM calls count as model calls, and identity crops sent off the + box never produce ``external_network_calls == "none"``. +4. The VLM service passes ``VLM_VLLM_URL`` to the vLLM backend. +5. The regulated profile refuses a non-loopback cleartext (``http://``) + appliance. +6. A pinned model that is unavailable never falls back to another placement + or model. +7. Every frame sent off the box is on a local append-only ledger, written + before the call, halted runs included; no ledger line, no call. +""" + +from __future__ import annotations + +import io +from datetime import datetime, timezone +from types import SimpleNamespace + +import pytest +from PIL import Image + +from openadapt_flow.deployment import GroundingModelConfig, RuntimeSection +from openadapt_flow.ir import ( + Anchor, + Postcondition, + PostconditionKind, + Resolution, + RunReport, + Step, + StepResult, + Workflow, +) +from openadapt_flow.runtime.grounder import component_may_egress +from openadapt_flow.runtime.remote_vlm import ( + RemoteGrounder, + RemoteIdentityVLM, + RemoteStateVerifier, +) +from openadapt_flow.runtime.replayer import EgressNotPermitted, Replayer +from tests.test_drift_oracle import _Backend, _png, _step, _Vision +from tests.test_replayer import FakeBackend + +# -------------------------------------------------------------------------- +# 1. Drift rescue: a model "yes" is a hint, never a pass. +# -------------------------------------------------------------------------- + + +class _Verifier: + """An appliance state-verifier (marked egress) with a scripted answer.""" + + MAY_EGRESS = True + + def __init__(self, answer: str) -> None: + self.answer = answer + self.calls = 0 + + def holds(self, screenshot, expected_state) -> bool: + self.calls += 1 + return self.answer == "yes" + + +def _check(vision, verifier, pc, tmp_path, step=None): + rp = Replayer( + _Backend(), + vision=vision, + state_verifier=verifier, + allow_model_grounding=True, + poll_interval_s=0.0, + ) + step = step if step is not None else _step(pc) + result = StepResult(step_id=step.id, intent=step.intent, ok=False) + ok, _frame, failed = rp._check_postconditions(step, _png(), tmp_path, {}, result) + return ok, failed, result + + +def test_drift_yes_does_not_clear_failed_text_postcondition_on_navigation( + tmp_path, +): + pc = Postcondition( + kind=PostconditionKind.TEXT_PRESENT, text="Patient list", timeout_s=0.0 + ) + ok, failed, _result = _check(_Vision(present=set()), _Verifier("yes"), pc, tmp_path) + assert ok is False + assert failed + + +def test_drift_yes_does_not_clear_failed_region_postcondition_on_read_only( + tmp_path, +): + pc = Postcondition( + kind=PostconditionKind.REGION_STABLE, + region=(0, 0, 10, 10), + phash="ff", + timeout_s=0.0, + ) + step = _step(pc, intent="view the chart", label="Chart") + ok, failed, _result = _check( + _Vision(present=set()), _Verifier("yes"), pc, tmp_path, step=step + ) + assert ok is False + assert failed + + +# -------------------------------------------------------------------------- +# 2. Unmarked components count as egress. +# -------------------------------------------------------------------------- + + +class _UnmarkedGrounder: + """A third-party grounder that never declares ``MAY_EGRESS``.""" + + def locate(self, screen_png, intent, ocr_text=None): + return None + + +def test_unmarked_component_counts_as_egress(): + assert component_may_egress(_UnmarkedGrounder()) is True + + +def test_unmarked_grounder_requires_explicit_egress_optin(): + with pytest.raises(EgressNotPermitted): + Replayer(FakeBackend(), grounder=_UnmarkedGrounder()) + + +# -------------------------------------------------------------------------- +# 3. Identity-VLM calls are model calls; off-box crops are never "none". +# -------------------------------------------------------------------------- + + +def _crop_png() -> bytes: + buf = io.BytesIO() + Image.new("RGB", (40, 12), (250, 250, 250)).save(buf, format="PNG") + return buf.getvalue() + + +class _OffBoxIdentityVLM: + """An appliance identity VLM: crops leave the box on every call.""" + + MAY_EGRESS = True + + def __init__(self, verdict: str) -> None: + self.verdict = verdict + self.calls = 0 + + def same_or_different(self, recorded_png, live_png): + self.calls += 1 + return self.verdict + + +def _identity_step() -> tuple[Step, Workflow, Resolution]: + anchor = Anchor( + template="t.png", + region=(0, 0, 40, 12), + click_point=(20, 6), + # A glyph-confusable identifier, so the VLM tier is consulted. + context_text="Smith AC50061", + ) + step = Step( + id="open_record", + intent="open record", + action="click", + anchor=anchor, + risk="irreversible", + ) + workflow = Workflow(name="identity_vlm_egress", params={}, steps=[step]) + res = Resolution(rung="ocr", point=(20, 6), confidence=0.9, elapsed_ms=1.0) + return step, workflow, res + + +@pytest.mark.parametrize("verdict", ["different", "same"]) +def test_identity_vlm_call_counts_as_model_call(monkeypatch, tmp_path, verdict): + vlm = _OffBoxIdentityVLM(verdict) + rp = Replayer(FakeBackend(), identity_vlm=vlm, allow_model_grounding=True) + rp._egress.bind_run(tmp_path / "run") + crop = _crop_png() + monkeypatch.setattr(rp, "_identifier_crops", lambda *a, **k: (crop, crop)) + step, workflow, res = _identity_step() + result = StepResult(step_id=step.id, intent=step.intent, ok=False) + rp._identity_gate_error(step, res, crop, {}, workflow, tmp_path, result) + assert vlm.calls == 1, "precondition: the identity VLM was consulted" + assert Replayer._result_model_calls(result) >= 1 + + +def test_off_box_identity_crops_never_report_no_external_calls(monkeypatch, tmp_path): + from openadapt_flow.execution_profiles import _external_network_call_state + + vlm = _OffBoxIdentityVLM("different") + rp = Replayer(FakeBackend(), identity_vlm=vlm, allow_model_grounding=True) + rp._egress.bind_run(tmp_path / "run") + crop = _crop_png() + monkeypatch.setattr(rp, "_identifier_crops", lambda *a, **k: (crop, crop)) + step, workflow, res = _identity_step() + result = StepResult(step_id=step.id, intent=step.intent, ok=False) + rp._identity_gate_error(step, res, crop, {}, workflow, tmp_path, result) + assert vlm.calls == 1, "precondition: identity crops left the box" + + # A loopback web run (the bundled tutorial's shape) whose identity crops + # went to an off-box appliance. + report = RunReport( + workflow_name=workflow.name, + started_at=datetime.now(timezone.utc).isoformat(), + execution_origin="http://127.0.0.1:5001", + execution_entry_url="http://127.0.0.1:5001/", + execution_target_kind="web", + screenshots_may_leave_box=True, + steps=[result], + ) + report.model_calls = Replayer._result_model_calls(result) + assert _external_network_call_state(report) != "none" + + +# -------------------------------------------------------------------------- +# 4. The VLM service honours VLM_VLLM_URL. +# -------------------------------------------------------------------------- + + +def test_vlm_service_passes_vllm_url_to_backend(monkeypatch): + pytest.importorskip("fastapi") + import openadapt_flow.services.vlm_service.app as app_mod + from openadapt_flow.services.vlm_service.config import ServiceConfig + + seen: dict = {} + + def _capture(backend, model=None, **kwargs): + seen.update(backend=backend, model=model, **kwargs) + from openadapt_flow.services.vlm_service.backends import StubBackend + + return StubBackend() + + monkeypatch.setattr(app_mod, "build_backend", _capture) + monkeypatch.setenv("VLM_BACKEND", "vllm") + monkeypatch.setenv("VLM_VLLM_URL", "http://gpu-box.internal:9000/v1") + app_mod.create_app(ServiceConfig.from_env()) + assert seen.get("base_url") == "http://gpu-box.internal:9000/v1" + + +# -------------------------------------------------------------------------- +# 5 and 6. build_replayer wiring (no real Replayer, no real OCR rung). +# -------------------------------------------------------------------------- + + +@pytest.fixture() +def wiring(monkeypatch): + captured: dict = {} + + import openadapt_flow.runtime as rt + import openadapt_flow.runtime.grounder as gmod + + class _FakeReplayer: + def __init__(self, backend, **kwargs): + captured["replayer_kwargs"] = kwargs + + def _fake_build_grounder(fallback=None, **_kwargs): + captured["fallback"] = fallback + return fallback + + monkeypatch.setattr(rt, "Replayer", _FakeReplayer) + monkeypatch.setattr(gmod, "build_grounder", _fake_build_grounder) + monkeypatch.delenv("OPENADAPT_FLOW_VLM_URL", raising=False) + monkeypatch.delenv("OPENADAPT_FLOW_VLM_TOKEN", raising=False) + return captured + + +def _build(*, runtime_config, phi_mode, governed_authorization=None): + from openadapt_flow.deployment import build_replayer + + build_replayer( + object(), + allow_egress=True, + effect_verifier=None, + api_actuator=None, + durable=False, + use_structural=True, + runtime_config=runtime_config, + phi_mode=phi_mode, + governed_authorization=governed_authorization, + ) + + +def _wired_appliance_handles(captured: dict) -> list[str]: + kwargs = captured.get("replayer_kwargs") or {} + wired = [ + name + for name in ("identity_vlm", "state_verifier") + if isinstance(kwargs.get(name), (RemoteIdentityVLM, RemoteStateVerifier)) + ] + if isinstance(captured.get("fallback"), RemoteGrounder): + wired.append("grounder") + return wired + + +def test_regulated_profile_refuses_cleartext_non_loopback_appliance( + wiring, monkeypatch +): + monkeypatch.setenv("OPENADAPT_FLOW_VLM_URL", "http://10.20.30.40:8000") + monkeypatch.setenv("OPENADAPT_FLOW_VLM_TOKEN", "t") + runtime = RuntimeSection(phi_grounding_allowlist=["10.20.30.40"]) + authorization = SimpleNamespace( + execution_profile="regulated", qualification_case_id=None + ) + _build( + runtime_config=runtime, + phi_mode=True, + governed_authorization=authorization, + ) + assert _wired_appliance_handles(wiring) == [] + + +def test_unavailable_pinned_model_never_falls_back_to_appliance(wiring, monkeypatch): + # The operator pinned an openai-compatible model, but it cannot be built + # (no base_url). The on-prem appliance is a different placement and + # model; it must not silently stand in for the pinned one. + monkeypatch.setenv("OPENADAPT_FLOW_VLM_URL", "https://vlm.internal:8443") + runtime = RuntimeSection( + grounding_model=GroundingModelConfig( + enabled=True, provider="openai_compatible", base_url="", model="pinned-m" + ) + ) + _build(runtime_config=runtime, phi_mode=False) + assert not isinstance(wiring.get("fallback"), RemoteGrounder) + + +def test_empty_pinned_model_is_refused_not_defaulted(wiring, monkeypatch, capsys): + from openadapt_flow.deployment import build_model_grounder + + cfg = GroundingModelConfig(enabled=True, provider="anthropic", model=" ") + assert build_model_grounder(cfg) is None + assert "requires a model" in capsys.readouterr().out + + # Wired through build_replayer: no default model, and no appliance either. + monkeypatch.setenv("OPENADAPT_FLOW_VLM_URL", "https://vlm.internal:8443") + _build(runtime_config=RuntimeSection(grounding_model=cfg), phi_mode=False) + assert wiring.get("fallback") is None + + +def test_regulated_profile_keeps_tls_and_loopback_appliances(wiring, monkeypatch): + for url in ("https://10.20.30.40:8443", "http://127.0.0.1:8000"): + wiring.clear() + monkeypatch.setenv("OPENADAPT_FLOW_VLM_URL", url) + runtime = RuntimeSection(phi_grounding_allowlist=["10.20.30.40", "127.0.0.1"]) + authorization = SimpleNamespace( + execution_profile="regulated", qualification_case_id=None + ) + _build( + runtime_config=runtime, + phi_mode=True, + governed_authorization=authorization, + ) + assert _wired_appliance_handles(wiring) == [ + "identity_vlm", + "state_verifier", + "grounder", + ], url + + +@pytest.mark.parametrize( + "url, allowed", + [ + ("https://vlm.internal:8443", True), + ("http://127.0.0.1:8000", True), + ("http://[::1]:8000", True), + ("http://localhost:8000", True), + ("http://10.20.30.40:8000", False), + ("http://localhost.evil.example:8000", False), + ("ftp://vlm.internal", False), + ("vlm.internal:8000", False), + ("", False), + ], +) +def test_regulated_transport_rule(url, allowed): + from openadapt_flow.model_transport import regulated_transport_refusal + + assert (regulated_transport_refusal(url) is None) is allowed + + +def test_appliance_still_backs_an_unpinned_run(wiring, monkeypatch): + monkeypatch.setenv("OPENADAPT_FLOW_VLM_URL", "https://vlm.internal:8443") + _build(runtime_config=RuntimeSection(), phi_mode=False) + assert isinstance(wiring.get("fallback"), RemoteGrounder) + + +# -------------------------------------------------------------------------- +# 7. The egress ledger, and grounder calls that abstained. +# -------------------------------------------------------------------------- + + +class _OffBoxGrounder: + MAY_EGRESS = True + base_url = "https://vlm.internal:8443" + + def __init__(self) -> None: + self.calls = 0 + + def locate(self, screen_png, intent, ocr_text=None): + self.calls += 1 + return None # abstains after the frame was sent + + +def _ledger_lines(path): + import json + + return [json.loads(line) for line in path.read_text().splitlines()] + + +def test_off_box_frame_is_ledgered_before_the_call(tmp_path, monkeypatch): + monkeypatch.delenv("OPENADAPT_FLOW_EGRESS_LEDGER", raising=False) + inner = _OffBoxGrounder() + rp = Replayer(FakeBackend(), grounder=inner, allow_model_grounding=True) + rp._egress.bind_run(tmp_path / "runs" / "r1") + rp._egress.step_id = "s1" + frame = _png() + assert rp.grounder.locate(frame, "open the chart") is None + assert inner.calls == 1 + (line,) = _ledger_lines(tmp_path / "runs" / "egress-ledger.jsonl") + assert line["component"] == "grounder" + assert line["destination"] == "vlm.internal" + assert line["run"] == "r1" and line["step"] == "s1" + import hashlib + + assert line["frames"] == [ + {"sha256": hashlib.sha256(frame).hexdigest(), "bytes": len(frame)} + ] + mode = (tmp_path / "runs" / "egress-ledger.jsonl").stat().st_mode & 0o777 + assert mode == 0o600 + + # The abstaining call still counts as an off-box model call. + result = StepResult(step_id="s1", intent="open the chart", ok=False) + rp._egress.drain(result) + assert result.grounder_calls == 1 + assert Replayer._result_model_calls(result) == 1 + + +def test_no_ledger_line_means_no_call(tmp_path, monkeypatch): + blocker = tmp_path / "not-a-dir" + blocker.write_text("") + monkeypatch.setenv("OPENADAPT_FLOW_EGRESS_LEDGER", str(blocker / "ledger.jsonl")) + inner = _OffBoxGrounder() + vlm = _OffBoxIdentityVLM("same") + verifier = _Verifier("yes") + rp = Replayer( + FakeBackend(), + grounder=inner, + identity_vlm=vlm, + state_verifier=verifier, + allow_model_grounding=True, + ) + rp._egress.bind_run(tmp_path / "run") + crop = _crop_png() + assert rp.grounder.locate(crop, "x") is None + assert rp.identity_vlm.same_or_different(crop, crop) == "different" + assert rp.state_verifier.holds(crop, "x") is False + assert (inner.calls, vlm.calls, verifier.calls) == (0, 0, 0) + + +def test_halted_run_frames_are_on_the_ledger(tmp_path, monkeypatch): + from tests.test_drift_oracle import _run, _text_present_pc + + monkeypatch.delenv("OPENADAPT_FLOW_EGRESS_LEDGER", raising=False) + verifier = _Verifier("yes") + report, _backend = _run( + tmp_path, [_step(_text_present_pc("Patient list"))], verifier + ) + assert report.success is False + (line,) = _ledger_lines(tmp_path / "egress-ledger.jsonl") + assert line["component"] == "state_verifier" + assert line["step"] == "s1" + assert report.model_calls == 1 + + +def test_in_process_identity_vlm_counts_as_local(monkeypatch, tmp_path): + vlm = _OffBoxIdentityVLM("different") + vlm.MAY_EGRESS = False + rp = Replayer(FakeBackend(), identity_vlm=vlm) + crop = _crop_png() + monkeypatch.setattr(rp, "_identifier_crops", lambda *a, **k: (crop, crop)) + step, workflow, res = _identity_step() + result = StepResult(step_id=step.id, intent=step.intent, ok=False) + rp._identity_gate_error(step, res, crop, {}, workflow, tmp_path, result) + assert vlm.calls == 1 + assert Replayer._result_model_calls(result) == 0 + assert Replayer._result_local_model_calls(result) == 1 + assert rp._egress.entries == [] + + +# -------------------------------------------------------------------------- +# 3, receipt side. The model-call rule is split by placement. +# -------------------------------------------------------------------------- + + +def _receipt_report(*, model_calls, local_model_calls, network): + from tests.test_run_receipt import _report + + base = _report() + classes = list(base.outcome_envelope.evidence_classes) + if model_calls: + classes = sorted({*classes, "model"}) + report = _report( + model_calls=model_calls, + outcome_envelope=base.outcome_envelope.model_copy( + update={"evidence_classes": classes, "external_network_calls": network} + ), + ) + report.local_model_calls = local_model_calls + return report + + +def test_receipt_refuses_off_box_calls_with_no_external_calls(): + from openadapt_flow.model_call_evidence import model_call_evidence_error + from openadapt_flow.receipt import build_receipt + + assert model_call_evidence_error(1, ["model"], "none") is not None + with pytest.raises(Exception, match="observed external network"): + build_receipt( + _receipt_report(model_calls=1, local_model_calls=0, network="none") + ) + receipt = build_receipt( + _receipt_report(model_calls=1, local_model_calls=0, network="observed") + ) + assert receipt.model_calls == 1 and receipt.external_network_calls == "observed" + + +def test_receipt_lets_in_process_calls_say_no_external_calls(): + from openadapt_flow.model_call_evidence import model_call_evidence_error + from openadapt_flow.receipt import build_receipt + + assert model_call_evidence_error(0, [], "none") is None + receipt = build_receipt( + _receipt_report(model_calls=0, local_model_calls=2, network="none") + ) + assert receipt.model_calls == 0 + assert receipt.external_network_calls == "none" + assert "model" not in receipt.evidence_classes + + +def test_counts_from_a_raised_step_never_land_on_the_next_run(tmp_path): + from openadapt_flow.runtime.model_egress import EgressRecorder + + recorder = EgressRecorder() + recorder.count("identity_vlm_calls") + recorder.drain(None) # the step raised: no result to put them on + recorder.bind_run(tmp_path / "run-2") + fresh = StepResult(step_id="s1", intent="x", ok=True) + recorder.drain(fresh) + assert fresh.identity_vlm_calls == 0 + + +def test_no_bound_ledger_means_no_off_box_call(monkeypatch): + from openadapt_flow.runtime.model_egress import LEDGER_ENV, EgressRecorder + + monkeypatch.delenv(LEDGER_ENV, raising=False) + recorder = EgressRecorder() + grounder = _OffBoxGrounder() + wrapped = recorder.wrap("grounder", grounder) + assert wrapped.locate(b"frame", "click Save") is None + assert grounder.calls == 0 and recorder.entries == [] + + +def test_model_grounder_checked_at_the_url_its_client_uses(wiring, monkeypatch): + # The Anthropic SDK takes ANTHROPIC_BASE_URL from the environment; the + # regulated check must see that URL, not the empty configured base_url. + pytest.importorskip("anthropic") + monkeypatch.setenv("ANTHROPIC_BASE_URL", "http://10.20.30.40:8080") + monkeypatch.setenv("ANTHROPIC_API_KEY", "test-not-a-key") + monkeypatch.setenv("OPENADAPT_FLOW_SEND_UNSCRUBBED", "wiring unit test") + runtime = RuntimeSection( + profile="regulated", + grounding_model=GroundingModelConfig( + enabled=True, provider="anthropic", model="pinned-m" + ), + ) + _build(runtime_config=runtime, phi_mode=False) + assert wiring.get("fallback") is None + + +def test_each_model_send_is_one_ledgered_counted_call(tmp_path, monkeypatch): + # The Anthropic SDK retries twice by default, so one ledgered, counted call + # could send the same frame three times. The grounder turns retries off: + # three sends must be three ledger lines and three counted calls. + anthropic = pytest.importorskip("anthropic") + import httpx + + from openadapt_flow.runtime.grounder import AnthropicGrounder + from openadapt_flow.runtime.model_egress import LEDGER_ENV, EgressRecorder + + sends = [] + + def overloaded(request): + sends.append(request) + return httpx.Response( + 529, json={"type": "error", "error": {"type": "overloaded_error"}} + ) + + client = anthropic.Anthropic( + api_key="test-not-a-key", + base_url="https://model.example.test", + http_client=httpx.Client(transport=httpx.MockTransport(overloaded)), + ) + assert client.max_retries > 0 # the SDK default this guards against + monkeypatch.setenv("OPENADAPT_FLOW_SEND_UNSCRUBBED", "retry count unit test") + ledger = tmp_path / "egress-ledger.jsonl" + monkeypatch.setenv(LEDGER_ENV, str(ledger)) + recorder = EgressRecorder() + grounder = recorder.wrap( + "grounder", AnthropicGrounder(model="pinned-m", client=client) + ) + for _ in range(3): + with pytest.raises(anthropic.APIStatusError): + grounder.locate(_png(), "click Save") + assert len(sends) == 3 + result = StepResult(step_id="s1", intent="click Save", ok=False) + recorder.drain(result) + assert result.grounder_calls == 3 + lines = _ledger_lines(ledger) + assert len(lines) == 3 + assert {line["destination"] for line in lines} == {"model.example.test"} + + +def test_ledger_names_the_openai_compatible_host(tmp_path, monkeypatch): + from openadapt_flow.runtime.grounder import OpenAICompatibleGrounder + from openadapt_flow.runtime.model_egress import LEDGER_ENV, EgressRecorder + + class _Refusing: + def post(self, url, **kwargs): + return SimpleNamespace(status_code=503) + + monkeypatch.setenv("OPENADAPT_FLOW_SEND_UNSCRUBBED", "host unit test") + ledger = tmp_path / "egress-ledger.jsonl" + monkeypatch.setenv(LEDGER_ENV, str(ledger)) + grounder = EgressRecorder().wrap( + "grounder", + OpenAICompatibleGrounder( + base_url="https://vlm.example.test/v1", model="m", client=_Refusing() + ), + ) + assert grounder.locate(_png(), "click Save") is None + (line,) = _ledger_lines(ledger) + assert line["destination"] == "vlm.example.test" + + +def test_component_assigned_after_first_access_is_ledgered_and_counted( + tmp_path, monkeypatch +): + # Assigning a model component after construction (and after the recorder + # is in use) wraps it exactly as __init__ does, so its send is counted. + monkeypatch.delenv("OPENADAPT_FLOW_EGRESS_LEDGER", raising=False) + rp = Replayer(FakeBackend(), allow_model_grounding=True) + rp._egress.bind_run(tmp_path / "runs" / "r1") + rp._egress.step_id = "s1" + assert rp._screenshots_may_leave_box is False + inner = _OffBoxGrounder() + rp.grounder = inner + rp.grounder = rp.grounder # re-assigning a wrapped component never double-wraps + assert rp.grounder is not inner + assert rp._screenshots_may_leave_box is True + assert rp.grounder.locate(_png(), "open the chart") is None + assert inner.calls == 1 + (line,) = _ledger_lines(tmp_path / "runs" / "egress-ledger.jsonl") + assert line["component"] == "grounder" and line["destination"] == "vlm.internal" + result = StepResult(step_id="s1", intent="open the chart", ok=False) + rp._egress.drain(result) + assert result.grounder_calls == 1 + + vlm = _OffBoxIdentityVLM("same") + rp.identity_vlm = vlm + verifier = _Verifier("yes") + rp.state_verifier = verifier + crop = _crop_png() + rp.identity_vlm.same_or_different(crop, crop) + rp.state_verifier.holds(crop, "x") + assert (vlm.calls, verifier.calls) == (1, 1) + assert len(_ledger_lines(tmp_path / "runs" / "egress-ledger.jsonl")) == 3 + + +def test_off_box_component_assigned_without_opt_in_is_refused(monkeypatch): + monkeypatch.delenv("OPENADAPT_FLOW_EGRESS_LEDGER", raising=False) + rp = Replayer(FakeBackend()) + with pytest.raises(EgressNotPermitted): + rp.grounder = _OffBoxGrounder() + with pytest.raises(EgressNotPermitted): + rp.identity_vlm = _OffBoxIdentityVLM("same") + with pytest.raises(EgressNotPermitted): + rp.state_verifier = _Verifier("yes") + assert rp.grounder is None and rp._screenshots_may_leave_box is False + + # A replayer built without __init__ has no opt-in either. + bare = Replayer.__new__(Replayer) + with pytest.raises(EgressNotPermitted): + bare.grounder = _OffBoxGrounder() + + +def test_replayer_built_without_init_still_ledgers_off_box_calls(monkeypatch): + # A Replayer made with __new__ gets its recorder on first use, and an + # opted-in component assigned to it is wrapped, so nothing is sent + # unrecorded (here: no ledger is bound, so the send is refused). + from openadapt_flow.runtime.model_egress import LEDGER_ENV + + monkeypatch.delenv(LEDGER_ENV, raising=False) + rp = Replayer.__new__(Replayer) + recorder = rp._egress + assert rp._egress is recorder + rp.allow_model_grounding = True + inner = _OffBoxGrounder() + rp.grounder = inner + assert rp.grounder is not inner + assert rp.grounder.locate(b"frame", "click Save") is None + assert inner.calls == 0 diff --git a/packages/flow/tests/test_resolver_fuzz.py b/packages/flow/tests/test_resolver_fuzz.py index 88385fc40d..69bdcf1e05 100644 --- a/packages/flow/tests/test_resolver_fuzz.py +++ b/packages/flow/tests/test_resolver_fuzz.py @@ -128,6 +128,8 @@ def find_text( class FakeGrounder: + MAY_EGRESS = False # in process; an unmarked grounder counts as egress + def __init__(self, result=None): self.result = result