Skip to content

Automate browser based workflows with AI

Return the producer-output facts the copilot binds against (SKY-15900) (#8532)

Andrew Neilson1402a0c7aecc
diff --git a/skyvern/forge/prompts/skyvern/workflow_knowledge_base.txt b/skyvern/forge/prompts/skyvern/workflow_knowledge_base.txt
index 447767a3f..7999ad1b5 100644
--- a/skyvern/forge/prompts/skyvern/workflow_knowledge_base.txt
+++ b/skyvern/forge/prompts/skyvern/workflow_knowledge_base.txt
@@ -907,10 +907,14 @@ There are TWO types of references:
IMPORTANT — block output shapes are NOT uniform across block types. Using the wrong shape either raises "dict object has no attribute 'output'" at render time or (worse) silently renders a None value into a URL field, producing `https://None` which fails with `net::ERR_NAME_NOT_RESOLVED`.
-* Browser-task blocks (navigation, extraction, goto_url, login, action, file_download):
- - `{{ label.output }}` — the full TaskOutput envelope.
- - `{{ label.output.extracted_information }}` — the extracted payload.
- - Example: `{{ extract_items.output }}` inside a downstream prompt.
+* Browser-task blocks (navigation, extraction, goto_url, login, action):
+ - `{{ label.output }}` — the extracted payload (an alias for extracted_information). Use this in a value field.
+ - `{{ label.extracted_information }}` — the extracted payload (also available).
+ - `{{ label }}` — the full TaskOutput envelope (status, failure_reason, the payload). Use it to inspect what a block returned, not as the value you want to write.
+ - Example: `{{ extract_items.output }}` or `{{ extract_items.extracted_information }}` inside a downstream prompt.
+
+* File download blocks (file_download):
+ - `{{ fetch_report.downloaded_file_urls }}` — the URLs of the downloaded files; `{{ fetch_report.downloaded_files }}` holds the full file records. Use these, NOT `{{ fetch_report.output.downloaded_file_urls }}`: a download has no extracted payload, so `.output` holds nothing to read from and renders blank on its own.
* Non-task blocks (text_prompt, http_request, file_url_parser):
- `{{ label.<field> }}` — fields from the returned JSON are on the block directly; there is NO `.output` wrapper.
diff --git a/skyvern/forge/sdk/copilot/output_utils.py b/skyvern/forge/sdk/copilot/output_utils.py
index 58cd5adf3..95390e4a6 100644
--- a/skyvern/forge/sdk/copilot/output_utils.py
+++ b/skyvern/forge/sdk/copilot/output_utils.py
@@ -12,6 +12,7 @@ from typing import TYPE_CHECKING, Any, Literal, TypeVar
from urllib.parse import urlsplit, urlunsplit
import structlog
+from pydantic import JsonValue
from skyvern.forge.sdk.agents.context import sanitize_agent_tool_result_for_llm as sanitize_generic_tool_result_for_llm
from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal, assert_clean_user_facing_text
@@ -68,6 +69,10 @@ _BUILD_TEST_FAILURE_REASON_MAX_CHARS = 1_200
_BUILD_TEST_LABEL_MAX_ITEMS = 24
_BUILD_TEST_OUTPUT_MAX_ITEMS = 12
_BUILD_TEST_OUTPUT_VALUE_MAX_CHARS = 800
+# The share of that cap a failure reason may hold before it starts crowding out available_keys, and
+# the shortest it is worth trimming one to.
+_AVAILABLE_KEYS_REASON_SHARE = 400
+_AVAILABLE_KEYS_REASON_FLOOR = 80
_BUILD_TEST_DOWNLOAD_MAX_ITEMS = 12
_BUILD_TEST_UNFINISHED_MAX_ITEMS = 24
_BUILD_TEST_ACTION_TRACE_MAX_ITEMS = 6
@@ -941,6 +946,82 @@ def _compact_packet_for_aggregate_limit(
)
+def _trim_failure_text(fitted: dict[str, Any], limit: int) -> bool:
+ """Trim the failure reason and each copy of it in ``errors[].reasoning`` to ``limit`` characters,
+ reporting whether anything changed."""
+
+ def bounded(text: JsonValue) -> str | None:
+ return text[: limit - 3] + "..." if isinstance(text, str) and len(text) > limit else None
+
+ changed = False
+ trimmed_reason = bounded(fitted.get("failure_reason"))
+ if trimmed_reason is not None:
+ fitted["failure_reason"] = trimmed_reason
+ changed = True
+ errors = fitted.get("errors")
+ if isinstance(errors, list):
+ rebuilt: list[JsonValue] = []
+ for error in errors:
+ trimmed = bounded(error.get("reasoning")) if isinstance(error, dict) else None
+ rebuilt.append(error if trimmed is None else {**error, "reasoning": trimmed})
+ changed = changed or trimmed is not None
+ fitted["errors"] = rebuilt
+ return changed
+
+
+def _bound_failure_text(fitted: dict[str, Any]) -> bool:
+ """Shrink the failure text until the output fits, halving the allowance each pass. One copy bounded
+ to a fixed share is not enough: build_block_failure_output repeats the reason once per error code,
+ so the total is what has to come down."""
+ shortened = False
+ limit = _AVAILABLE_KEYS_REASON_SHARE
+ while True:
+ shortened = _trim_failure_text(fitted, limit) or shortened
+ fits = len(json.dumps(fitted, ensure_ascii=False, separators=(",", ":"))) <= _BUILD_TEST_OUTPUT_VALUE_MAX_CHARS
+ if fits or limit <= _AVAILABLE_KEYS_REASON_FLOOR:
+ return shortened
+ limit //= 2
+
+
+def _fit_available_keys(block_output: JsonValue, label: str | None, notices: list[str]) -> tuple[JsonValue, bool]:
+ """Drop ``available_keys`` entries until the output fits the per-output cap, and report whether any
+ were dropped. Letting the cap stringify the whole dict instead cuts the keys off entirely, and they
+ are the field a failed binding is repaired from."""
+ if not isinstance(block_output, dict) or not isinstance(block_output.get("available_keys"), list):
+ return block_output, False
+ original = block_output["available_keys"]
+ fitted = dict(block_output)
+ over_cap = len(json.dumps(fitted, ensure_ascii=False, separators=(",", ":"))) > _BUILD_TEST_OUTPUT_VALUE_MAX_CHARS
+ # A failure reason quoting a long template can fill the cap by itself, and build_block_failure_output
+ # copies that same text into every errors[].reasoning, so trimming the keys to nothing would hand the
+ # model an error with no path to repair from. failure.reason keeps a longer copy, so these ones
+ # yield the space instead.
+ reason_shortened = _bound_failure_text(fitted) if over_cap else False
+ if reason_shortened:
+ append_omission_notice(
+ notices,
+ f"failure text on {label or '(unlabeled)'} shortened so available_keys fit; "
+ "a longer copy is in failure.reason.",
+ )
+ # Reference paths answer the failing reference; bare top-level names say what else exists, and for
+ # an undefined root they are the only answer. Trim whichever group is larger so neither empties first.
+ paths = [key for key in original if isinstance(key, str) and ("." in key or "[" in key)]
+ roots = [key for key in original if not (isinstance(key, str) and ("." in key or "[" in key))]
+ while (paths or roots) and len(
+ json.dumps(fitted, ensure_ascii=False, separators=(",", ":"))
+ ) > _BUILD_TEST_OUTPUT_VALUE_MAX_CHARS:
+ (paths if len(paths) >= len(roots) else roots).pop()
+ fitted["available_keys"] = [*paths, *roots]
+ keys_shortened = len(paths) + len(roots) != len(original)
+ if keys_shortened:
+ append_omission_notice(
+ notices,
+ f"available_keys on {label or '(unlabeled)'} shortened to {len(paths) + len(roots)} of "
+ f"{len(original)} entries.",
+ )
+ return fitted, keys_shortened or reason_shortened
+
+
def project_build_test_packet_for_llm(packet: BuildTestEvidencePacket) -> BuildTestEvidencePacket:
"""Return the one bounded model projection of a factual build-test packet."""
notices = list(packet.omission_notices)
@@ -1052,9 +1133,9 @@ def project_build_test_packet_for_llm(packet: BuildTestEvidencePacket) -> BuildT
registered_outputs: list[BuildTestPacketRegisteredOutput] = []
for output in packet.registered_outputs[:_BUILD_TEST_OUTPUT_MAX_ITEMS]:
- rendered_output = json.dumps(output.output, ensure_ascii=False, separators=(",", ":"))
- block_output = output.output
- value_complete = output.value_complete
+ block_output, keys_shortened = _fit_available_keys(output.output, output.label, notices)
+ rendered_output = json.dumps(block_output, ensure_ascii=False, separators=(",", ":"))
+ value_complete = output.value_complete and not keys_shortened
if len(rendered_output) > _BUILD_TEST_OUTPUT_VALUE_MAX_CHARS:
block_output = rendered_output[: _BUILD_TEST_OUTPUT_VALUE_MAX_CHARS - 3] + "..."
value_complete = False
diff --git a/skyvern/forge/sdk/copilot/tools/frontier.py b/skyvern/forge/sdk/copilot/tools/frontier.py
index 4cddcde80..5b3e11f5f 100644
--- a/skyvern/forge/sdk/copilot/tools/frontier.py
+++ b/skyvern/forge/sdk/copilot/tools/frontier.py
@@ -14,6 +14,7 @@ try:
from bs4 import BeautifulSoup # type: ignore[import-not-found]
except ImportError: # pragma: no cover — bs4 is a transitive dep but discovery degrades gracefully without it.
BeautifulSoup = None # type: ignore[assignment, misc]
+from jinja2 import TemplateError, meta
from jinja2.sandbox import SandboxedEnvironment
from skyvern.forge import app
@@ -67,9 +68,9 @@ _BLOCK_TYPES_STATE_ESTABLISHER = frozenset({"navigation", "login", "goto_url"})
_MAX_BLOCK_NESTING_DEPTH = 10
_JINJA_IDENTIFIER = r"[A-Za-z_][A-Za-z0-9_]*"
-_OUTPUT_REF_RE = re.compile(rf"\{{\{{\s*({_JINJA_IDENTIFIER})_output\s*(?=[\.|}}])")
-_BLOCK_FORM_REF_RE = re.compile(rf"\{{\{{\s*({_JINJA_IDENTIFIER})\s*\.")
-_JINJA_ROOT_RE = re.compile(rf"\{{\{{\s*({_JINJA_IDENTIFIER})\s*(?=[\.|}}])")
+# Fallback only: this sees the identifier that opens an expression, so `{{ a ~ b }}` hides `b`.
+# _jinja_roots parses instead, and falls back to this when the text is not valid Jinja.
+_JINJA_ROOT_RE = re.compile(rf"\{{\{{\s*({_JINJA_IDENTIFIER})")
_JINJA_RUNTIME_GLOBAL_ROOTS = frozenset(SandboxedEnvironment().globals)
_JINJA_LITERAL_ROOTS = frozenset({"none", "true", "false"})
@@ -699,12 +700,51 @@ def _workflow_parameter_keys(definition: object | None) -> set[str]:
_CREDENTIAL_REAL_VALUE_SUFFIXES = ("_real_username", "_real_password")
+def _jinja_string_leaves(serialized: str) -> list[str]:
+ """The block config's own string values. The serialized form is JSON, so a quoted Jinja literal
+ arrives escaped as ``\\"`` — which no Jinja parser accepts — and parsing the whole blob would cost
+ every reference in a block that uses one."""
+ try:
+ payload = json.loads(serialized)
+ except (json.JSONDecodeError, TypeError, ValueError):
+ return [serialized]
+ leaves: list[str] = []
+ stack: list[Any] = [payload]
+ while stack:
+ item = stack.pop()
+ if isinstance(item, str):
+ leaves.append(item)
+ elif isinstance(item, dict):
+ # Keys too: error_code_mapping is templatable on both sides, so a key can carry a reference.
+ stack.extend(item.keys())
+ stack.extend(item.values())
+ elif isinstance(item, list):
+ stack.extend(item)
+ return leaves
+
+
+def _jinja_roots(serialized: str) -> set[str]:
+ """Every identifier the config's Jinja expressions read, from Jinja's own parser. Falls back to the
+ opening-identifier regex for a leaf that does not parse, which keeps a malformed block classifiable
+ rather than silently referenceless."""
+ roots: set[str] = set()
+ for leaf in _jinja_string_leaves(serialized):
+ try:
+ roots |= meta.find_undeclared_variables(SandboxedEnvironment().parse(leaf))
+ except (TemplateError, RecursionError):
+ roots |= set(_JINJA_ROOT_RE.findall(leaf))
+ return roots
+
+
def _classify_frontier_jinja_refs(
frontier_labels: list[str],
new_definition: object | None,
serialized_configs: list[str] | None = None,
) -> tuple[set[str], set[str], set[str]]:
- """Single pass over frontier blocks; returns ``(suffix_form_refs, block_form_refs, unknown_roots)``."""
+ """Single pass over frontier blocks; returns ``(suffix_form_refs, block_form_refs, unknown_roots)``.
+
+ A reference anywhere in an expression counts, not just the one that opens it: seeding only the
+ first of ``{{ a.output.x ~ b.output.x }}`` would leave ``b`` undefined in the scoped run."""
if serialized_configs is None:
serialized_configs = _serialized_frontier_block_configs(frontier_labels, new_definition)
known_labels = set(_blocks_by_label(new_definition))
@@ -716,16 +756,14 @@ def _classify_frontier_jinja_refs(
unknown_roots: set[str] = set()
for serialized in serialized_configs:
- for match in _OUTPUT_REF_RE.findall(serialized):
- if match in known_labels:
- suffix_form_refs.add(match)
- for match in _BLOCK_FORM_REF_RE.findall(serialized):
- if match in known_labels:
- block_form_refs.add(match)
- for root in _JINJA_ROOT_RE.findall(serialized):
- if root in known_roots:
+ for root in _jinja_roots(serialized):
+ produced_by = root[: -len("_output")] if root.endswith("_output") else None
+ if produced_by in known_labels:
+ suffix_form_refs.add(str(produced_by))
continue
- if root.endswith("_output") and root[: -len("_output")] in known_labels:
+ if root in known_labels:
+ block_form_refs.add(root)
+ if root in known_roots:
continue
if any(
root.endswith(suffix) and root[: -len(suffix)] in parameter_keys
@@ -746,15 +784,6 @@ def _referenced_output_labels(
return suffix_refs | block_form_refs
-def _block_form_output_labels(
- frontier_labels: list[str],
- new_definition: object | None,
- serialized_configs: list[str] | None = None,
-) -> set[str]:
- _, block_form_refs, _ = _classify_frontier_jinja_refs(frontier_labels, new_definition, serialized_configs)
- return block_form_refs
-
-
def _unknown_jinja_roots(
frontier_labels: list[str],
new_definition: object | None,
@@ -1201,10 +1230,6 @@ def _seed_for_frontier(
suffix_refs, block_form_refs, unknown_roots = _classify_frontier_jinja_refs(
labels_to_execute, new_definition, serialized_configs
)
- if any(label in block_form_refs for label in prefix_labels):
- # Seeded block_outputs only register <label>_output; block-form refs
- # need a normal upstream execution to populate the <label> namespace.
- return requested_labels, {}, requested_labels[0]
needed = suffix_refs | block_form_refs
seed: dict[str, Any] = {}
for label in prefix_labels:
diff --git a/skyvern/forge/sdk/workflow/context_manager.py b/skyvern/forge/sdk/workflow/context_manager.py
index a2039cf2c..0e5490d0c 100644
--- a/skyvern/forge/sdk/workflow/context_manager.py
+++ b/skyvern/forge/sdk/workflow/context_manager.py
@@ -206,6 +206,7 @@ class WorkflowRunContext:
if block_outputs:
for label, value in block_outputs.items():
workflow_run_context.values[f"{label}_output"] = value
+ workflow_run_context.register_block_reference_variable(label, value, carried=True)
for secret_parameter in secret_parameters:
if isinstance(secret_parameter, AWSSecretParameter):
@@ -291,6 +292,7 @@ class WorkflowRunContext:
self.values: dict[str, Any] = {}
self.secrets: dict[str, Any] = {}
self.workflow_run_outputs: dict[str, Any] = {}
+ self.carried_block_labels: set[str] = set()
self._aws_client = aws_client
self.organization_id: str | None = None
self.browser_session_id: str | None = None
@@ -1704,8 +1706,15 @@ class WorkflowRunContext:
# output parameter key is formatted as `<block_label>_output`
if not parameter.key.endswith("_output"):
return
- block_label = parameter.key.removesuffix("_output")
+ self.register_block_reference_variable(parameter.key.removesuffix("_output"), value)
+ def register_block_reference_variable(
+ self,
+ block_label: str,
+ value: dict[str, Any] | list | str | None,
+ *,
+ carried: bool = False,
+ ) -> None:
block_reference_value = copy.deepcopy(value)
if isinstance(block_reference_value, dict) and "extracted_information" in block_reference_value:
block_reference_value.update({"output": block_reference_value.get("extracted_information")})
@@ -1715,9 +1724,12 @@ class WorkflowRunContext:
# Merge old into new so the latest loop iteration's keys win. A failure payload describes
# one attempt only, so it is never merged in either direction: merging it into a later
# success would carry `failure_reason` forward, and merging an earlier success into it
- # would let a prior iteration's keys leak into the failed one.
+ # would let a prior iteration's keys leak into the failed one. A carried value describes an
+ # earlier run, so it is replaced outright — merging would report that run's facts as this one's.
if (
- isinstance(current_value, dict)
+ block_label not in self.carried_block_labels
+ and not carried
+ and isinstance(current_value, dict)
and isinstance(block_reference_value, dict)
and not current_value.get("failure_reason")
and not block_reference_value.get("failure_reason")
@@ -1727,7 +1739,14 @@ class WorkflowRunContext:
LOG.debug(f"Parameter {block_label} already has a value in workflow run context, overwriting")
self.values[block_label] = block_reference_value
- self.workflow_run_outputs[block_label] = block_reference_value
+ # Templates iterate workflow_run_outputs as what this run produced, so a value carried in from an
+ # earlier run resolves by label without being listed there.
+ if not carried:
+ self.workflow_run_outputs[block_label] = block_reference_value
+ if carried:
+ self.carried_block_labels.add(block_label)
+ else:
+ self.carried_block_labels.discard(block_label)
async def set_parameter_values_for_output_parameter_dependent_blocks(
self,
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 1ea57f02a..0014090f3 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -1048,9 +1048,13 @@ class Block(BaseModel, abc.ABC):
if error_codes
else {"failure_reason": failure_reason}
)
- if isinstance(exc, FailedToFormatJinjaStyleParameter) and exc.available_keys:
+ # Blocks that re-raise a formatting error as another exception type keep the original on __cause__.
+ format_exc: BaseException | None = exc
+ while format_exc is not None and not isinstance(format_exc, FailedToFormatJinjaStyleParameter):
+ format_exc = format_exc.__cause__
+ if isinstance(format_exc, FailedToFormatJinjaStyleParameter) and format_exc.available_keys:
failure_output["available_keys"] = [
- self._redact_registered_secrets(key, workflow_run_context) for key in exc.available_keys
+ self._redact_registered_secrets(key, workflow_run_context) for key in format_exc.available_keys
]
await self.record_output_parameter_value(workflow_run_context, workflow_run_id, failure_output)
return await self.build_block_result(
diff --git a/skyvern/utils/templating.py b/skyvern/utils/templating.py
index e5ac3f306..349c2ca4b 100644
--- a/skyvern/utils/templating.py
+++ b/skyvern/utils/templating.py
@@ -1,3 +1,5 @@
+import json
+import keyword
import re
from typing import Any
@@ -66,6 +68,26 @@ def get_missing_variables(template_source: str, template_data: dict) -> set[str]
MAX_AVAILABLE_KEYS = 200
MAX_AVAILABLE_KEY_LENGTH = 128
+MAX_AVAILABLE_PATH_LENGTH = 512
+_JINJA_RESERVED = frozenset(word.lower() for word in keyword.kwlist) | {"true", "false", "none"}
+
+
+def _extend_path(path: str, segment: str | int) -> str | None:
+ """``path`` extended by one segment, written so Jinja resolves it back to that segment, or None
+ when no renderable form exists: an over-long key, or a non-identifier with no root to subscript.
+ A segment that also names a dict attribute (``items``, ``keys``) is subscripted, because dotted
+ access would resolve to the bound method instead of the value."""
+ if isinstance(segment, int):
+ return f"{path}[{segment}]" if path else None
+ if len(segment) > MAX_AVAILABLE_KEY_LENGTH:
+ return None
+ if segment.isidentifier() and segment.lower() not in _JINJA_RESERVED:
+ if not path:
+ return segment
+ # hasattr applies to dotted access on a dict, not to a top-level binding of the same name.
+ if not hasattr(dict, segment):
+ return f"{path}.{segment}"
+ return f"{path}[{json.dumps(segment)}]" if path else None
def _flatten_reference_chain(node: nodes.Node) -> tuple[str, list[str | int]] | None:
@@ -85,26 +107,45 @@ def _flatten_reference_chain(node: nodes.Node) -> tuple[str, list[str | int]] |
return node.name, segments
-def _descend(data: dict[str, Any], root: str, segments: list[str | int]) -> Any:
+def _descend(data: dict[str, Any], root: str, segments: list[str | int]) -> tuple[str, Any]:
current: Any = data
+ path = ""
for segment in [root, *segments]:
if isinstance(current, dict) and segment in current:
- current = current[segment]
+ descended = current[segment]
elif isinstance(current, list) and isinstance(segment, int) and -len(current) <= segment < len(current):
- current = current[segment]
+ descended = current[segment]
else:
- return current
- return current
+ return path, current
+ extended = _extend_path(path, segment)
+ if extended is None:
+ return path, current
+ path, current = extended, descended
+ return path, current
def get_available_keys(template_source: str, template_data: dict[str, Any]) -> list[str]:
- """Key names that a failing reference in ``template_source`` could have used: the keys of the
- deepest dict each dotted chain resolved to, plus the top-level bindings. Values are never
- included, but a key of a parsed file or an extracted object is itself run data, so the result
- is bounded in count and per-key length rather than treated as free of customer content."""
- keys: set[str] = set()
+ """Reference paths a failing reference in ``template_source`` could have used: one path per key
+ of the dict each dotted chain landed on, then the top-level bindings, each written so that
+ pasting it into ``{{ }}`` resolves to that key's value. A bare key name is not published: the
+ reader cannot tell it from a top-level binding, and pasting it renders nothing. Values are never
+ included, but a key of a parsed file or an extracted object is itself run data, so the result is
+ bounded in count and in path length rather than treated as free of customer content."""
+ reachable: set[str] = set()
+ roots: set[str] = set()
+
+ def add(into: set[str], entry: str | None) -> None:
+ if entry and len(entry) <= MAX_AVAILABLE_PATH_LENGTH:
+ into.add(entry)
+
+ def published() -> list[str]:
+ # Paths under the failing reference answer it; top-level names only say what else exists.
+ return (sorted(reachable) + sorted(roots - reachable))[:MAX_AVAILABLE_KEYS]
+
try:
- keys.update(str(key)[:MAX_AVAILABLE_KEY_LENGTH] for key in template_data)
+ for key in template_data:
+ if isinstance(key, str):
+ add(roots, _extend_path("", key))
ast = SandboxedEnvironment().parse(template_source)
chains = list(ast.find_all((nodes.Getattr, nodes.Getitem)))
nested = {id(chain.node) for chain in chains}
@@ -114,9 +155,12 @@ def get_available_keys(template_source: str, template_data: dict[str, Any]) -> l
flattened = _flatten_reference_chain(chain)
if flattened is None:
continue
- resolved = _descend(template_data, *flattened)
- if isinstance(resolved, dict):
- keys.update(str(key)[:MAX_AVAILABLE_KEY_LENGTH] for key in resolved)
+ path, resolved = _descend(template_data, *flattened)
+ if path and isinstance(resolved, dict):
+ for key in resolved:
+ # An int key is subscripted as an int; coercing it to a string key would not resolve.
+ if isinstance(key, str) or (isinstance(key, int) and not isinstance(key, bool)):
+ add(reachable, _extend_path(path, key))
except Exception:
- return sorted(keys)[:MAX_AVAILABLE_KEYS]
- return sorted(keys)[:MAX_AVAILABLE_KEYS]
+ return published()
+ return published()
diff --git a/tests/unit/test_copilot_build_test_outcome.py b/tests/unit/test_copilot_build_test_outcome.py
index dc7b96ee6..db186eb13 100644
--- a/tests/unit/test_copilot_build_test_outcome.py
+++ b/tests/unit/test_copilot_build_test_outcome.py
@@ -9,7 +9,7 @@ from contextlib import asynccontextmanager
from datetime import UTC, datetime
from types import SimpleNamespace
from typing import Any
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from pydantic import ValidationError
@@ -96,7 +96,9 @@ from skyvern.forge.sdk.copilot.workflow_yaml import runner_code_block_associatio
from skyvern.forge.sdk.db.exceptions import CopilotProposalConflictError
from skyvern.forge.sdk.schemas.copilot_turn_outcome import ResponseKind, TurnOutcome, UnresolvedRuntimeFailure
from skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrowserSession
+from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext
from skyvern.forge.sdk.workflow.models.block import CodeBlock
+from skyvern.forge.sdk.workflow.models.google_sheets_blocks import GoogleSheetsWriteBlock
from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, ParameterType
from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowDefinition, WorkflowRunStatus
from skyvern.services import workflow_service as workflow_service_module
@@ -256,6 +258,134 @@ def test_packet_projects_every_recorded_block_output_in_row_order_and_scrubs_sec
)
+async def test_packet_surfaces_available_keys_from_a_sheets_render_failure() -> None:
+ write_block = GoogleSheetsWriteBlock(
+ label="write_row",
+ output_parameter=OutputParameter(
+ parameter_type=ParameterType.OUTPUT,
+ key="write_row_output",
+ output_parameter_id="op_write_row",
+ workflow_id="w",
+ created_at=datetime.now(UTC),
+ modified_at=datetime.now(UTC),
+ ),
+ spreadsheet_url="https://docs.google.com/spreadsheets/d/sheet-id/edit",
+ values='[["{{ extract_failure_rate.output.extracted_information.failure_rate }}"]]',
+ )
+ run_context = WorkflowRunContext(
+ workflow_title="t",
+ workflow_id="w",
+ workflow_permanent_id="wpid",
+ workflow_run_id="wr_sheets_available_keys",
+ aws_client=MagicMock(),
+ )
+ run_context.values["extract_failure_rate"] = {
+ "status": "completed",
+ "extracted_information": {"failure_rate": "25.65%"},
+ "output": {"failure_rate": "25.65%"},
+ }
+
+ with pytest.raises(ValueError) as excinfo:
+ write_block._render_values_or_raise(run_context)
+
+ with (
+ patch.object(GoogleSheetsWriteBlock, "record_output_parameter_value", AsyncMock()) as record_output,
+ patch.object(GoogleSheetsWriteBlock, "build_block_result", AsyncMock()),
+ ):
+ await write_block._template_format_failure_result(
+ excinfo.value, str(excinfo.value), run_context, "wr_sheets_available_keys", None, None
+ )
+ recorded_output = record_output.await_args.args[2]
+
+ packet = build_test_evidence_packet(
+ _locator_packet_ctx(),
+ {
+ "ok": False,
+ "data": {
+ "workflow_run_id": "wr_sheets_available_keys",
+ "overall_status": "failed",
+ "blocks": [{"label": "write_row", "status": "failed", "output": recorded_output}],
+ },
+ },
+ )
+
+ assert "extract_failure_rate.output.failure_rate" in packet.registered_outputs[0].output["available_keys"]
+
+
+def test_projection_keeps_available_keys_when_the_output_exceeds_the_per_output_cap() -> None:
+ failure_output = {
+ "failure_reason": (
+ "Failed to format jinja template: block `write_row` field `values` references a value no "
+ "upstream block produced: 'dict object' has no attribute 'extracted_information'. Return "
+ "that key from the producing block, or write an explicit default (e.g. "
+ "{{ block_label.field | default('') }}) if an empty cell is intended."
+ ),
+ "available_keys": [
+ *[f"extract_metrics.output.metric_{index:02d}" for index in range(25)],
+ *[f"block_{index:02d}" for index in range(10)],
+ ],
+ }
+
+ projected = project_build_test_packet_for_llm(
+ build_test_evidence_packet(
+ _locator_packet_ctx(),
+ {
+ "ok": False,
+ "data": {
+ "workflow_run_id": "wr_available_keys_cap",
+ "overall_status": "failed",
+ "blocks": [{"label": "write_row", "status": "failed", "output": failure_output}],
+ },
+ },
+ )
+ )
+
+ registered = projected.registered_outputs[0]
+ kept = registered.output["available_keys"]
+ assert "extract_metrics.output.metric_00" in kept
+ # Top-level names are the only answer when a root is undefined, so trimming must not empty them first.
+ assert "block_00" in kept
+ assert 0 < len(kept) < 35
+ assert registered.value_complete is False
+ assert any("available_keys on write_row shortened" in notice for notice in projected.omission_notices)
+
+
+def test_projection_keeps_repair_keys_when_the_failure_reason_alone_fills_the_cap() -> None:
+ # A generic Jinja failure quotes the whole template, so the reason alone can exceed the cap, and
+ # build_block_failure_output copies that same text into every errors[].reasoning.
+ long_reason = "Failed to format Jinja style parameter '" + ("{{ verify.x }} " * 90) + "'."
+ failure_output = {
+ "status": "failed",
+ "failure_reason": long_reason,
+ "errors": [
+ {"error_code": "file_parse_failed", "reasoning": long_reason, "confidence_float": 1.0},
+ {"error_code": "template_failed", "reasoning": long_reason, "confidence_float": 1.0},
+ ],
+ "available_keys": ["verify.output.status", "verify.output.detail", "verify", "verify_output"],
+ }
+
+ projected = project_build_test_packet_for_llm(
+ build_test_evidence_packet(
+ _locator_packet_ctx(),
+ {
+ "ok": False,
+ "data": {
+ "workflow_run_id": "wr_long_reason",
+ "overall_status": "failed",
+ "blocks": [{"label": "write_row", "status": "failed", "output": failure_output}],
+ },
+ },
+ )
+ )
+
+ registered = projected.registered_outputs[0]
+ assert registered.output["available_keys"], "the repair paths must survive a reason that fills the cap"
+ assert registered.output["failure_reason"].endswith("...")
+ assert [error["reasoning"].endswith("...") for error in registered.output["errors"]] == [True, True]
+ assert registered.value_complete is False
+
+
def test_recorded_run_block_projection_keeps_falsey_and_null_outputs() -> None:
def row(output: object) -> SimpleNamespace:
return SimpleNamespace(
diff --git a/tests/unit/test_copilot_frontier.py b/tests/unit/test_copilot_frontier.py
index 15b3174f5..460ccf8a4 100644
--- a/tests/unit/test_copilot_frontier.py
+++ b/tests/unit/test_copilot_frontier.py
@@ -1120,8 +1120,7 @@ def test_referenced_output_labels_finds_block_form_jinja_refs() -> None:
"text_prompt",
{
"prompt": (
- "Summarize {{ extract_article_info.output.extracted_information.abstract }} "
- "and {{ extract_article_info.title }}."
+ "Summarize {{ extract_article_info.output.abstract }} and {{ extract_article_info.title }}."
)
},
),
@@ -1133,7 +1132,96 @@ def test_referenced_output_labels_finds_block_form_jinja_refs() -> None:
assert refs == {"extract_article_info"}
-def test_plan_frontier_append_with_block_form_jinja_ref_falls_back_to_full_run() -> None:
+def test_referenced_output_labels_finds_bare_block_form_jinja_refs() -> None:
+ new = _FakeDefinition(
+ [
+ _FakeBlock("extract_article_info", "extraction"),
+ _FakeBlock(
+ "summarize_article",
+ "text_prompt",
+ {"prompt": "Summarize {{ extract_article_info }} in one sentence."},
+ ),
+ ]
+ )
+
+ refs = _referenced_output_labels(["summarize_article"], new)
+
+ assert refs == {"extract_article_info"}
+
+
+def test_referenced_output_labels_finds_every_ref_in_one_expression() -> None:
+ new = _FakeDefinition(
+ [
+ _FakeBlock("extract_article_info", "extraction"),
+ _FakeBlock("extract_author", "extraction"),
+ _FakeBlock(
+ "summarize_article",
+ "text_prompt",
+ {"prompt": "{{ extract_article_info.output.title ~ extract_author.output.name }}"},
+ ),
+ ]
+ )
+
+ refs = _referenced_output_labels(["summarize_article"], new)
+
+ assert refs == {"extract_article_info", "extract_author"}
+
+
+def test_referenced_output_labels_finds_a_ref_in_a_templated_mapping_key() -> None:
+ new = _FakeDefinition(
+ [
+ _FakeBlock("extract_result", "extraction"),
+ _FakeBlock(
+ "report_failure",
+ "text_prompt",
+ # error_code_mapping renders its keys, so a key can carry the only reference.
+ {"error_code_mapping": {"ERR_{{ extract_result.output.code }}": "the run failed"}},
+ ),
+ ]
+ )
+
+ refs = _referenced_output_labels(["report_failure"], new)
+
+ assert refs == {"extract_result"}
+
+
+def test_referenced_output_labels_finds_refs_around_a_quoted_jinja_literal() -> None:
+ new = _FakeDefinition(
+ [
+ _FakeBlock("extract_article_info", "extraction"),
+ _FakeBlock("extract_author", "extraction"),
+ _FakeBlock(
+ "summarize_article",
+ "text_prompt",
+ # The config is serialized as JSON, so these quotes reach the classifier escaped.
+ {"prompt": '{{ extract_article_info.output.title ~ " by " ~ extract_author.output.name }}'},
+ ),
+ ]
+ )
+
+ refs = _referenced_output_labels(["summarize_article"], new)
+
+ assert refs == {"extract_article_info", "extract_author"}
+
+
+def test_referenced_output_labels_finds_a_bare_ref_followed_by_an_operator() -> None:
+ new = _FakeDefinition(
+ [
+ _FakeBlock("extract_article_info", "extraction"),
+ _FakeBlock(
+ "summarize_article",
+ "text_prompt",
+ {"prompt": "Summarize {{ extract_article_info or {} }} in one sentence."},
+ ),
+ ]
+ )
+
+ refs = _referenced_output_labels(["summarize_article"], new)
+
+ assert refs == {"extract_article_info"}
+
+
+def test_plan_frontier_falls_back_to_a_full_run_when_a_bare_ref_has_no_verified_output() -> None:
old = _FakeDefinition(
[
_FakeBlock("open_page", "navigation"),
@@ -1147,12 +1235,35 @@ def test_plan_frontier_append_with_block_form_jinja_ref_falls_back_to_full_run()
_FakeBlock(
"summarize_article",
"text_prompt",
- {
- "prompt": (
- "Summarize the main findings from "
- "{{ extract_article_info.output.extracted_information.abstract }}."
- )
- },
+ {"prompt": "Summarize {{ extract_article_info }} in one sentence."},
+ ),
+ ]
+ )
+ ctx = _make_ctx()
+ ctx.verified_prefix_labels = ["open_page", "extract_article_info"]
+ ctx.verified_block_outputs = {"open_page": "nav_ok"}
+
+ requested = ["open_page", "extract_article_info", "summarize_article"]
+ labels, seed, frontier, _provenance = _plan_frontier(ctx, requested, old, new)
+
+ assert (labels, seed, frontier) == (requested, {}, "open_page")
+
+
+def test_plan_frontier_append_with_block_form_jinja_ref_seeds_the_prefix_output() -> None:
+ old = _FakeDefinition(
+ [
+ _FakeBlock("open_page", "navigation"),
+ _FakeBlock("extract_article_info", "extraction", {"prompt": "extract abstract"}),
+ ]
+ )
+ new = _FakeDefinition(
+ [
+ _FakeBlock("open_page", "navigation"),
+ _FakeBlock("extract_article_info", "extraction", {"prompt": "extract abstract"}),
+ _FakeBlock(
+ "summarize_article",
+ "text_prompt",
+ {"prompt": ("Summarize the main findings from {{ extract_article_info.output.abstract }}.")},
),
]
)
@@ -1170,9 +1281,12 @@ def test_plan_frontier_append_with_block_form_jinja_ref_falls_back_to_full_run()
new,
)
- assert labels == ["open_page", "extract_article_info", "summarize_article"]
- assert seed == {}
- assert frontier == "open_page"
+ assert labels == ["summarize_article"]
+ assert seed == {
+ "open_page": "nav_ok",
+ "extract_article_info": {"extracted_information": {"abstract": "Prior output"}},
+ }
+ assert frontier == "summarize_article"
def test_plan_frontier_append_seeds_output_parameter_jinja_ref() -> None:
diff --git a/tests/unit/test_mcp_block_tools.py b/tests/unit/test_mcp_block_tools.py
index a058d3ef9..f73145160 100644
--- a/tests/unit/test_mcp_block_tools.py
+++ b/tests/unit/test_mcp_block_tools.py
@@ -4,18 +4,25 @@ from __future__ import annotations
import inspect
import json
+import re
+from datetime import UTC, datetime
from pathlib import Path
+from unittest.mock import MagicMock
import pytest
from skyvern.cli.mcp_tools.blocks import (
CODE_BLOCK_RUNTIME_TOPIC,
WORKFLOW_KNOWLEDGE_TOPIC_HEADERS,
+ _parse_knowledge_topics,
skyvern_block_schema,
skyvern_block_validate,
skyvern_workflow_knowledge,
)
-from skyvern.forge.sdk.workflow.models.block import CodeBlock
+from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext
+from skyvern.forge.sdk.workflow.exceptions import FailedToFormatJinjaStyleParameter, MissingJinjaVariables
+from skyvern.forge.sdk.workflow.models.block import CodeBlock, TaskBlock
+from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, ParameterType
@pytest.mark.asyncio
@@ -264,3 +271,106 @@ async def test_block_validate_data_export() -> None:
assert result["ok"] is True
assert result["data"]["block_type"] == "data_export"
+
+
+_JINJA_EXPRESSION = re.compile(r"\{\{.*?\}\}")
+
+_BROWSER_TASK_OUTPUT = {"status": "completed", "extracted_information": {"abstract": "a study abstract"}}
+_NON_TASK_OUTPUT = {"summary": "a short summary"}
+# A direct (non-website) download records file fields with no extracted_information, so no .output alias.
+_DIRECT_FILE_DOWNLOAD_OUTPUT = {
+ "file_name": "report.pdf",
+ "downloaded_files": [{"url": "https://files.example.test/report.pdf", "filename": "report.pdf"}],
+ "downloaded_file_urls": ["https://files.example.test/report.pdf"],
+}
+_TEMPLATING_FAMILY_OUTPUTS = {
+ "label": _BROWSER_TASK_OUTPUT,
+ "extract_items": _BROWSER_TASK_OUTPUT,
+ "get_data": _BROWSER_TASK_OUTPUT,
+ "summarize_notes": _NON_TASK_OUTPUT,
+ "fetch_report": _DIRECT_FILE_DOWNLOAD_OUTPUT,
+}
+
+
+def _templating_context() -> WorkflowRunContext:
+ ctx = WorkflowRunContext(
+ workflow_title="t",
+ workflow_id="w_kb",
+ workflow_permanent_id="wpid_kb",
+ workflow_run_id="wr_kb",
+ aws_client=MagicMock(),
+ )
+ for label, value in _TEMPLATING_FAMILY_OUTPUTS.items():
+ ctx.register_block_reference_variable(label, value)
+ return ctx
+
+
+def _refuted_expressions(line: str) -> set[str]:
+ """The section refutes a shape either as "X raises ..." or as "Y (NOT X)"."""
+ if "raises" in line:
+ return set(_JINJA_EXPRESSION.findall(line.split("raises", 1)[0]))
+ if "NOT" in line:
+ return set(_JINJA_EXPRESSION.findall(line.split("NOT", 1)[1]))
+ return set()
+
+
+def _documented_block_output_expressions() -> tuple[set[str], set[str]]:
+ section = _parse_knowledge_topics()["parameter_templating"]["content"]
+ taught: set[str] = set()
+ refuted: set[str] = set()
+ for line in section.splitlines():
+ line_refuted = _refuted_expressions(line)
+ for expression in _JINJA_EXPRESSION.findall(line):
+ if "<" in expression:
+ continue
+ root = expression.strip("{} ").split(".")[0].split("|")[0].strip()
+ if root not in _TEMPLATING_FAMILY_OUTPUTS:
+ continue
+ (refuted if expression in line_refuted else taught).add(expression)
+ return taught - refuted, refuted
+
+
+def _kb_block() -> TaskBlock:
+ return TaskBlock(
+ label="downstream",
+ title="t",
+ output_parameter=OutputParameter(
+ parameter_type=ParameterType.OUTPUT,
+ key="downstream_output",
+ output_parameter_id="op_kb",
+ workflow_id="w_kb",
+ created_at=datetime.now(UTC),
+ modified_at=datetime.now(UTC),
+ ),
+ )
+
+
+def test_parameter_templating_block_output_examples_match_the_real_registrar() -> None:
+ taught, refuted = _documented_block_output_expressions()
+ taught_roots = {expression.strip("{} ").split(".")[0].split("|")[0].strip() for expression in taught}
+ assert taught_roots == set(_TEMPLATING_FAMILY_OUTPUTS)
+ assert len(taught) >= len(_TEMPLATING_FAMILY_OUTPUTS) + 2
+ assert refuted
+
+ ctx = _templating_context()
+ block = _kb_block()
+
+ for expression in sorted(taught):
+ assert block.format_block_parameter_template_from_workflow_run_context(expression, ctx), expression
+
+ for expression in sorted(refuted):
+ with pytest.raises((FailedToFormatJinjaStyleParameter, MissingJinjaVariables)):
+ block.format_block_parameter_template_from_workflow_run_context(expression, ctx)
+
+
+def test_parameter_templating_block_output_examples_resolve_to_the_documented_values() -> None:
+ ctx = _templating_context()
+ block = _kb_block()
+
+ def render(expression: str) -> str:
+ return block.format_block_parameter_template_from_workflow_run_context(expression, ctx)
+
+ assert render("{{ label.output }}") == render("{{ label.extracted_information }}")
+ assert "a study abstract" in render("{{ label.output }}")
+ assert "extracted_information" in render("{{ label }}")
+ assert render("{{ summarize_notes.summary }}") == "a short summary"
diff --git a/tests/unit/test_multi_placeholder_secret_resolution.py b/tests/unit/test_multi_placeholder_secret_resolution.py
index 70b82077b..caa5e8da0 100644
--- a/tests/unit/test_multi_placeholder_secret_resolution.py
+++ b/tests/unit/test_multi_placeholder_secret_resolution.py
@@ -17,6 +17,7 @@ def _make_context(secrets: dict[str, str]) -> WorkflowRunContext:
ctx.values = {}
ctx.parameters = {}
ctx.workflow_run_outputs = {}
+ ctx.carried_block_labels = set()
ctx.credential_totp_identifiers = {}
return ctx
diff --git a/tests/unit/workflow/test_http_request_block.py b/tests/unit/workflow/test_http_request_block.py
index 34a3c61a1..4796dec8e 100644
--- a/tests/unit/workflow/test_http_request_block.py
+++ b/tests/unit/workflow/test_http_request_block.py
@@ -26,6 +26,7 @@ def _make_context(
context.values = dict(values or {})
context.parameters = {}
context.workflow_run_outputs = {}
+ context.carried_block_labels = set()
context.blocks_metadata = {}
context.include_secrets_in_templates = False
context.credential_totp_identifiers = {}
diff --git a/tests/unit/workflow/test_task_block_template_rendering.py b/tests/unit/workflow/test_task_block_template_rendering.py
index 68176cedf..7eeeff2e6 100644
--- a/tests/unit/workflow/test_task_block_template_rendering.py
+++ b/tests/unit/workflow/test_task_block_template_rendering.py
@@ -1,13 +1,17 @@
from datetime import datetime, timezone
+from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from jinja2 import StrictUndefined
+from jinja2.sandbox import SandboxedEnvironment
+from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext
-from skyvern.forge.sdk.workflow.exceptions import FailedToFormatJinjaStyleParameter
+from skyvern.forge.sdk.workflow.exceptions import FailedToFormatJinjaStyleParameter, MissingJinjaVariables
from skyvern.forge.sdk.workflow.models.block import FileDownloadBlock, HumanInteractionBlock, TaskBlock
from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, ParameterType
-from skyvern.utils.templating import get_available_keys
+from skyvern.utils.templating import MAX_AVAILABLE_KEY_LENGTH, get_available_keys
def _make_output_parameter(key: str = "task_output") -> OutputParameter:
@@ -22,7 +26,7 @@ def _make_output_parameter(key: str = "task_output") -> OutputParameter:
)
-def _make_workflow_run_context(values: dict | None = None) -> WorkflowRunContext:
+def _make_workflow_run_context(values: dict[str, Any] | None = None) -> WorkflowRunContext:
ctx = WorkflowRunContext(
workflow_title="test",
workflow_id="w_task_template_test",
@@ -134,7 +138,7 @@ def test_jinja_render_failure_carries_available_keys() -> None:
with pytest.raises(FailedToFormatJinjaStyleParameter) as exc_info:
block.format_potential_template_parameters(ctx)
- assert {"status", "url"}.issubset(set(exc_info.value.available_keys))
+ assert {"a_output.status", "a_output.url"}.issubset(set(exc_info.value.available_keys))
assert str(exc_info.value).startswith(
"Failed to format Jinja style parameter '{{ a_output.missing_key.id }}'. Reason: "
)
@@ -152,7 +156,7 @@ def test_jinja_render_failure_available_keys_walks_list_index() -> None:
with pytest.raises(FailedToFormatJinjaStyleParameter) as exc_info:
block.format_potential_template_parameters(ctx)
- assert {"sku", "qty"}.issubset(set(exc_info.value.available_keys))
+ assert {"items[0].sku", "items[0].qty"}.issubset(set(exc_info.value.available_keys))
def test_jinja_literal_braces_survive_undeclared_field_and_parameter_value() -> None:
@@ -216,14 +220,29 @@ def test_jinja_failure_output_never_merges_across_loop_iterations() -> None:
assert ctx.values["task"]["output"] == {"sku": "b"}
-def test_jinja_available_keys_are_names_only_and_bounded() -> None:
+def test_jinja_available_keys_are_paste_able_paths_not_bare_names() -> None:
secret = "parameter-secret-value-15419"
- long_key = "k" * 500
- keys = get_available_keys("{{ a.missing }}", {"a": {"token": secret, long_key: 1}, "top": secret})
+ long_key = "k" * (MAX_AVAILABLE_KEY_LENGTH + 1)
+ template_data = {
+ "a": {"token": secret, long_key: 1, "items": 2, "by region": {"north-west": 3}, 7: "seven"},
+ "rows": [{"sku": "x"}],
+ "top": secret,
+ }
+
+ keys = get_available_keys("{{ a.missing }} {{ rows[0].missing }}", template_data)
+ env = SandboxedEnvironment(undefined=StrictUndefined)
- assert "token" in keys and "top" in keys
+ assert {"a.token", 'a["items"]', "rows[0].sku", "top"}.issubset(set(keys))
+ # A bare child name reads as a top-level binding and renders nothing, which is what the model
+ # pasted in production, so it is never published.
+ assert "token" not in keys and "sku" not in keys
assert secret not in " ".join(keys)
- assert max(len(key) for key in keys) == 128
+ assert not any(long_key in key for key in keys)
+ for key in keys:
+ env.from_string("{{ " + key + " }}").render(template_data)
+ assert env.from_string('{{ a["items"] }}').render(template_data) == "2"
+ assert "a[7]" in keys and 'a["7"]' not in keys
+ assert env.from_string("{{ a[7] }}").render(template_data) == "seven"
@pytest.mark.asyncio
@@ -242,3 +261,167 @@ async def test_jinja_failure_result_surfaces_redacted_payload_on_the_block_resul
assert result.output_parameter_value == record_output.await_args.args[2]
assert result.output_parameter_value["failure_reason"] == "Failed to format jinja template: boom [redacted]"
assert result.output_parameter_value["available_keys"] == ["[redacted]", "status"]
+
+
+async def test_jinja_failure_result_preserves_available_keys_when_exception_is_wrapped() -> None:
+ secret_value = "secret-value-abc"
+ ctx = _make_workflow_run_context()
+ ctx.secrets["sensitive_key"] = secret_value
+ block = TaskBlock(label="task", output_parameter=_make_output_parameter(), title="t")
+
+ inner_exc = FailedToFormatJinjaStyleParameter(
+ "{{ extract.missing }}", "boom", available_keys=[secret_value, "result"]
+ )
+ middle_exc = ValueError("wrapped error message")
+ middle_exc.__cause__ = inner_exc
+ wrapped_exc = RuntimeError("wrapped twice")
+ wrapped_exc.__cause__ = middle_exc
+
+ with patch.object(TaskBlock, "record_output_parameter_value", AsyncMock()) as record_output:
+ result = await block._template_format_failure_result(
+ wrapped_exc, "Failed to format jinja template: boom", ctx, "wr-1", None, None
+ )
+
+ assert result.output_parameter_value == record_output.await_args.args[2]
+ assert result.output_parameter_value["available_keys"] == ["[redacted]", "result"]
+
+
+async def _scoped_context(block_outputs: dict[str, Any]) -> WorkflowRunContext:
+ return await WorkflowRunContext.init(
+ aws_client=MagicMock(),
+ organization=Organization(
+ organization_id="o_task_template_test",
+ organization_name="test",
+ created_at=datetime.now(timezone.utc),
+ modified_at=datetime.now(timezone.utc),
+ ),
+ workflow_run_id="wr_task_template_test",
+ workflow_title="test",
+ workflow_id="w_task_template_test",
+ workflow_permanent_id="wpid_task_template_test",
+ workflow_parameter_tuples=[],
+ workflow_output_parameters=[],
+ context_parameters=[],
+ secret_parameters=[],
+ block_outputs=block_outputs,
+ )
+
+
+def _full_run_context(label: str, value: dict[str, Any]) -> WorkflowRunContext:
+ ctx = _make_workflow_run_context()
+ ctx.register_block_reference_variable_from_output_parameter(_make_output_parameter(f"{label}_output"), value)
+ return ctx
+
+
+CARRIED_EXTRACTION_OUTPUT = {
+ "status": "completed",
+ "extracted_information": {"failure_rate": "25.65%"},
+}
+
+
+async def test_scoped_rerun_renders_block_references_identically_to_a_full_run() -> None:
+ block = TaskBlock(label="write_row", output_parameter=_make_output_parameter(), title="t")
+ scoped = await _scoped_context({"extract_failure_rate": CARRIED_EXTRACTION_OUTPUT})
+ full_run = _full_run_context("extract_failure_rate", CARRIED_EXTRACTION_OUTPUT)
+
+ for expression in (
+ "{{ extract_failure_rate.output.failure_rate }}",
+ "{{ extract_failure_rate.extracted_information.failure_rate }}",
+ "{{ extract_failure_rate.status }}",
+ ):
+ scoped_rendered = block.format_block_parameter_template_from_workflow_run_context(expression, scoped)
+ full_run_rendered = block.format_block_parameter_template_from_workflow_run_context(expression, full_run)
+ assert scoped_rendered == full_run_rendered
+ assert scoped_rendered
+
+ assert (
+ block.format_block_parameter_template_from_workflow_run_context(
+ "{{ extract_failure_rate.output.failure_rate }}", scoped
+ )
+ == "25.65%"
+ )
+
+
+async def test_scoped_rerun_leaves_a_label_without_a_carried_output_undefined() -> None:
+ block = TaskBlock(label="write_row", output_parameter=_make_output_parameter(), title="t")
+ scoped = await _scoped_context({"extract_failure_rate": CARRIED_EXTRACTION_OUTPUT})
+
+ assert "never_ran" not in scoped.values
+ with pytest.raises((FailedToFormatJinjaStyleParameter, MissingJinjaVariables)):
+ block.format_block_parameter_template_from_workflow_run_context("{{ never_ran.output }}", scoped)
+
+
+async def test_scoped_rerun_keeps_carried_labels_out_of_workflow_run_outputs() -> None:
+ scoped = await _scoped_context({"extract_failure_rate": CARRIED_EXTRACTION_OUTPUT})
+
+ assert scoped.values["extract_failure_rate"]["output"] == {"failure_rate": "25.65%"}
+ assert "extract_failure_rate" not in scoped.workflow_run_outputs
+ summary = scoped.build_workflow_run_summary()
+ assert summary["status"] is None
+ assert summary["output"] == {"extracted_information": {}}
+
+
+async def test_scoped_rerun_never_reports_a_carried_payload_as_this_runs_result() -> None:
+ block = TaskBlock(label="write_row", output_parameter=_make_output_parameter(), title="t")
+ carried_failure = {
+ "status": "failed",
+ "failure_reason": "the prior run could not open the sheet",
+ "errors": [{"reason": "prior run error"}],
+ "downloaded_files": [{"path": "/tmp/prior-run.csv"}],
+ "extracted_information": {"failure_rate": "25.65%"},
+ }
+ scoped = await _scoped_context({"extract_failure_rate": carried_failure})
+
+ summary = scoped.build_workflow_run_summary()
+ assert summary["status"] is None
+ assert summary["failure_reason"] is None
+ assert summary["errors"] == []
+ assert summary["downloaded_files"] == []
+ assert summary["output"] == {"extracted_information": {}}
+
+ assert "extract_failure_rate" not in scoped.workflow_run_outputs
+ assert (
+ block.format_block_parameter_template_from_workflow_run_context(
+ "{{ extract_failure_rate.output.failure_rate }}", scoped
+ )
+ == "25.65%"
+ )
+
+
+async def test_a_carried_label_that_executes_this_run_is_reported_again() -> None:
+ scoped = await _scoped_context({"extract_failure_rate": CARRIED_EXTRACTION_OUTPUT})
+ scoped.register_block_reference_variable_from_output_parameter(
+ _make_output_parameter("extract_failure_rate_output"),
+ {"status": "failed", "failure_reason": "this run failed", "errors": [{"reason": "this run"}]},
+ )
+
+ summary = scoped.build_workflow_run_summary()
+ assert summary["status"] == "failed"
+ assert summary["failure_reason"] == "this run failed"
+ assert summary["errors"] == [{"reason": "this run"}]
+
+
+async def test_a_carried_success_is_replaced_by_this_runs_success_rather_than_merged() -> None:
+ carried_success = {
+ "status": "completed",
+ "extracted_information": {"failure_rate": "25.65%"},
+ "downloaded_files": [{"path": "/tmp/prior-run.csv"}],
+ "errors": [{"reason": "prior run error"}],
+ }
+ scoped = await _scoped_context({"extract_failure_rate": carried_success})
+ scoped.register_block_reference_variable_from_output_parameter(
+ _make_output_parameter("extract_failure_rate_output"),
+ {"status": "completed", "extracted_information": {"failure_rate": "31.02%"}},
+ )
+
+ summary = scoped.build_workflow_run_summary()
+ assert summary["downloaded_files"] == []
+ assert summary["errors"] == []
+ assert summary["output"] == {"extracted_information": {"failure_rate": "31.02%"}}