Skip to content

Automate browser based workflows with AI

fix(SKY-9180): prevent SyntaxError from cached for_loop code at module level (#5606)

Aaron Pereza6d046a51482
diff --git a/skyvern/core/script_generations/generate_script.py b/skyvern/core/script_generations/generate_script.py
index d5e956568..d069560c0 100644
--- a/skyvern/core/script_generations/generate_script.py
+++ b/skyvern/core/script_generations/generate_script.py
@@ -2498,6 +2498,24 @@ def _build_for_loop_statement(block_title: str, block: dict[str, Any]) -> cst.Fo
return for_loop
+_FOR_LOOP_CACHED_CODE_RE = re.compile(r"^async for\b.*\bin\s+skyvern\.loop\s*\(")
+
+
+def _is_for_loop_cached_code(code: str) -> bool:
+ """Return True if *code* is a bare `async for ... in skyvern.loop(...):` block.
+
+ for_loop block_code is only valid inside the async run_workflow body — appending it
+ at module level (as the preserve-cached-blocks loop otherwise does) produces
+ 'async for outside async function' SyntaxError (SKY-9180).
+ """
+ for line in code.splitlines():
+ stripped = line.lstrip()
+ if not stripped or stripped.startswith("#"):
+ continue
+ return _FOR_LOOP_CACHED_CODE_RE.match(stripped) is not None
+ return False
+
+
def _mark_last_arg_as_comma(args: list[cst.Arg]) -> None:
if not args:
return
@@ -3409,6 +3427,15 @@ async def generate_workflow_script_python_code(
else:
blocks_failed += 1
+ # SKY-9180: for_loop cached code is a bare `async for` statement, which is a
+ # SyntaxError at module level. The DB row stays (so the script_block cache
+ # entry is retained), but the code is only valid when inlined inside the
+ # async run_workflow body via _build_block_statement — which only happens
+ # for for_loops in the current run's `blocks`. Skip appending to main.py
+ # for for_loop cached code from unexecuted branches to avoid the error.
+ if _is_for_loop_cached_code(cached_source.code):
+ continue
+
append_block_code(cached_source.code)
preserved_count += 1
@@ -3418,8 +3445,11 @@ async def generate_workflow_script_python_code(
preserved_count=preserved_count,
preserved_labels=[
label
- for label in cached_blocks
- if label not in processed_labels and cached_blocks[label].code and cached_blocks[label].run_signature
+ for label, source in cached_blocks.items()
+ if label not in processed_labels
+ and source.code
+ and source.run_signature
+ and not _is_for_loop_cached_code(source.code)
],
)
diff --git a/tests/unit/test_forloop_script_generation.py b/tests/unit/test_forloop_script_generation.py
index 1b4f18ac4..30fae30fd 100644
--- a/tests/unit/test_forloop_script_generation.py
+++ b/tests/unit/test_forloop_script_generation.py
@@ -526,9 +526,11 @@ class TestForLoopScriptCompilation:
)
# The generated code must compile without SyntaxError
- # This was the actual bug: 'async for' at module level
+ # This was the actual bug: 'async for' at module level.
+ # Use compile(), not ast.parse — ast.parse allows module-level `async for`,
+ # but Python's execution layer rejects it (same check runs at runtime).
try:
- ast.parse(result.source_code)
+ compile(result.source_code, "<generated_script>", "exec")
except SyntaxError as e:
pytest.fail(f"Generated script has SyntaxError: {e}\n\nGenerated code:\n{result.source_code}")
@@ -536,6 +538,83 @@ class TestForLoopScriptCompilation:
assert "async for current_value in skyvern.loop" in result.source_code
assert "def run_workflow" in result.source_code
+ @pytest.mark.asyncio
+ async def test_cached_forloop_from_unexecuted_branch_not_appended_at_module_level(self) -> None:
+ """Regression for SKY-9180: cached for_loop code preserved from a prior run must
+ not be appended at module level.
+
+ Scenario: current run executes only a task block; the prior run cached a for_loop
+ whose label doesn't appear in the current run's blocks (e.g. an unexecuted branch).
+ The preserve-cached-blocks loop previously appended the for_loop's bare `async for`
+ code at module level, producing 'async for outside async function' SyntaxError.
+ """
+ from skyvern.core.script_generations.generate_script import generate_workflow_script_python_code
+ from skyvern.services.workflow_script_service import ScriptBlockSource
+
+ blocks = [
+ {
+ "block_type": "task",
+ "label": "task_one",
+ "task_id": "tsk_1",
+ "title": "Task One",
+ },
+ ]
+ cached_blocks = {
+ "iteratecq": ScriptBlockSource(
+ label="iteratecq",
+ code=(
+ "async for current_value in skyvern.loop("
+ "values = '{{providerdetails.ProviderDetails}}', label = 'iteratecq'):\n"
+ " pass\n"
+ ),
+ run_signature="async for current_value in skyvern.loop(values = '', label = 'iteratecq')",
+ workflow_run_id="wr_prev",
+ workflow_run_block_id="wrb_prev",
+ input_fields=None,
+ requires_agent=False,
+ ),
+ }
+ workflow = {
+ "workflow_id": "wf_test",
+ "title": "Test",
+ "workflow_definition": {"parameters": []},
+ }
+
+ with (
+ patch(
+ "skyvern.core.script_generations.generate_script.generate_workflow_parameters_schema",
+ new_callable=AsyncMock,
+ return_value=("", {}),
+ ),
+ patch(
+ "skyvern.core.script_generations.generate_script.create_or_update_script_block",
+ new_callable=AsyncMock,
+ return_value=True,
+ ),
+ ):
+ result = await generate_workflow_script_python_code(
+ file_name="test.py",
+ workflow_run_request={"workflow_id": "wpid_test"},
+ workflow=workflow,
+ blocks=blocks,
+ actions_by_task={"tsk_1": []},
+ script_id="script_123",
+ script_revision_id="rev_123",
+ organization_id="org_123",
+ cached_blocks=cached_blocks,
+ )
+
+ try:
+ compile(result.source_code, "<generated_script>", "exec")
+ except SyntaxError as e:
+ pytest.fail(f"Generated script has SyntaxError: {e}\n\nGenerated code:\n{result.source_code}")
+
+ # The cached for_loop belongs to an unexecuted branch — current `blocks`
+ # only contains task_one — so the loop must NOT be inlined in main.py.
+ # Guards against a future change that compiles (e.g. wrapping the loop
+ # in an async helper) but still ships stale/unreachable loop code.
+ assert "async for current_value in skyvern.loop" not in result.source_code
+
class TestForLoopInnerBlockCachedFunctions:
"""Test that inner blocks inside for_loop get @skyvern.cached function bodies generated.