From 5f6db4b33ef7c6cea4c671cce90c927f265e877f Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 08:38:44 -0500 Subject: [PATCH] feat(flow): add hardware-tiered local model router and PrePostSubmitVisualVeto --- .../flow/openadapt_flow/models/__init__.py | 27 ++ .../flow/openadapt_flow/models/runtime.py | 418 ++++++++++++++++++ .../tests/test_tiered_local_model_runtime.py | 385 ++++++++++++++++ 3 files changed, 830 insertions(+) create mode 100644 packages/flow/openadapt_flow/models/__init__.py create mode 100644 packages/flow/openadapt_flow/models/runtime.py create mode 100644 packages/flow/tests/test_tiered_local_model_runtime.py diff --git a/packages/flow/openadapt_flow/models/__init__.py b/packages/flow/openadapt_flow/models/__init__.py new file mode 100644 index 0000000000..b0f00a4948 --- /dev/null +++ b/packages/flow/openadapt_flow/models/__init__.py @@ -0,0 +1,27 @@ +"""Hardware-tiered local model policy, routing, and veto-only visual guards.""" + +from openadapt_flow.models.runtime import ( + CpuVlmRefusedError, + HardwareCapabilities, + HardwareTier, + PrePostSubmitVisualVeto, + SubmitVetoResult, + TieredLocalModelRouter, + TierPolicy, + TierRouteDecision, + VisualVetoStage, + detect_hardware_capabilities, +) + +__all__ = [ + "CpuVlmRefusedError", + "HardwareCapabilities", + "HardwareTier", + "PrePostSubmitVisualVeto", + "SubmitVetoResult", + "TierPolicy", + "TierRouteDecision", + "TieredLocalModelRouter", + "VisualVetoStage", + "detect_hardware_capabilities", +] diff --git a/packages/flow/openadapt_flow/models/runtime.py b/packages/flow/openadapt_flow/models/runtime.py new file mode 100644 index 0000000000..5b2f9f08dd --- /dev/null +++ b/packages/flow/openadapt_flow/models/runtime.py @@ -0,0 +1,418 @@ +"""Hardware-tiered local model policy, router, and pre/post-submit visual veto. + +Routes verification and grounding work by measured hardware capability instead +of running 4B+ VLMs interactively on CPU-only hosts: + +* **Tier 1 (``DETERMINISTIC_ONLY``):** Zero-model fast path (~10-100 ms). + Default whenever deterministic API, DB, SQL, or DOM evidence covers the check. +* **Tier 2 (``LOCAL_ACCELERATED`` / ``LAN_APPLIANCE``):** Apple Silicon MLX or + local GPU, or an opted-in customer LAN GPU appliance, paired with + Global-to-Local (GOLD) ROI cropping and :class:`VetoOnlyVLMGuard` under + strict ``MAY_EGRESS`` enforcement. +* **Tier 3 (``CPU_LIGHTWEIGHT``):** CPU-only hosts allow lightweight ONNX + locate-only grounding (~55 ms) and **explicitly refuse** interactive 4B+ VLM + calls unless ``allow_slow_cpu_vlm=True`` is opted in for offline/async jobs. + +All visual checks are strictly **veto-only**: ``VETO`` and ``ABSTAIN`` halt; +``PASS`` never overrides a failing deterministic check. +""" + +from __future__ import annotations + +import importlib.util +import os +import platform +from dataclasses import dataclass +from enum import Enum +from typing import Any, Mapping, Optional + +from openadapt_flow.ir import Region +from openadapt_flow.runtime.grounder import component_may_egress +from openadapt_flow.runtime.identity_vlm import ( + MLXIdentityVLM, + VetoDecision, + VetoOnlyVLMGuard, + VetoVerdict, +) +from openadapt_flow.runtime.remote_vlm import ( + _MAX_MODEL_IMAGE_DIM, + RemoteAppliance, + appliance_from_env, +) + + +class HardwareTier(str, Enum): + """Execution tier for local verification and grounding.""" + + DETERMINISTIC_ONLY = "deterministic_only" + LOCAL_ACCELERATED = "local_accelerated" + LAN_APPLIANCE = "lan_appliance" + CPU_LIGHTWEIGHT = "cpu_lightweight" + + +class CpuVlmRefusedError(RuntimeError): + """Raised when an interactive 4B+ VLM call is requested on a CPU-only host + without explicit offline/async opt-in (``allow_slow_cpu_vlm=True``). + """ + + +@dataclass(frozen=True) +class HardwareCapabilities: + """Immutable snapshot of host model-execution capabilities.""" + + platform_system: str + machine: str + has_apple_silicon_mlx: bool = False + has_cuda_gpu: bool = False + has_lan_appliance: bool = False + has_onnxruntime: bool = False + available_ram_gib: Optional[float] = None + + +def _module_available(module_name: str) -> bool: + try: + return importlib.util.find_spec(module_name) is not None + except (ImportError, ValueError): + return False + + +def detect_hardware_capabilities( + env: Optional[Mapping[str, str]] = None, + *, + probe_imports: bool = True, +) -> HardwareCapabilities: + """Detect local hardware capabilities without importing heavy ML stacks.""" + src = os.environ if env is None else env + sys_name = platform.system() + machine = platform.machine().lower() + + has_mlx = False + has_cuda = False + has_onnx = False + if probe_imports: + is_apple_arm = sys_name == "Darwin" and machine in ("arm64", "aarch64") + has_mlx = is_apple_arm and _module_available("mlx_vlm") + has_onnx = _module_available("onnxruntime") + if _module_available("torch"): + try: + import torch + + has_cuda = bool(torch.cuda.is_available()) + except Exception: + has_cuda = False + + has_lan = bool((src.get("OPENADAPT_FLOW_VLM_URL") or "").strip()) + return HardwareCapabilities( + platform_system=sys_name, + machine=machine, + has_apple_silicon_mlx=has_mlx, + has_cuda_gpu=has_cuda, + has_lan_appliance=has_lan, + has_onnxruntime=has_onnx, + ) + + +@dataclass(frozen=True) +class TierPolicy: + """Routing and safety policy for :class:`TieredLocalModelRouter`. + + * ``prefer_deterministic`` -- route to ``DETERMINISTIC_ONLY`` whenever + deterministic evidence covers the check. + * ``allow_lan_appliance`` -- explicit opt-in to route to a configured LAN + GPU appliance (``MAY_EGRESS = True``). Off by default so screenshots + never silently leave the local host. + * ``allow_slow_cpu_vlm`` -- explicit opt-in to allow 4B+ VLM calls on + CPU-only hosts for offline/async jobs. Off by default to prevent 40s+ + interactive UI stalls and multi-GB multimodal RAM spikes. + * ``interactive`` -- marks interactive UI replay paths (default ``True``). + * ``max_image_dim`` -- GOLD crop / downscale pixel ceiling (default 1024). + """ + + prefer_deterministic: bool = True + allow_lan_appliance: bool = False + allow_slow_cpu_vlm: bool = False + interactive: bool = True + max_image_dim: int = _MAX_MODEL_IMAGE_DIM + + +@dataclass(frozen=True) +class TierRouteDecision: + """Outcome of a single hardware-tier routing decision.""" + + tier: HardwareTier + allow_vlm_veto: bool + allow_lightweight_locate: bool + may_egress: bool + reason: str + + +class TieredLocalModelRouter: + """Hardware-tiered local model policy router. + + Selects the lowest-cost safe execution tier for each check and builds + fail-closed :class:`VetoOnlyVLMGuard` / :class:`PrePostSubmitVisualVeto` + handles that preserve ``MAY_EGRESS`` classification. + """ + + def __init__( + self, + capabilities: Optional[HardwareCapabilities] = None, + policy: Optional[TierPolicy] = None, + *, + local_identity_vlm: Optional[Any] = None, + local_state_verifier: Optional[Any] = None, + lan_appliance: Optional[RemoteAppliance] = None, + env: Optional[Mapping[str, str]] = None, + ) -> None: + self._env = os.environ if env is None else env + self.capabilities = ( + detect_hardware_capabilities(self._env) + if capabilities is None + else capabilities + ) + self.policy = TierPolicy() if policy is None else policy + self._local_identity_vlm = local_identity_vlm + self._local_state_verifier = local_state_verifier + self._lan_appliance = lan_appliance + + @property + def MAY_EGRESS(self) -> bool: + """Whether this router's configured VLM tier can send screenshots off-box.""" + decision = self.route(deterministic_available=False, needs_vlm_veto=True) + if decision.may_egress: + return True + if decision.tier is HardwareTier.LOCAL_ACCELERATED or decision.allow_vlm_veto: + return component_may_egress( + self._local_identity_vlm + ) or component_may_egress(self._local_state_verifier) + return False + + def route( + self, + *, + deterministic_available: bool = False, + needs_vlm_veto: bool = False, + needs_locate: bool = False, + ) -> TierRouteDecision: + """Choose the execution tier for a check or grounding request.""" + if deterministic_available and self.policy.prefer_deterministic: + return TierRouteDecision( + tier=HardwareTier.DETERMINISTIC_ONLY, + allow_vlm_veto=False, + allow_lightweight_locate=False, + may_egress=False, + reason="deterministic_authority_available", + ) + + if self.capabilities.has_apple_silicon_mlx or self.capabilities.has_cuda_gpu: + accel = ( + "apple_silicon_mlx" + if self.capabilities.has_apple_silicon_mlx + else "cuda_gpu" + ) + return TierRouteDecision( + tier=HardwareTier.LOCAL_ACCELERATED, + allow_vlm_veto=True, + allow_lightweight_locate=True, + may_egress=False, + reason=f"local_accelerator:{accel}", + ) + + lan_configured = ( + self._lan_appliance is not None or self.capabilities.has_lan_appliance + ) + if lan_configured and self.policy.allow_lan_appliance: + return TierRouteDecision( + tier=HardwareTier.LAN_APPLIANCE, + allow_vlm_veto=True, + allow_lightweight_locate=True, + may_egress=True, + reason="lan_appliance_opted_in", + ) + + # Tier 3: CPU-only host (or LAN configured without egress opt-in). + if self.policy.allow_slow_cpu_vlm and not self.policy.interactive: + reason = "cpu_vlm_offline_opt_in" + allow_vlm = True + elif self.policy.allow_slow_cpu_vlm: + reason = "cpu_vlm_explicit_opt_in" + allow_vlm = True + elif lan_configured and not self.policy.allow_lan_appliance: + reason = "lan_appliance_requires_egress_opt_in;cpu_refuses_interactive_vlm" + allow_vlm = False + elif needs_vlm_veto: + reason = "cpu_only_refuses_interactive_vlm" + allow_vlm = False + elif needs_locate and self.capabilities.has_onnxruntime: + reason = "cpu_lightweight_onnx_locate_only" + allow_vlm = False + else: + reason = "cpu_lightweight_no_interactive_vlm" + allow_vlm = False + + return TierRouteDecision( + tier=HardwareTier.CPU_LIGHTWEIGHT, + allow_vlm_veto=allow_vlm, + allow_lightweight_locate=self.capabilities.has_onnxruntime, + may_egress=False, + reason=reason, + ) + + def _resolve_lan_appliance(self) -> Optional[RemoteAppliance]: + if self._lan_appliance is not None: + return self._lan_appliance + return appliance_from_env(dict(self._env)) + + def build_veto_guard(self, *, require_vlm: bool = False) -> VetoOnlyVLMGuard: + """Build a tier-appropriate :class:`VetoOnlyVLMGuard`. + + On CPU-only hosts without ``allow_slow_cpu_vlm=True``: + * raises :class:`CpuVlmRefusedError` when ``require_vlm=True``; + * otherwise returns an empty fail-closed guard that abstains without + loading or running a slow 4B+ model on CPU. + """ + decision = self.route(deterministic_available=False, needs_vlm_veto=True) + + if decision.tier is HardwareTier.LOCAL_ACCELERATED: + id_vlm = ( + self._local_identity_vlm + if self._local_identity_vlm is not None + else ( + MLXIdentityVLM() + if self.capabilities.has_apple_silicon_mlx + else None + ) + ) + return VetoOnlyVLMGuard( + identity_vlm=id_vlm, + state_verifier=self._local_state_verifier, + max_dim=self.policy.max_image_dim, + ) + + if decision.tier is HardwareTier.LAN_APPLIANCE: + appliance = self._resolve_lan_appliance() + if appliance is None: + return VetoOnlyVLMGuard(max_dim=self.policy.max_image_dim) + return VetoOnlyVLMGuard( + identity_vlm=appliance.identity_vlm, + state_verifier=appliance.state_verifier, + max_dim=self.policy.max_image_dim, + ) + + if not decision.allow_vlm_veto: + if require_vlm: + raise CpuVlmRefusedError( + "Refusing interactive 4B+ VLM execution on CPU-only host " + f"({decision.reason}). Pass TierPolicy(allow_slow_cpu_vlm=True) " + "for offline/async CPU jobs, or opt in to a LAN appliance." + ) + return VetoOnlyVLMGuard(max_dim=self.policy.max_image_dim) + + return VetoOnlyVLMGuard( + identity_vlm=self._local_identity_vlm, + state_verifier=self._local_state_verifier, + max_dim=self.policy.max_image_dim, + ) + + def build_submit_veto( + self, *, require_vlm: bool = False + ) -> PrePostSubmitVisualVeto: + """Build a :class:`PrePostSubmitVisualVeto` wired for the routed tier.""" + decision = self.route(deterministic_available=False, needs_vlm_veto=True) + guard = self.build_veto_guard(require_vlm=require_vlm) + return PrePostSubmitVisualVeto(guard=guard, tier=decision.tier) + + +class VisualVetoStage(str, Enum): + """Lifecycle stage guarded by :class:`PrePostSubmitVisualVeto`.""" + + PRE_SUBMIT = "pre_submit" + POST_SUBMIT = "post_submit" + + +@dataclass(frozen=True) +class SubmitVetoResult: + """Combined deterministic + veto-only visual outcome for a submit boundary.""" + + stage: VisualVetoStage + decision: VetoDecision + deterministic_passed: bool + allowed: bool + tier: HardwareTier + + +class PrePostSubmitVisualVeto: + """Domain-agnostic pre-submit and post-submit visual veto guard. + + Wraps :class:`VetoOnlyVLMGuard` (with GOLD ROI cropping on >1024px frames) + and enforces strict veto-only semantics at form/GUI submit boundaries: + + * ``VETO`` or ``ABSTAIN`` always sets ``allowed = False`` (halt). + * ``PASS`` lets a passing deterministic check stand, and **never** + overrides ``deterministic_passed = False``. + * Propagates ``MAY_EGRESS`` from the underlying guard. + """ + + def __init__( + self, + guard: VetoOnlyVLMGuard, + *, + tier: HardwareTier = HardwareTier.LOCAL_ACCELERATED, + ) -> None: + self._guard = guard + self._tier = tier + + @property + def MAY_EGRESS(self) -> bool: + """Propagate screenshot-egress classification from the wrapped guard.""" + return component_may_egress(self._guard) + + def check_pre_submit( + self, + *, + recorded_png: bytes, + live_png: bytes, + deterministic_passed: bool, + roi: Optional[Region] = None, + expected_state: Optional[str] = None, + ) -> SubmitVetoResult: + """Run a veto-only visual identity (and optional state) check before submit.""" + id_decision = self._guard.check_identity(recorded_png, live_png, roi=roi) + decision = id_decision + if not id_decision.should_halt and expected_state is not None: + state_decision = self._guard.check_state(live_png, expected_state, roi=roi) + if state_decision.should_halt: + decision = state_decision + else: + decision = VetoDecision( + verdict=VetoVerdict.PASS, + used_gold_crop=( + id_decision.used_gold_crop or state_decision.used_gold_crop + ), + ) + + return SubmitVetoResult( + stage=VisualVetoStage.PRE_SUBMIT, + decision=decision, + deterministic_passed=bool(deterministic_passed), + allowed=decision.apply_to_deterministic(deterministic_passed), + tier=self._tier, + ) + + def check_post_submit( + self, + *, + screenshot: bytes, + expected_state: str, + deterministic_passed: bool, + roi: Optional[Region] = None, + ) -> SubmitVetoResult: + """Run a veto-only visual state check after submit.""" + decision = self._guard.check_state(screenshot, expected_state, roi=roi) + return SubmitVetoResult( + stage=VisualVetoStage.POST_SUBMIT, + decision=decision, + deterministic_passed=bool(deterministic_passed), + allowed=decision.apply_to_deterministic(deterministic_passed), + tier=self._tier, + ) diff --git a/packages/flow/tests/test_tiered_local_model_runtime.py b/packages/flow/tests/test_tiered_local_model_runtime.py new file mode 100644 index 0000000000..7a6b2e79ec --- /dev/null +++ b/packages/flow/tests/test_tiered_local_model_runtime.py @@ -0,0 +1,385 @@ +"""Unit tests for hardware-tiered local model routing and PrePostSubmitVisualVeto. + +Covers: +1. Hardware capability detection and Tier 1 / Tier 2 / Tier 3 routing. +2. Explicit refusal of interactive 4B+ VLM calls on CPU-only hosts and offline + opt-in via ``TierPolicy(allow_slow_cpu_vlm=True)``. +3. Strict ``MAY_EGRESS`` propagation into ``Replayer`` opt-in enforcement. +4. GOLD-cropped pre-submit and post-submit strict veto-only truth table on + ``>1024px`` synthetic frames. +""" + +from __future__ import annotations + +import io + +import pytest +from PIL import Image, ImageDraw + +from openadapt_flow.models import ( + CpuVlmRefusedError, + HardwareCapabilities, + HardwareTier, + PrePostSubmitVisualVeto, + TieredLocalModelRouter, + TierPolicy, + VisualVetoStage, + detect_hardware_capabilities, +) +from openadapt_flow.runtime.grounder import component_may_egress +from openadapt_flow.runtime.identity_vlm import VetoOnlyVLMGuard, VetoVerdict +from openadapt_flow.runtime.remote_vlm import ( + _MAX_MODEL_IMAGE_DIM, + RemoteAppliance, + RemoteGrounder, + RemoteIdentityVLM, + RemoteStateVerifier, + RemoteVLMClient, +) +from openadapt_flow.runtime.replayer import EgressNotPermitted, Replayer + + +def _dims(png: bytes) -> tuple[int, int]: + return Image.open(io.BytesIO(png)).size + + +def _make_frame( + w: int = 2560, + h: int = 1440, + roi: tuple[int, int, int, int] = (400, 120, 320, 64), +) -> bytes: + img = Image.new("RGB", (w, h), (240, 240, 240)) + draw = ImageDraw.Draw(img) + rx, ry, rw, rh = roi + draw.rectangle( + [rx, ry, rx + rw - 1, ry + rh - 1], + fill=(255, 255, 255), + outline=(200, 40, 40), + ) + buf = io.BytesIO() + img.save(buf, format="PNG") + return buf.getvalue() + + +class _FakeLocalIdentity: + MAY_EGRESS = False + + def __init__(self, answer: str = "same") -> None: + self.answer = answer + self.calls: list[tuple[tuple[int, int], tuple[int, int]]] = [] + + def same_or_different(self, recorded_png: bytes, live_png: bytes) -> str: + self.calls.append((_dims(recorded_png), _dims(live_png))) + return self.answer + + +class _FakeLocalState: + MAY_EGRESS = False + + def __init__(self, verdict: str = "yes") -> None: + self.verdict = verdict + self.calls: list[tuple[tuple[int, int], str]] = [] + + def verify(self, screenshot: bytes, expected_state: str) -> str: + self.calls.append((_dims(screenshot), expected_state)) + return self.verdict + + +def _make_lan_appliance() -> RemoteAppliance: + client = RemoteVLMClient("http://127.0.0.1:9") + return RemoteAppliance( + client=client, + identity_vlm=RemoteIdentityVLM(client), + grounder=RemoteGrounder(client), + state_verifier=RemoteStateVerifier(client), + ) + + +# -------------------------------------------------------------------------- +# 1. Capability detection & tier routing +# -------------------------------------------------------------------------- + + +def test_detect_hardware_capabilities_reads_lan_env(): + caps_off = detect_hardware_capabilities(env={}, probe_imports=False) + assert caps_off.has_lan_appliance is False + assert caps_off.has_apple_silicon_mlx is False + assert caps_off.has_cuda_gpu is False + + caps_on = detect_hardware_capabilities( + env={"OPENADAPT_FLOW_VLM_URL": "http://127.0.0.1:8077"}, + probe_imports=False, + ) + assert caps_on.has_lan_appliance is True + + +@pytest.mark.parametrize( + "caps", + [ + HardwareCapabilities("Darwin", "arm64", has_apple_silicon_mlx=True), + HardwareCapabilities("Linux", "x86_64", has_cuda_gpu=True), + HardwareCapabilities("Linux", "x86_64", has_lan_appliance=True), + HardwareCapabilities("Linux", "x86_64", has_onnxruntime=True), + ], +) +def test_tier1_deterministic_always_wins_when_available(caps): + router = TieredLocalModelRouter( + capabilities=caps, + policy=TierPolicy(prefer_deterministic=True, allow_lan_appliance=True), + ) + decision = router.route(deterministic_available=True, needs_vlm_veto=True) + assert decision.tier is HardwareTier.DETERMINISTIC_ONLY + assert decision.allow_vlm_veto is False + assert decision.may_egress is False + + +def test_tier2_local_accelerated_routes_without_egress(): + caps = HardwareCapabilities("Darwin", "arm64", has_apple_silicon_mlx=True) + router = TieredLocalModelRouter( + capabilities=caps, + local_identity_vlm=_FakeLocalIdentity("same"), + local_state_verifier=_FakeLocalState("yes"), + ) + decision = router.route(deterministic_available=False, needs_vlm_veto=True) + assert decision.tier is HardwareTier.LOCAL_ACCELERATED + assert decision.allow_vlm_veto is True + assert decision.may_egress is False + assert router.MAY_EGRESS is False + + +def test_tier2_lan_appliance_requires_explicit_egress_opt_in(): + caps = HardwareCapabilities( + "Linux", "x86_64", has_lan_appliance=True, has_onnxruntime=True + ) + appliance = _make_lan_appliance() + + # Without allow_lan_appliance=True: refuses LAN egress and falls back to CPU tier. + router_blocked = TieredLocalModelRouter( + capabilities=caps, + policy=TierPolicy(allow_lan_appliance=False), + lan_appliance=appliance, + ) + dec_blocked = router_blocked.route( + deterministic_available=False, needs_vlm_veto=True + ) + assert dec_blocked.tier is HardwareTier.CPU_LIGHTWEIGHT + assert dec_blocked.allow_vlm_veto is False + assert dec_blocked.may_egress is False + assert router_blocked.MAY_EGRESS is False + + # With allow_lan_appliance=True: routes to LAN_APPLIANCE and propagates MAY_EGRESS. + router_opted = TieredLocalModelRouter( + capabilities=caps, + policy=TierPolicy(allow_lan_appliance=True), + lan_appliance=appliance, + ) + dec_opted = router_opted.route(deterministic_available=False, needs_vlm_veto=True) + assert dec_opted.tier is HardwareTier.LAN_APPLIANCE + assert dec_opted.allow_vlm_veto is True + assert dec_opted.may_egress is True + assert router_opted.MAY_EGRESS is True + + +# -------------------------------------------------------------------------- +# 2. Tier 3 CPU-only: interactive 4B+ VLM refusal + offline opt-in +# -------------------------------------------------------------------------- + + +def test_tier3_cpu_only_refuses_interactive_vlm_and_allows_onnx_locate(): + caps = HardwareCapabilities("Linux", "x86_64", has_onnxruntime=True) + local_id = _FakeLocalIdentity("same") + router = TieredLocalModelRouter( + capabilities=caps, + policy=TierPolicy(allow_slow_cpu_vlm=False, interactive=True), + local_identity_vlm=local_id, + ) + + dec_locate = router.route(deterministic_available=False, needs_locate=True) + assert dec_locate.tier is HardwareTier.CPU_LIGHTWEIGHT + assert dec_locate.allow_lightweight_locate is True + assert dec_locate.allow_vlm_veto is False + + # Explicit require_vlm=True raises CpuVlmRefusedError. + with pytest.raises(CpuVlmRefusedError): + router.build_veto_guard(require_vlm=True) + + # Non-raising build returns a fail-closed abstaining guard that never calls the VLM. + veto = router.build_submit_veto(require_vlm=False) + frame = _make_frame() + res = veto.check_pre_submit( + recorded_png=frame, live_png=frame, deterministic_passed=True + ) + assert res.tier is HardwareTier.CPU_LIGHTWEIGHT + assert res.decision.verdict is VetoVerdict.ABSTAIN + assert res.allowed is False + assert local_id.calls == [] + + +def test_tier3_cpu_only_allows_vlm_when_offline_opted_in(): + caps = HardwareCapabilities("Linux", "x86_64", has_onnxruntime=True) + local_id = _FakeLocalIdentity("same") + router = TieredLocalModelRouter( + capabilities=caps, + policy=TierPolicy(allow_slow_cpu_vlm=True, interactive=False), + local_identity_vlm=local_id, + ) + + dec = router.route(deterministic_available=False, needs_vlm_veto=True) + assert dec.tier is HardwareTier.CPU_LIGHTWEIGHT + assert dec.allow_vlm_veto is True + assert dec.may_egress is False + + veto = router.build_submit_veto(require_vlm=True) + frame = _make_frame() + res = veto.check_pre_submit( + recorded_png=frame, live_png=frame, deterministic_passed=True + ) + assert res.decision.verdict is VetoVerdict.PASS + assert res.allowed is True + assert len(local_id.calls) == 1 + + +# -------------------------------------------------------------------------- +# 3. MAY_EGRESS propagation into Replayer +# -------------------------------------------------------------------------- + + +def test_router_and_submit_veto_propagate_egress_to_replayer(): + caps = HardwareCapabilities("Linux", "x86_64", has_lan_appliance=True) + router = TieredLocalModelRouter( + capabilities=caps, + policy=TierPolicy(allow_lan_appliance=True), + lan_appliance=_make_lan_appliance(), + ) + guard = router.build_veto_guard() + veto = router.build_submit_veto() + + assert component_may_egress(router) is True + assert component_may_egress(guard) is True + assert component_may_egress(veto) is True + + with pytest.raises(EgressNotPermitted): + Replayer(backend=object(), vision=object(), identity_vlm=guard) + + replayer = Replayer( + backend=object(), + vision=object(), + identity_vlm=guard, + allow_model_grounding=True, + ) + assert replayer._screenshots_may_leave_box is True + + +# -------------------------------------------------------------------------- +# 4. PrePostSubmitVisualVeto GOLD-crop & strict veto-only truth table +# -------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("det_passed", "raw_id", "expected_verdict", "expected_allowed"), + [ + (True, "same", VetoVerdict.PASS, True), + (True, "different", VetoVerdict.VETO, False), + (True, "uncertain", VetoVerdict.ABSTAIN, False), + # PASS must NEVER override a failed deterministic check. + (False, "same", VetoVerdict.PASS, False), + (False, "different", VetoVerdict.VETO, False), + (False, "uncertain", VetoVerdict.ABSTAIN, False), + ], +) +def test_pre_submit_visual_veto_truth_table_and_gold_crop( + det_passed, raw_id, expected_verdict, expected_allowed +): + roi = (400, 120, 320, 64) + frame = _make_frame(2560, 1440, roi=roi) + id_backend = _FakeLocalIdentity(raw_id) + guard = VetoOnlyVLMGuard(identity_vlm=id_backend) + veto = PrePostSubmitVisualVeto(guard=guard, tier=HardwareTier.LOCAL_ACCELERATED) + + res = veto.check_pre_submit( + recorded_png=frame, + live_png=frame, + deterministic_passed=det_passed, + roi=roi, + ) + assert res.stage is VisualVetoStage.PRE_SUBMIT + assert res.decision.verdict is expected_verdict + assert res.decision.used_gold_crop is True + assert res.allowed is expected_allowed + rec_dims, live_dims = id_backend.calls[0] + assert max(rec_dims) <= _MAX_MODEL_IMAGE_DIM + assert max(live_dims) <= _MAX_MODEL_IMAGE_DIM + assert rec_dims[0] < 1024 # native ROI crop, not full 2560px frame + + +@pytest.mark.parametrize( + ("det_passed", "raw_state", "expected_verdict", "expected_allowed"), + [ + (True, "yes", VetoVerdict.PASS, True), + (True, "no", VetoVerdict.VETO, False), + (True, "uncertain", VetoVerdict.ABSTAIN, False), + (False, "yes", VetoVerdict.PASS, False), + (False, "no", VetoVerdict.VETO, False), + (False, "uncertain", VetoVerdict.ABSTAIN, False), + ], +) +def test_post_submit_visual_veto_truth_table_and_gold_crop( + det_passed, raw_state, expected_verdict, expected_allowed +): + roi = (400, 120, 320, 64) + frame = _make_frame(2560, 1440, roi=roi) + state_backend = _FakeLocalState(raw_state) + guard = VetoOnlyVLMGuard(state_verifier=state_backend) + veto = PrePostSubmitVisualVeto(guard=guard, tier=HardwareTier.LOCAL_ACCELERATED) + + res = veto.check_post_submit( + screenshot=frame, + expected_state="confirmation banner visible", + deterministic_passed=det_passed, + roi=roi, + ) + assert res.stage is VisualVetoStage.POST_SUBMIT + assert res.decision.verdict is expected_verdict + assert res.decision.used_gold_crop is True + assert res.allowed is expected_allowed + sent_dims, _ = state_backend.calls[0] + assert max(sent_dims) <= _MAX_MODEL_IMAGE_DIM + + +def test_pre_submit_combined_identity_and_state_halts_if_state_vetoes(): + roi = (400, 120, 320, 64) + frame = _make_frame(2560, 1440, roi=roi) + guard = VetoOnlyVLMGuard( + identity_vlm=_FakeLocalIdentity("same"), + state_verifier=_FakeLocalState("no"), + ) + veto = PrePostSubmitVisualVeto(guard=guard, tier=HardwareTier.LOCAL_ACCELERATED) + res = veto.check_pre_submit( + recorded_png=frame, + live_png=frame, + deterministic_passed=True, + roi=roi, + expected_state="submit button enabled and no validation error", + ) + assert res.decision.verdict is VetoVerdict.VETO + assert res.allowed is False + + +def test_pre_submit_partly_clipped_roi_abstains_without_calling_backend(): + clipped_roi = (900, 80, 320, 64) + large_frame = _make_frame(2560, 1440, roi=clipped_roi) + small_frame = _make_frame(1024, 768, roi=(200, 80, 320, 64)) + id_backend = _FakeLocalIdentity("same") + veto = PrePostSubmitVisualVeto( + guard=VetoOnlyVLMGuard(identity_vlm=id_backend), + tier=HardwareTier.LOCAL_ACCELERATED, + ) + res = veto.check_pre_submit( + recorded_png=large_frame, + live_png=small_frame, + deterministic_passed=True, + roi=clipped_roi, + ) + assert res.decision.verdict is VetoVerdict.ABSTAIN + assert res.allowed is False + assert id_backend.calls == []