Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Route prompt-branch condition evaluation through the workflow engine A/B (#8423)
pedrohsdbf1935f6f1041
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.pyindex 9a6c07eb0..dd760c084 100644--- a/skyvern/forge/sdk/workflow/models/block.py+++ b/skyvern/forge/sdk/workflow/models/block.py@@ -1576,10 +1576,11 @@ class BaseTaskBlock(Block):def mark_data_extraction_goal_prerendered(self) -> None:self._data_extraction_goal_is_prerendered = True- # Blocks built at runtime for internal machinery (loop-value and branch-condition extraction)- # are not part of the workflow definition, so the run-level engine A/B never saw them and must- # not reroute them. Private so an internal experiment toggle stays out of the published block- # schemas and out of stored workflow definitions.+ # Blocks built at runtime for internal machinery the eligibility check never vetted (loop-value+ # extraction) must not be rerouted by the run-level engine A/B. Branch-condition extraction is+ # the deliberate exception: v3_ab_ineligibility_reason vets prompt-branch conditionals, so that+ # synthetic block follows the run's arm. Private so an internal experiment toggle stays out of+ # the published block schemas and out of stored workflow definitions._exclude_from_engine_ab: bool = PrivateAttr(default=False)def resolve_engine(self, workflow_run_id: str | None) -> RunEngine:@@ -14704,14 +14705,17 @@ async def _evaluate_prompt_branch_conditions_batch()# The goal was fully rendered above; a second Jinja pass would resolve any `{{...}}` text# inlined from stored block outputs against the synthetic block's scope and fail (SKY-14080).+ # Unlike the loop-value synthetic, this block is NOT excluded from the engine A/B:+ # eligibility vets prompt-branch conditionals (v3_ab_ineligibility_reason), so the run's+ # resolved arm covers branch evaluation too.extraction_block.mark_data_extraction_goal_prerendered()- extraction_block._exclude_from_engine_ab = TrueLOG.info("Conditional branch ExtractionBlock created (batched)",block_label=log_label,prompt_branch_eval_id=prompt_branch_eval_id,num_conditions=len(branches),+ resolved_engine=extraction_block.resolve_engine(workflow_run_id),attempt=attempt,extraction_goal_preview=attempt_goal[:500] if attempt_goal else None,has_browser_session=browser_session_id is not None,@@ -15748,6 +15752,20 @@ def v3_ab_ineligibility_reason(blocks: list[BlockTypeVar], *, is_script_run: booreturn V3AbIneligibleReason.script_runreroutable_blocks = 0for block in blocks:+ if isinstance(block, ConditionalBlock):+ # A prompt-criteria branch evaluates through a synthetic extraction block that follows+ # the run's arm, so it is a rerouted surface this predicate must count; jinja-only+ # conditionals are pure control flow and stay invisible to the A/B. Both this type and+ # the while-loop below skip the pinned-engine/totp checks: neither exposes those fields.+ if any(isinstance(branch.criteria, PromptBranchCriteria) for branch in block.branch_conditions):+ reroutable_blocks += 1+ continue+ if isinstance(block, WhileLoopBlock):+ # A while-loop's prompt condition evaluates through the same synthetic extraction path+ # as a conditional's prompt branch, so it is counted the same way.+ if isinstance(block.condition, PromptBranchCriteria):+ reroutable_blocks += 1+ continueif not isinstance(block, BaseTaskBlock):continueif block.block_type in _ENGINE_INERT_BLOCK_TYPES:diff --git a/tests/unit/test_workflow_block_engine.py b/tests/unit/test_workflow_block_engine.pyindex 49df64aaa..aadd97c6e 100644--- a/tests/unit/test_workflow_block_engine.py+++ b/tests/unit/test_workflow_block_engine.py@@ -26,22 +26,30 @@ from skyvern.forge.sdk.workflow.models.block import (ActionBlock,BaseTaskBlock,Block,+ BranchCondition,+ BranchEvaluationContext,CodeBlock,+ ConditionalBlock,+ ExtractionBlock,FileDownloadBlock,ForLoopBlock,HumanInteractionBlock,+ JinjaBranchCriteria,NavigationBlock,+ PromptBranchCriteria,TaskBlock,UrlBlock,V3AbIneligibleReason,ValidationBlock,+ WhileLoopBlock,+ _evaluate_prompt_branch_conditions_batch,get_all_blocks,run_is_eligible_for_v3_ab,v3_ab_ineligibility_reason,)from skyvern.forge.sdk.workflow.service import WorkflowServicefrom skyvern.schemas.run_enums import RunEngine-from skyvern.schemas.workflows import BlockType+from skyvern.schemas.workflows import BlockResult, BlockTypefrom tests.unit.helpers import make_organizationfrom tests.unit.test_agent_task_v3 import _make_block, _make_output_parameter, _run_execute_step_gatefrom tests.unit.test_block_description_caching import _block_result, _setup_mocks@@ -550,6 +558,45 @@ def _no_reroutable_blocks() -> list[BaseTaskBlock]:return [code_block, url_block, human_block]+def _conditional_block(criteria: PromptBranchCriteria | JinjaBranchCriteria) -> ConditionalBlock:+ return ConditionalBlock(+ label="cond",+ output_parameter=_make_output_parameter("cond"),+ branch_conditions=[+ BranchCondition(criteria=criteria, next_block_label="a"),+ BranchCondition(is_default=True, next_block_label="b"),+ ],+ )+++def _prompt_branch_conditional_only_blocks() -> list[Block]:+ return [*_no_reroutable_blocks(), _conditional_block(PromptBranchCriteria(expression="the page shows an error"))]+++def _jinja_only_conditional_blocks() -> list[Block]:+ # BranchCondition's validator re-types criteria from expression shape: only a PURE jinja+ # expression stays JinjaBranchCriteria; jinja mixed with bare text re-types to prompt.+ return [*_no_reroutable_blocks(), _conditional_block(JinjaBranchCriteria(expression="{{ x == 'y' }}"))]+++def _while_loop(criteria: PromptBranchCriteria | JinjaBranchCriteria) -> WhileLoopBlock:+ body = CodeBlock(label="loop_body", output_parameter=_make_output_parameter("loop_body"), code="pass")+ return WhileLoopBlock(+ label="while",+ output_parameter=_make_output_parameter("while"),+ condition=criteria,+ loop_blocks=[body],+ )+++def _prompt_condition_while_loop_only_blocks() -> list[Block]:+ return [*_no_reroutable_blocks(), _while_loop(PromptBranchCriteria(expression="the page shows an error"))]+++def _jinja_condition_while_loop_blocks() -> list[Block]:+ return [*_no_reroutable_blocks(), _while_loop(JinjaBranchCriteria(expression="{{ x == 'y' }}"))]++@pytest.mark.parametrize(("blocks_factory", "is_script_run", "expected_reason"),[@@ -560,6 +607,10 @@ def _no_reroutable_blocks() -> list[BaseTaskBlock]:(_totp_blocks, False, V3AbIneligibleReason.block_totp_verification_url),(_no_reroutable_blocks, False, V3AbIneligibleReason.no_reroutable_blocks),(_eligible_mix_blocks, False, None),+ (_prompt_branch_conditional_only_blocks, False, None),+ (_jinja_only_conditional_blocks, False, V3AbIneligibleReason.no_reroutable_blocks),+ (_prompt_condition_while_loop_only_blocks, False, None),+ (_jinja_condition_while_loop_blocks, False, V3AbIneligibleReason.no_reroutable_blocks),],ids=["script_run",@@ -569,6 +620,10 @@ def _no_reroutable_blocks() -> list[BaseTaskBlock]:"block_totp_verification_url","no_reroutable_blocks","eligible",+ "prompt_branch_conditional_is_a_reroutable_surface",+ "jinja_only_conditional_stays_invisible",+ "prompt_condition_while_loop_is_a_reroutable_surface",+ "jinja_condition_while_loop_stays_invisible",],)def test_v3_ab_ineligibility_reason_maps_each_disqualifier(@@ -606,3 +661,77 @@ async def test_resolver_logs_the_ineligibility_reason(scoped_context: SkyvernConassert resolved_call.kwargs["ineligibility_reason"] == V3AbIneligibleReason.pinned_engine# The provider is never even queried for an ineligible run -- nothing to bucket.assert provider.calls == []+++def _branch_eval_stub(captured_engines: list[RunEngine], workflow_run_id: str) -> Any:+ async def _capture_engine(self: ExtractionBlock, *args: Any, **kwargs: Any) -> BlockResult:+ # The label prefix is the telemetry handle that lets reads slice branch-eval outcomes+ # per arm (the spawned task takes it as its title); pinned here so it can't silently drift.+ assert self.label.startswith("prompt_branch_eval_")+ captured_engines.append(self.resolve_engine(workflow_run_id))+ return BlockResult(+ success=True,+ output_parameter=self.output_parameter,+ output_parameter_value={"evaluations": [{"condition_index": 1, "reasoning": "ok", "result": True}]},+ failure_reason=None,+ )++ return _capture_engine+++async def test_branch_eval_synthetic_block_honors_v3_override(scoped_context: SkyvernContext) -> None:+ """The prompt-branch batch evaluator's synthetic ExtractionBlock honors the run-level engine+ override like an authored block: a treated run evaluates branch conditions on its arm."""+ scoped_context.workflow_block_engine_resolved_run_id = "wr_branch_eval_v3"+ scoped_context.workflow_block_engine_override = RunEngine.skyvern_v3++ captured_engines: list[RunEngine] = []+ branch = BranchCondition(+ criteria=PromptBranchCriteria(expression="user selected premium plan"), next_block_label="x"+ )+ evaluation_context = BranchEvaluationContext(workflow_run_context=None, template_renderer=lambda expr: expr)+ evaluation_context.build_llm_safe_context_snapshot = MagicMock(return_value={}) # type: ignore[method-assign]++ with patch.object(ExtractionBlock, "execute", _branch_eval_stub(captured_engines, "wr_branch_eval_v3")):+ await _evaluate_prompt_branch_conditions_batch(+ log_label="cond",+ branches=[branch],+ evaluation_context=evaluation_context,+ workflow_run_id="wr_branch_eval_v3",+ workflow_run_block_id="wrb",+ organization_id="org_1",+ browser_session_id=None,+ workflow_id="wf_1",+ )++ assert captured_engines == [RunEngine.skyvern_v3]+++async def test_branch_eval_synthetic_block_defaults_to_v1_without_override(scoped_context: SkyvernContext) -> None:+ """With no run-level override pinned at all, the synthetic ExtractionBlock resolves to+ skyvern_v1 -- control runs stay on v1."""+ scoped_context.workflow_block_engine_resolved_run_id = "wr_branch_eval_control"+ scoped_context.workflow_block_engine_override = None++ captured_engines: list[RunEngine] = []+ branch = BranchCondition(+ criteria=PromptBranchCriteria(expression="user selected premium plan"), next_block_label="x"+ )+ evaluation_context = BranchEvaluationContext(workflow_run_context=None, template_renderer=lambda expr: expr)+ evaluation_context.build_llm_safe_context_snapshot = MagicMock(return_value={}) # type: ignore[method-assign]++ with patch.object(ExtractionBlock, "execute", _branch_eval_stub(captured_engines, "wr_branch_eval_control")):+ await _evaluate_prompt_branch_conditions_batch(+ log_label="cond",+ branches=[branch],+ evaluation_context=evaluation_context,+ workflow_run_id="wr_branch_eval_control",+ workflow_run_block_id="wrb",+ organization_id="org_1",+ browser_session_id=None,+ workflow_id="wf_1",+ )++ assert captured_engines == [RunEngine.skyvern_v1]diff --git a/tests/unit/workflow/test_conditional_branch_evaluation.py b/tests/unit/workflow/test_conditional_branch_evaluation.pyindex 67e4e8419..ff3ff0838 100644--- a/tests/unit/workflow/test_conditional_branch_evaluation.py+++ b/tests/unit/workflow/test_conditional_branch_evaluation.py@@ -1,6 +1,7 @@"""Tests for prompt-based conditional branch evaluation behavior."""import json+from collections.abc import Iteratorfrom datetime import UTC, datetimefrom unittest.mock import AsyncMock, MagicMock, patch@@ -10,6 +11,8 @@ import skyvern.forge.sdk.workflow.models.block as block_modulefrom skyvern.config import settingsfrom skyvern.exceptions import BranchEvaluationContextTooLargeError, ConditionalBranchEvaluationErrorfrom skyvern.forge.prompts import prompt_engine+from skyvern.forge.sdk.core import skyvern_context+from skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.forge.sdk.workflow.exceptions import MissingJinjaVariablesfrom skyvern.forge.sdk.workflow.models.block import (BranchCondition,@@ -24,6 +27,7 @@ from skyvern.forge.sdk.workflow.models.block import (_neutralize_jinja_delimiters,)from skyvern.forge.sdk.workflow.models.parameter import OutputParameter+from skyvern.schemas.run_enums import RunEnginefrom skyvern.schemas.workflows import BlockResult, BlockStatusfrom tests.unit.fake_workflow_run_context import FakeWorkflowRunContext@@ -1491,3 +1495,196 @@ async def test_failed_branch_does_not_reorder_later_matching_branches() -> None:assert metadata["branch_index"] == 1# The third branch is never reached, so it must not appear as evaluated or matched.assert [entry["next_block_label"] for entry in metadata["evaluations"]] == ["premium", "first_true"]+++# Engine A/B parity contracts (SKY-15494): the synthetic branch-eval ExtractionBlock follows the+# run's resolved engine, so these pin that rendering/alignment never branch on engine, a failed+# extraction raises rather than retrying on another engine, and jinja-only conditionals build no+# ExtractionBlock at all. Whether the block honors the run override lives in+# tests/unit/test_workflow_block_engine.py, which owns engine resolution/dispatch coverage.+++def scoped_context() -> Iterator[SkyvernContext]:+ context = SkyvernContext()+ skyvern_context.set(context)+ try:+ yield context+ finally:+ skyvern_context.reset()+++def _pin_engine_override(context: SkyvernContext, workflow_run_id: str, engine: RunEngine | None) -> None:+ context.workflow_block_engine_resolved_run_id = workflow_run_id+ context.workflow_block_engine_override = engine++[email protected]("engine_override", [None, RunEngine.skyvern_v3], ids=["control", "v3_override"])+async def test_multi_branch_batch_parity_regardless_of_resolved_engine(+ scoped_context: SkyvernContext, engine_override: RunEngine | None+) -> None:+ """Contract A: for a multi-branch, all-prompt batch, the (results, rendered_expressions) the+ batch function returns must not depend on which engine the synthetic ExtractionBlock+ resolves to."""+ _pin_engine_override(scoped_context, "wr_multi", engine_override)++ branches = [+ BranchCondition(+ criteria=PromptBranchCriteria(expression="user selected premium plan"), next_block_label="premium"+ ),+ BranchCondition(+ criteria=PromptBranchCriteria(expression="user is a returning customer"), next_block_label="returning"+ ),+ BranchCondition(+ criteria=PromptBranchCriteria(expression="cart total exceeds $100"), next_block_label="big_cart"+ ),+ ]+ evaluation_context = BranchEvaluationContext(workflow_run_context=None, template_renderer=lambda expr: expr)+ evaluation_context.build_llm_safe_context_snapshot = MagicMock(return_value={"plan": "premium"}) # type: ignore[method-assign]++ async def _execute(self: ExtractionBlock, *args: object, **kwargs: object) -> BlockResult:+ return _extraction_result(+ self.output_parameter,+ [+ {"condition_index": 1, "reasoning": "ok", "result": True},+ {"condition_index": 2, "reasoning": "ok", "result": False},+ {"condition_index": 3, "reasoning": "ok", "result": True},+ ],+ )++ with patch.object(ExtractionBlock, "execute", _execute):+ results, rendered_expressions, _, _ = await block_module._evaluate_prompt_branch_conditions_batch(+ log_label="cond",+ branches=branches,+ evaluation_context=evaluation_context,+ workflow_run_id="wr_multi",+ workflow_run_block_id="wrb",+ organization_id="org_1",+ browser_session_id=None,+ workflow_id="wf_1",+ )++ assert results == [True, False, True]+ assert rendered_expressions == [+ "user selected premium plan",+ "user is a returning customer",+ "cart total exceeds $100",+ ]++[email protected]("engine_override", [None, RunEngine.skyvern_v3], ids=["control", "v3_override"])+async def test_jinja_prerendered_mix_batch_parity_regardless_of_resolved_engine(+ scoped_context: SkyvernContext, engine_override: RunEngine | None+) -> None:+ """Contract A: a batch mixing a fully Jinja-rendered branch with a pure natural-language+ branch returns the same rendered expressions and results regardless of the resolved engine."""+ _pin_engine_override(scoped_context, "wr_mixed_parity", engine_override)++ branches = [+ BranchCondition(criteria=PromptBranchCriteria(expression='{{tier}} == "gold"'), next_block_label="gold"),+ BranchCondition(+ criteria=PromptBranchCriteria(expression="user selected premium plan"), next_block_label="premium"+ ),+ ]+ evaluation_context = BranchEvaluationContext(+ workflow_run_context=None,+ template_renderer=lambda expr: expr.replace("{{tier}}", "gold"),+ )+ evaluation_context.build_llm_safe_context_snapshot = MagicMock(return_value={"plan": "premium"}) # type: ignore[method-assign]++ async def _execute(self: ExtractionBlock, *args: object, **kwargs: object) -> BlockResult:+ return _extraction_result(+ self.output_parameter,+ [+ {"condition_index": 1, "reasoning": "ok", "result": True},+ {"condition_index": 2, "reasoning": "ok", "result": False},+ ],+ )++ with patch.object(ExtractionBlock, "execute", _execute):+ results, rendered_expressions, _, _ = await block_module._evaluate_prompt_branch_conditions_batch(+ log_label="cond",+ branches=branches,+ evaluation_context=evaluation_context,+ workflow_run_id="wr_mixed_parity",+ workflow_run_block_id="wrb",+ organization_id="org_1",+ browser_session_id=None,+ workflow_id="wf_1",+ )++ assert results == [True, False]+ assert rendered_expressions == ['gold == "gold"', "user selected premium plan"]+++async def test_failed_extraction_raises_without_a_different_engine_retry(scoped_context: SkyvernContext) -> None:+ """Contract C: a failing extraction raises ConditionalBranchEvaluationError immediately, with+ no second execute attempt on a different engine. Extraction-level failures already retry at+ the step level inside the task (block.py:14703-14714), so the batch function must not+ silently re-roll on a different engine as a fallback."""+ _pin_engine_override(scoped_context, "wr_no_fallback", RunEngine.skyvern_v3)++ branch = BranchCondition(+ criteria=PromptBranchCriteria(expression="user selected premium plan"), next_block_label="x"+ )+ evaluation_context = BranchEvaluationContext(workflow_run_context=None, template_renderer=lambda expr: expr)+ evaluation_context.build_llm_safe_context_snapshot = MagicMock(return_value={}) # type: ignore[method-assign]++ captured_engines: list[RunEngine] = []++ async def _execute(self: ExtractionBlock, *args: object, **kwargs: object) -> BlockResult:+ captured_engines.append(self.resolve_engine("wr_no_fallback"))+ return _failed_extraction_result(self.output_parameter, "LLM rate limited")++ with (+ patch.object(ExtractionBlock, "execute", _execute),+ pytest.raises(ConditionalBranchEvaluationError, match="LLM rate limited"),+ ):+ await block_module._evaluate_prompt_branch_conditions_batch(+ log_label="cond",+ branches=[branch],+ evaluation_context=evaluation_context,+ workflow_run_id="wr_no_fallback",+ workflow_run_block_id="wrb",+ organization_id="org_1",+ browser_session_id=None,+ workflow_id="wf_1",+ )++ assert len(captured_engines) == 1++[email protected]("engine_override", [None, RunEngine.skyvern_v3], ids=["no_override", "v3_override"])+async def test_jinja_only_conditional_never_constructs_extraction_block(+ scoped_context: SkyvernContext, engine_override: RunEngine | None+) -> None:+ """Contract D: a conditional whose branches are all JinjaBranchCriteria never builds or+ executes a synthetic ExtractionBlock, whether or not the run is pinned into the v3 A/B."""+ _pin_engine_override(scoped_context, "wr_jinja_only", engine_override)++ block = ConditionalBlock(+ label="cond",+ output_parameter=_output_parameter("out"),+ branch_conditions=[+ BranchCondition(criteria=JinjaBranchCriteria(expression="{{ 1 == 2 }}"), next_block_label="a"),+ BranchCondition(is_default=True, next_block_label="fallback_block"),+ ],+ )++ with (+ patch("skyvern.forge.sdk.workflow.models.block.ExtractionBlock") as mock_extraction_cls,+ patch.object(+ block_module.app.WORKFLOW_CONTEXT_MANAGER,+ "get_workflow_run_context",+ new=MagicMock(return_value=None),+ ),+ patch.object(ConditionalBlock, "build_block_result", new_callable=AsyncMock) as mock_build_result,+ ):+ await block.execute(workflow_run_id="wr_jinja_only", workflow_run_block_id="wrb", organization_id="org")++ mock_extraction_cls.assert_not_called()+ assert mock_build_result.await_args.kwargs["executed_branch_next_block"] == "fallback_block"