Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Record generated-code execution failures for Copilot repair (#8329)
Aaron Perez52b5d14e6d49
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 095107b93..b9827a027 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -1073,6 +1073,13 @@ def _recorded_build_test_outcome_prompt(ctx: CopilotContext | None) -> str:f"page_evidence_refs: {_render_authoring_repair_prompt_list(outcome.page_evidence_refs)}",f"evidence_refs: {_render_authoring_repair_prompt_list(outcome.evidence_refs)}",]+ # Without this an unavailable capture is indistinguishable from a page that had nothing on it.+ page_capture = outcome.page_capture+ if page_capture is not None:+ capture_fields = f"status={_clean_authoring_repair_prompt_atom(page_capture.status)}"+ if page_capture.omission:+ capture_fields += f"; omission={_clean_authoring_repair_prompt_atom(page_capture.omission)}"+ lines.append(f"page_capture: {capture_fields}")if outcome.missing_requested_output_facts:lines.append("missing_requested_output_facts:")lines.append(@@ -1526,13 +1533,19 @@ def _review_projection_for(ctx: CopilotContext, proposal_yaml: str | None) -> Nadef _tested_draft_reply(ctx: CopilotContext,- review: NarrativeReviewProjection | None,+ proposal_yaml: str | None,*,tested_reply: str,unvalidated_reply: str,) -> str:- """The reply and the proposal disposition read one predicate, so prose cannot outrun the pill."""- tested = _turn_facts_for_context(ctx, review)["ranCleanOnCurrentSource"]+ """The reply and the proposal disposition read one predicate, so prose cannot outrun the pill.++ Takes the proposal rather than a built projection so the projection and the open-failure check+ cannot end up describing two different documents.+ """+ tested = _turn_facts_for_context(ctx, _review_projection_for(ctx, proposal_yaml), proposal_yaml)[+ "ranCleanOnCurrentSource"+ ]return tested_reply if tested else unvalidated_reply@@ -1562,13 +1575,23 @@ def _turn_fact_bundle(return facts-def _turn_facts_for_context(ctx: CopilotContext, review: NarrativeReviewProjection | None) -> NarrativeTurnFacts:+def _turn_facts_for_context(+ ctx: CopilotContext,+ review: NarrativeReviewProjection | None,+ proposal_yaml: str | None,+) -> NarrativeTurnFacts:return _turn_fact_bundle(review,select_run_outcome_anchor(_terminal_envelope_run_outcomes(ctx)),_terminal_cause_for_context(ctx),len(ctx.executed_block_labels),- unresolved_runtime_block_failure(ctx),+ # The proposal these facts describe, not the turn-start persisted workflow. The terminal+ # seam asks whether the workflow the user can run today still carries the failure and is+ # right to read persistence; this pill claims the draft ran clean, so a failure the draft+ # still carries must keep it, and a repair the draft made must clear it. Reading the+ # turn-start snapshot inverts both: a block authored this turn is always absent from it,+ # and a call the turn only just introduced always reads as already removed.+ unresolved_runtime_block_failure(ctx, reported_workflow_yaml=proposal_yaml),)@@ -1702,7 +1725,7 @@ def _make_agent_result(narrative_payload.get("review") if isinstance(narrative_payload, dict) else None)terminal_cause = _terminal_cause_for_context(ctx) if ctx is not None else None- turn_facts = _turn_facts_for_context(ctx, review_projection) if ctx is not None else None+ turn_facts = _turn_facts_for_context(ctx, review_projection, proposal_yaml) if ctx is not None else Noneresponse_type = kwargs.get("response_type", "REPLY")response_type_value = response_type if isinstance(response_type, str) else "REPLY"raw_disposition = kwargs.get("proposal_disposition")@@ -1782,6 +1805,9 @@ def _make_agent_result(# shown, tested, or auto-applied later, but this terminal is assembled before the route# commits it, so at claim time it is not yet what anyone would run. `workflow_was_persisted`# records a mid-turn canonical write that can still be rolled back, so it proves nothing here.+ # Deliberately a different question from the tested pill above, which judges the proposal:+ # both can hold at once, and a turn that repairs a block it authored this turn will say the+ # draft tested clean while its saved workflow still carries the failure.reported_workflow_yaml = ctx.persisted_workflow_yamlunresolved_failure, detector_disposition = unresolved_runtime_block_failure_with_disposition(ctx, reported_workflow_yaml=reported_workflow_yaml@@ -2945,7 +2971,7 @@ def _build_wip_exit_result(final_text, outcome = _guard(_tested_draft_reply(ctx,- _review_projection_for(ctx, verified_yaml),+ verified_yaml,tested_reply=tested_reply,unvalidated_reply=unvalidated_reply,)@@ -2991,7 +3017,7 @@ def _build_wip_exit_result(append_failure_detail = recorded_failure_reply and not deadline_suppresses_failure_detailheld_reply = _tested_draft_reply(ctx,- _review_projection_for(ctx, ctx.last_good_workflow_yaml),+ ctx.last_good_workflow_yaml,tested_reply=tested_reply,unvalidated_reply=unvalidated_reply,)@@ -3038,7 +3064,7 @@ def _build_wip_exit_result(if unvalidatedelse _tested_draft_reply(ctx,- _review_projection_for(ctx, ctx.last_workflow_yaml),+ ctx.last_workflow_yaml,tested_reply=tested_reply,unvalidated_reply=unvalidated_reply,)diff --git a/skyvern/forge/sdk/copilot/build_test_outcome.py b/skyvern/forge/sdk/copilot/build_test_outcome.pyindex b46c1b08f..ca1947cf1 100644--- a/skyvern/forge/sdk/copilot/build_test_outcome.py+++ b/skyvern/forge/sdk/copilot/build_test_outcome.py@@ -29,7 +29,7 @@ from skyvern.forge.sdk.copilot.request_policy import redact_raw_secrets_for_promfrom skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcomefrom skyvern.forge.sdk.copilot.secret_scrub import scrub_all_registered_from_textfrom skyvern.forge.sdk.schemas.copilot_turn_outcome import UnresolvedRuntimeFailure-from skyvern.schemas.workflows import BlockStatus+from skyvern.schemas.workflows import BlockStatus, BlockTypeLOG = structlog.get_logger()@@ -93,6 +93,29 @@ _INSPECT_PAGE_SOURCE_TOOL = "inspect_page_for_composition"_UNRECOVERABLE_TOOL_ERROR_CATEGORY = "UNRECOVERABLE_TOOL_ERROR"_BROWSER_OPERATION_FAILED: BuildTestFailedOperationKind = "browser_operation_failed"_EXECUTED_BLOCK_STATUSES = frozenset(status.value for status in BlockStatus if status != BlockStatus.skipped)+# Sandbox-process faults, not authored-code faults. ``timeout`` and ``user_code_error`` stay+# out: both are repairable despite also carrying ``runner_internal_error``. ``busy`` is in —+# a saturated runner gate says nothing about the code, so rewriting it cannot help.+INFRASTRUCTURE_RUNNER_ERROR_CODES: frozenset[str] = frozenset(+ {+ "runner_unavailable",+ "protocol_error",+ "internal_error",+ "child_exited",+ "child_no_request",+ "child_malformed_request",+ "busy",+ }+)++# The wider question: which failures no rewrite of the block could have prevented. The sandbox+# faults above, plus the two that end a run from outside it — the browser going away and the run+# being cancelled. Both can pass unchanged on the next attempt, so recording them as authored-code+# failures would hold the block open until an edit that had nothing to do with them.+_NOT_AUTHORED_CODE_ERROR_CODES: frozenset[str] = INFRASTRUCTURE_RUNNER_ERROR_CODES | {+ "browser_disconnected",+ "cancelled",+}_PLAYWRIGHT_LOCATOR_WAIT_RE = re.compile(r"waiting for locator\((?P<quote>['\"])(?P<selector>.*?)(?P=quote)\)"r"(?P<locator_chain>(?:\.[A-Za-z_][A-Za-z0-9_]*(?:\([^)]*\))?)*)\s+to be (?P<state>[a-z_]+)",@@ -1351,9 +1374,7 @@ def recorded_outcome_from_run_blocks_result(attempted_block_label=_redacted_terminal_text(_safe_str(failed_block.get("label"))) or ""if failed_block is not Noneelse "",- attempted_call_ref=selector_identity_from_failure(- _safe_str(failed_block.get("failure_reason")) if failed_block is not None else ""- ),+ attempted_call_ref=_attempted_call_ref(failed_block),verdict=verdict,reason_code=reason_code,workflow_run_id=workflow_run_id or None,@@ -1369,7 +1390,12 @@ def recorded_outcome_from_run_blocks_result(authored_structure_signature=authored_structure_signature,failed_operation=failed_operation,executed_block_associations=executed_block_associations,- observed_evidence_summary=_bounded_text(run_status),+ # The failed block's recorded reason carries the exception and its line; the run status is+ # the word "failed" and says nothing a repair can act on.+ observed_evidence_summary=(+ _bounded_text(failed_block.get("failure_reason")) if failed_block is not None else ""+ )+ or _bounded_text(run_status),key_provenance={"structural_failure_identity": ("typed runtime failure structure"@@ -1471,7 +1497,7 @@ def _code_block_signature_payloads(value: object) -> list[dict[str, object]]:"parameter_keys": _string_list(block.get("parameter_keys")),})- for child_key in ("blocks",):+ for child_key in ("blocks", "loop_blocks"):payloads.extend(_code_block_signature_payloads(block.get(child_key)))for branch in _mapping_list(block.get("branch_conditions")):payloads.extend(_code_block_signature_payloads(branch.get("blocks")))@@ -1627,6 +1653,65 @@ def _referenced_unbound_input_keys(def _runtime_failure_identity(failed_block: Mapping[str, object] | None) -> str:if failed_block is None:return ""+ return _locator_wait_failure_identity(failed_block) or _code_execution_failure_identity(failed_block)+++def _attempted_call_ref(failed_block: Mapping[str, object] | None) -> str:+ """The selector whose removal clears this failure, and only when the failure is about it.++ Clearance treats a call ref as the one thing that must change, so a reason that merely mentions+ a locator must not carry one: a code-execution failure is repaired by rewriting the block, which+ the block signature already witnesses, and demanding the selector be dropped strands a repair+ that correctly kept it.+ """+ if failed_block is None:+ return ""+ if not _locator_wait_failure_identity(failed_block) and _code_execution_failure_identity(failed_block):+ return ""+ return selector_identity_from_failure(_safe_str(failed_block.get("failure_reason")))+++def _is_code_block_failure(failed_block: Mapping[str, object] | None) -> bool:+ """A native block's failure is the agent's run, not authored code, and has no code signature to+ change, so it has no route out of an unresolved-failure note."""+ return failed_block is not None and _safe_str(failed_block.get("block_type")).upper() == BlockType.CODE.name+++def _runner_authored_reason(failure_reason: str) -> str:+ """The part of a runner failure reason this repository wrote, without the exception's own words.++ ``codeblock/workflow.py::_with_failure_detail`` builds the reason as a fixed phrase, optionally+ ``at line N``, then ``": "`` and the raised exception's message. Only the part before that+ delimiter is ours; the message after it is authored by the failing code, so a value it quotes+ would otherwise decide whether two runs count as the same failure.+ """+ return failure_reason.split(": ", 1)[0].strip()+++def _code_execution_failure_identity(failed_block: Mapping[str, object]) -> str:+ """Identity of a generated-code execution failure: the runner's typed error codes and the+ account of the failure the runner itself authored.++ Without this a raised exception carries no identity at all, so two different exceptions in the+ same block are indistinguishable and a run whose only evidence is the raise records nothing.+ """+ if not _is_code_block_failure(failed_block):+ return ""+ error_codes = _clean_list(_string_list(failed_block.get("error_codes")))+ if not error_codes or any(code in _NOT_AUTHORED_CODE_ERROR_CODES for code in error_codes):+ return ""+ return _stable_hash(+ {+ "source": "generated_code_execution",+ "error_codes": error_codes,+ "runner_reason": _runner_authored_reason(_safe_str(failed_block.get("failure_reason"))),+ "block_label": _safe_str(failed_block.get("label")),+ "block_status": _safe_str(failed_block.get("status")),+ }+ )+++def _locator_wait_failure_identity(failed_block: Mapping[str, object]) -> str:failure_reason = _safe_str(failed_block.get("failure_reason"))if not failure_reason:return ""diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.pyindex a49f6bea3..10316b06e 100644--- a/skyvern/forge/sdk/copilot/tools/run_execution.py+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py@@ -29,6 +29,7 @@ from skyvern.forge.sdk.copilot.blocker_signal import (stash_blocker_signal,)from skyvern.forge.sdk.copilot.build_test_outcome import (+ INFRASTRUCTURE_RUNNER_ERROR_CODES,BuildTestEvidencePacket,BuildTestPacketDownload,BuildTestPacketFailure,@@ -268,21 +269,6 @@ _SANDBOX_REQUIRED_BLOCK_TYPES = frozenset(})-# Sandbox-process faults, not authored-code faults. ``timeout`` and ``user_code_error`` stay-# out: both are repairable despite also carrying ``runner_internal_error``. ``busy`` is in —-# a saturated runner gate says nothing about the code, so rewriting it cannot help.-INFRASTRUCTURE_RUNNER_ERROR_CODES: frozenset[str] = frozenset(- {- "runner_unavailable",- "protocol_error",- "internal_error",- "child_exited",- "child_no_request",- "child_malformed_request",- "busy",- }-)-# Detached cleanup tasks held here so the garbage collector does not drop them# while they still have work to do, and so the "task exception was never# retrieved" warning cannot fire — each task adds a done-callback that logs@@ -648,15 +634,9 @@ async def _recorded_watchdog_block_receipts(workflow_run_id: str, organization_iexcept Exception:LOG.debug("Failed to load block receipts after watchdog exit", workflow_run_id=workflow_run_id, exc_info=True)return []- receipts: list[dict[str, Any]] = []- for block in blocks:- label = getattr(block, "label", None)- raw_status = getattr(block, "status", None)- enum_value = getattr(raw_status, "value", None)- status = enum_value if isinstance(enum_value, str) else raw_status- if isinstance(status, str) and status:- receipts.append({"label": label if isinstance(label, str) and label else None, "status": status})- return receipts+ # The same projection a normal run's receipts get: a block that failed before the watchdog exit+ # failed for a reason, and dropping it here left that failure with no identity to repair.+ return [_recorded_run_block_result(block) for block in blocks if block.status]def _forget_browser_position(ctx: CopilotContext) -> None:diff --git a/tests/unit/fixtures/copilot/generated_code_exception/packet.json b/tests/unit/fixtures/copilot/generated_code_exception/packet.jsonnew file mode 100644index 000000000..c8ef354b6--- /dev/null+++ b/tests/unit/fixtures/copilot/generated_code_exception/packet.json@@ -0,0 +1,45 @@+{+ "schema": "generated-code-exception-packet-v1",+ "provenance": "runner response produced by tests/browser_e2e/test_workflow_copilot_generated_code_exception_repair.py against a live Chromium page",+ "runner_exception_class": "builtins.NameError",+ "runner_failing_line": 2,+ "workflow_yaml": "workflow_definition:\n parameters: []\n blocks:\n - block_type: code\n label: price_the_trip\n code: |\n fare = float(await page.locator(\"#fare\").inner_text())\n total = fare * passenger_count\n return {\"total\": f\"{total:.2f}\"}\n",+ "repaired_workflow_yaml": "workflow_definition:\n parameters: []\n blocks:\n - block_type: code\n label: price_the_trip\n code: |\n fare = float(await page.locator(\"#fare\").inner_text())\n passenger_count = int(await page.locator(\"#pax\").inner_text())\n total = fare * passenger_count\n return {\"total\": f\"{total:.2f}\"}\n",+ "recorded_run_outcome": {+ "verdict": "not_demonstrated",+ "reason_code": "blocker_reported",+ "display_reason": "CodeBlock failed with NameError at line 2: name 'passenger_count' is not defined.",+ "workflow_run_id": "wr_generated_code_exception_fixture",+ "run_completed": false+ },+ "result": {+ "ok": false,+ "data": {+ "workflow_run_id": "wr_generated_code_exception_fixture",+ "browser_session_id": "pbs_generated_code_exception_fixture",+ "overall_status": "failed",+ "requested_block_labels": [+ "price_the_trip"+ ],+ "executed_block_labels": [+ "price_the_trip"+ ],+ "post_run_page_capture": {+ "status": "unavailable",+ "omission": "page_capture_unavailable"+ },+ "blocks": [+ {+ "label": "price_the_trip",+ "block_type": "CODE",+ "status": "failed",+ "workflow_run_block_id": "wrb_generated_code_exception_fixture",+ "failure_reason": "CodeBlock failed with NameError at line 2: name 'passenger_count' is not defined.",+ "error_codes": [+ "user_code_error"+ ]+ }+ ]+ }+ }+}diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.pyindex 2268d236c..f5d99958a 100644--- a/tests/unit/test_copilot_agent_helpers.py+++ b/tests/unit/test_copilot_agent_helpers.py@@ -33,6 +33,7 @@ from skyvern.forge.sdk.copilot.build_test_outcome import (PostRunPagePathFailure,RecordedBuildTestOutcome,record_build_test_outcome,+ recorded_outcome_from_run_blocks_result,)from skyvern.forge.sdk.copilot.completion_criteria_store import (StoredCriteriaSet,@@ -6302,6 +6303,88 @@ workflow_definition:assert rendered["facts"]["runCompleted"] is Trueassert rendered["disposition"] == "review_untested"+ @staticmethod+ def _code_yaml(body: str) -> str:+ return f"workflow_definition:\n blocks:\n - block_type: code\n label: price\n code: |\n {body}\n"++ @staticmethod+ def _raised_run(run_id: str, failure_reason: str) -> Any:+ return recorded_outcome_from_run_blocks_result(+ {+ "ok": False,+ "data": {+ "workflow_run_id": run_id,+ "overall_status": "failed",+ "requested_block_labels": ["price"],+ "blocks": [+ {+ "label": "price",+ "block_type": "CODE",+ "status": "failed",+ "failure_reason": failure_reason,+ "error_codes": ["user_code_error"],+ }+ ],+ },+ }+ )++ def _proposed_after_code_failure(+ self,+ failure_reason: str,+ proposal: str,+ *,+ persisted: str = "workflow_definition:\n blocks: []\n",+ raised: str | None = None,+ ) -> dict[str, Any]:+ """A code block fails mid-turn, then the turn proposes ``proposal``.++ ``persisted_workflow_yaml`` stays at the turn-start snapshot because nothing writes it+ mid-turn; a test that hand-sets it to the proposal cannot see either failure direction.+ """+ raised = raised or self._code_yaml("total = fare * pax")+ ctx = _ctx(+ persisted_workflow_yaml=persisted,+ workflow_yaml=raised,+ last_run_outcome=_clean_recorded_run(),+ )+ record_build_test_outcome(ctx, self._raised_run("wr_raised", failure_reason))+ ctx.workflow_yaml = proposal+ record_build_test_outcome(ctx, passing_run("wr_later", ["price"]))+ ctx.executed_block_fingerprints = {+ label: set(fingerprints) for label, fingerprints in workflow_block_fingerprints(proposal).items()+ }+ ctx.executed_block_labels = {"price"}+ return self._render(ctx, proposal)++ def test_a_repaired_and_passing_code_failure_keeps_the_tested_pill(self) -> None:+ """The block raised, the model rewrote it, and the re-run passed, so the turn is tested."""+ rendered = self._proposed_after_code_failure(+ "CodeBlock failed with NameError at line 1: name 'fare' is not defined.",+ self._code_yaml("total = float(await page.locator('#fare').inner_text())"),+ )++ assert rendered["facts"]["ranCleanOnCurrentSource"] is True+ assert rendered["disposition"] == "review_tested"++ def test_a_proposal_still_carrying_the_failing_call_never_reads_as_tested(self) -> None:+ """The pill claims the proposal ran clean, so a later passing run cannot launder a draft+ that still carries the call the failure named.++ The turn-start workflow does carry the block but not that call, so reading persistence here+ would report the call as already removed and hand the draft a tested pill it never earned.+ """+ failing_call = 'await page.locator("#pay-now").click()'+ rendered = self._proposed_after_code_failure(+ 'Timeout 30000ms exceeded. Call log: waiting for locator("#pay-now") to be visible',+ self._code_yaml(failing_call),+ persisted=self._code_yaml('await page.goto("https://shop.test/cart")'),+ raised=self._code_yaml(failing_call),+ )++ assert rendered["facts"]["ranCleanOnCurrentSource"] is False+ assert rendered["disposition"] == "review_untested"+def test_full_coverage_over_an_unconfirmed_outcome_drops_the_tested_pill(self) -> None:staged = self._two_block_yaml()ctx = _ctx(diff --git a/tests/unit/test_copilot_build_test_outcome.py b/tests/unit/test_copilot_build_test_outcome.pyindex b425402f0..966010102 100644--- a/tests/unit/test_copilot_build_test_outcome.py+++ b/tests/unit/test_copilot_build_test_outcome.py@@ -57,6 +57,7 @@ from skyvern.forge.sdk.copilot.tools.run_execution import (build_test_evidence_packet,)from skyvern.forge.sdk.copilot.workflow_yaml import runner_code_block_associations+from skyvern.forge.sdk.schemas.copilot_turn_outcome import UnresolvedRuntimeFailurefrom skyvern.forge.sdk.workflow.models.block import CodeBlockfrom skyvern.forge.sdk.workflow.models.parameter import OutputParameter, ParameterTypefrom skyvern.webeye.browser_artifacts import BrowserArtifacts@@ -1441,6 +1442,289 @@ def _run_history_ctx(workflow_yaml: str) -> SimpleNamespace:)+def _raising_code_workflow_yaml(code: str) -> str:+ return (+ "workflow_definition:\n"+ " parameters: []\n"+ " blocks:\n"+ " - block_type: code\n"+ " label: book_trip\n"+ " code: |\n" + "".join(f" {line}\n" for line in code.splitlines())+ )+++def _generated_code_exception_result(+ workflow_run_id: str,+ failure_reason: str,+) -> dict[str, object]:+ return {+ "ok": False,+ "data": {+ "workflow_run_id": workflow_run_id,+ "browser_session_id": "pbs_trip",+ "overall_status": "failed",+ "requested_block_labels": ["book_trip"],+ "executed_block_labels": ["book_trip"],+ # The run reached the page but retained no usable evidence of it, which is the shape+ # that used to erase the whole outcome.+ "post_run_page_capture": {"status": "unavailable", "omission": "page_capture_unavailable"},+ "blocks": [+ {+ "label": "book_trip",+ "block_type": "CODE",+ "status": "failed",+ "workflow_run_block_id": "wrb_trip",+ "failure_reason": failure_reason,+ "error_codes": ["user_code_error"],+ }+ ],+ },+ }+++def test_generated_code_exception_reaches_repair_and_needs_a_changed_submission() -> None:+ """A raised exception is the only evidence: no page state, no outputs, no failure categories."""+ raising_code = "total = passenger_count * fare\nawait page.locator('#pay-now').click()\n"+ repaired_code = (+ "total = int(await page.locator('#pax').input_value()) * fare\nawait page.locator('#pay-now').click()\n"+ )+ failure_reason = "CodeBlock failed with NameError at line 1: name 'passenger_count' is not defined."+ other_line_reason = "CodeBlock failed with NameError at line 2: name 'passenger_count' is not defined."++ ctx = CopilotContext(+ organization_id="org",+ workflow_id="w",+ workflow_permanent_id="wpid",+ workflow_yaml=_raising_code_workflow_yaml(raising_code),+ persisted_workflow_yaml=_raising_code_workflow_yaml(raising_code),+ browser_session_id=None,+ stream=None, # type: ignore[arg-type]+ api_key=None,+ block_authoring_policy=BlockAuthoringPolicy.CODE_ONLY_BROWSER,+ )+ outcome = recorded_outcome_from_run_blocks_result(+ _generated_code_exception_result("wr_trip", failure_reason),+ recorded_run_outcome=RecordedRunOutcome(+ verdict="not_demonstrated",+ reason_code="blocker_reported",+ display_reason=failure_reason,+ workflow_run_id="wr_trip",+ run_completed=False,+ ),+ )++ assert outcome is not None+ assert outcome.verdict == "repairable_failure"+ assert outcome.reason_code == "runtime_block_failure"+ assert outcome.attempted_block_label == "book_trip"+ assert outcome.is_authoritative is True+ assert failure_reason in outcome.observed_evidence_summary+ assert outcome.page_capture is not None and outcome.page_capture.omission == "page_capture_unavailable"++ # Two exceptions in the same block are different failures, not one repeated one.+ other_line_outcome = recorded_outcome_from_run_blocks_result(+ _generated_code_exception_result("wr_trip_again", other_line_reason)+ )+ assert other_line_outcome is not None+ assert other_line_outcome.structural_key != outcome.structural_key++ # The exception's own message is written by the failing code, so it cannot decide identity.+ # These two ran out of the same unlocatable raise; only the value the message quotes differs.+ unlocated = "CodeBlock failed with NameError: name 'passenger_count' is not defined."+ unlocated_quoting_a_line = "CodeBlock failed with NameError: name 'passenger_count' is not defined at line 9."+ assert (+ recorded_outcome_from_run_blocks_result(+ _generated_code_exception_result("wr_trip_third", unlocated_quoting_a_line)+ ).structural_key # type: ignore[union-attr]+ == recorded_outcome_from_run_blocks_result(+ _generated_code_exception_result("wr_trip_fourth", unlocated)+ ).structural_key # type: ignore[union-attr]+ )++ record_build_test_outcome(ctx, outcome)+ rendered = _recorded_build_test_outcome_prompt(ctx)+ assert failure_reason in rendered+ assert "page_capture: status=unavailable; omission=page_capture_unavailable" in rendered++ # Re-running the same code does not clear the failure; a changed submission does.+ assert unresolved_runtime_block_failure(+ ctx,+ reported_workflow_yaml=_raising_code_workflow_yaml(raising_code),+ pending_later_run_id="wr_trip_rerun",+ ) == UnresolvedRuntimeFailure(workflow_run_id="wr_trip", block_label="book_trip")+ assert (+ unresolved_runtime_block_failure(+ ctx,+ reported_workflow_yaml=_raising_code_workflow_yaml(repaired_code),+ pending_later_run_id="wr_trip_rerun",+ )+ is None+ )+++def _looped_code_workflow_yaml(code: str) -> str:+ return (+ "workflow_definition:\n"+ " parameters: []\n"+ " blocks:\n"+ " - block_type: for_loop\n"+ " label: per_passenger\n"+ " loop_over: passengers\n"+ " loop_blocks:\n"+ " - block_type: code\n"+ " label: book_trip\n"+ " code: |\n" + "".join(f" {line}\n" for line in code.splitlines())+ )+++def test_a_repaired_code_block_inside_a_loop_clears_its_failure() -> None:+ """A nested block is repaired by editing its code, so its signature has to be readable there."""+ raising_code = "total = passenger_count * fare\n"+ repaired_code = "total = int(await page.locator('#pax').input_value()) * fare\n"+ failure_reason = "CodeBlock failed with NameError at line 1: name 'passenger_count' is not defined."++ ctx = _run_history_ctx(_looped_code_workflow_yaml(raising_code))+ record_build_test_outcome(+ ctx,+ recorded_outcome_from_run_blocks_result(_generated_code_exception_result("wr_loop", failure_reason)),+ )++ assert ctx.recorded_build_test_outcome_history[-1]["attempted_block_signature"]+ assert unresolved_runtime_block_failure(+ ctx,+ reported_workflow_yaml=_looped_code_workflow_yaml(raising_code),+ pending_later_run_id="wr_loop_rerun",+ ) == UnresolvedRuntimeFailure(workflow_run_id="wr_loop", block_label="book_trip")+ assert (+ unresolved_runtime_block_failure(+ ctx,+ reported_workflow_yaml=_looped_code_workflow_yaml(repaired_code),+ pending_later_run_id="wr_loop_rerun",+ )+ is None+ )+++def test_a_code_failure_with_no_typed_identity_is_not_admitted() -> None:+ """Nothing names the failure, so no later edit could ever be shown to have addressed it."""+ assert (+ recorded_outcome_from_run_blocks_result(+ {+ "ok": False,+ "data": {+ "workflow_run_id": "wr_untyped",+ "overall_status": "failed",+ "requested_block_labels": ["book_trip"],+ "blocks": [+ {+ "label": "book_trip",+ "block_type": "CODE",+ "status": "failed",+ "failure_reason": "the block did not produce the requested output",+ }+ ],+ },+ }+ )+ is None+ )+++def test_a_recorded_code_failure_always_has_a_route_out_and_native_blocks_stay_out() -> None:+ """Both edges of admitting a bare block failure.++ A non-builtin exception inside a code block reaches persistence as the runner's generic phrase,+ naming neither the exception nor a line, and that failure still has to clear when the block is+ rewritten. A native block — which has no code signature to change — must not be admitted at+ all, or its unresolved-failure note could never be cleared by any edit.+ """+ # Byte-for-byte what the runner persists when the raised class is not a builtin, e.g. a+ # Playwright timeout: the exception's own words are stripped on the way out.+ generic_reason = "CodeBlock failed while running user code."+ timed_out = 'await page.locator("#pay-now").click()\n'+ repaired_same_selector = 'await page.locator("#pay-now").first.click(timeout=15000)\n'++ ctx = _run_history_ctx(_raising_code_workflow_yaml(timed_out))+ record_build_test_outcome(+ ctx,+ recorded_outcome_from_run_blocks_result(+ {+ "ok": False,+ "data": {+ "workflow_run_id": "wr_browser_op",+ "overall_status": "failed",+ "requested_block_labels": ["book_trip"],+ "blocks": [+ {+ "label": "book_trip",+ "block_type": "CODE",+ "status": "failed",+ "failure_reason": generic_reason,+ "error_codes": ["user_code_error"],+ }+ ],+ },+ }+ ),+ )+ assert (+ unresolved_runtime_block_failure(+ ctx,+ reported_workflow_yaml=_raising_code_workflow_yaml(repaired_same_selector),+ pending_later_run_id="wr_browser_op_rerun",+ )+ is None+ )++ # A failure no rewrite could have prevented is not recorded as an authored-code failure: the+ # same block can pass unchanged once the sandbox is back, the browser reconnects, or the run is+ # not cancelled, and recording one would hold the block open until an unrelated edit.+ for code in ("runner_unavailable", "browser_disconnected", "cancelled"):+ assert (+ recorded_outcome_from_run_blocks_result(+ {+ "ok": False,+ "data": {+ "workflow_run_id": f"wr_{code}",+ "overall_status": "failed",+ "requested_block_labels": ["book_trip"],+ "blocks": [+ {+ "label": "book_trip",+ "block_type": "CODE",+ "status": "failed",+ "failure_reason": generic_reason,+ "error_codes": [code],+ }+ ],+ },+ }+ )+ is None+ ), code++ native_outcome = recorded_outcome_from_run_blocks_result(+ {+ "ok": False,+ "data": {+ "workflow_run_id": "wr_native",+ "overall_status": "failed",+ "requested_block_labels": ["inspect_record"],+ "blocks": [+ {+ "label": "inspect_record",+ "block_type": "TASK",+ "status": "failed",+ "failure_reason": "Reached the maximum steps (30)",+ "error_codes": ["max_steps_exceeded"],+ }+ ],+ },+ }+ )+ assert native_outcome is None++def test_failure_stays_open_when_a_later_run_passes_without_taking_the_failed_branch() -> None:"""The live shape: the block runs to completion while its internal branch skips the failing call."""ctx = _run_history_ctx(two_page_login_yaml())diff --git a/tests/unit/test_copilot_run_outcome_event.py b/tests/unit/test_copilot_run_outcome_event.pyindex b91ff8972..bfce5f211 100644--- a/tests/unit/test_copilot_run_outcome_event.py+++ b/tests/unit/test_copilot_run_outcome_event.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport inspectimport reimport time+from datetime import datetime, timezonefrom types import SimpleNamespacefrom typing import Any@@ -37,6 +38,8 @@ from skyvern.forge.sdk.copilot.tools.run_execution import (_verify_and_record_run_blocks_result,)from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotRunOutcomeUpdate+from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock+from skyvern.schemas.workflows import BlockTypeclass _FakeStream:@@ -114,25 +117,48 @@ workflow_definition:assert before < ctx.executed_block_fingerprints["step"]-async def test_watchdog_receipts_preserve_terminal_block_statuses(monkeypatch: pytest.MonkeyPatch) -> None:- observer = SimpleNamespace(- get_workflow_run_blocks=lambda **_kwargs: None,+def _run_block(label: str, status: str, **fields: Any) -> WorkflowRunBlock:+ now = datetime(2026, 8, 30, tzinfo=timezone.utc)+ return WorkflowRunBlock(+ workflow_run_block_id=f"wrb_{label}",+ workflow_run_id="wr_test",+ organization_id="org",+ block_type=BlockType.CODE,+ label=label,+ status=status,+ created_at=now,+ modified_at=now,+ **fields,)- async def get_workflow_run_blocks(**_kwargs: Any) -> list[SimpleNamespace]:++async def test_watchdog_receipts_carry_why_a_block_failed(monkeypatch: pytest.MonkeyPatch) -> None:+ """A run capped by the watchdog still has to say what failed, not only that something did."""++ async def get_workflow_run_blocks(**_kwargs: Any) -> list[WorkflowRunBlock]:return [- SimpleNamespace(label="ran", status=SimpleNamespace(value="failed")),- SimpleNamespace(label="waiting", status=SimpleNamespace(value="queued")),+ _run_block(+ "ran",+ "failed",+ failure_reason="CodeBlock failed with NameError at line 2: name 'total' is not defined.",+ error_codes=["user_code_error"],+ ),+ _run_block("waiting", "queued"),]- observer.get_workflow_run_blocks = get_workflow_run_blocks- monkeypatch.setattr(run_execution.app.DATABASE, "observer", observer)+ monkeypatch.setattr(+ run_execution.app.DATABASE,+ "observer",+ SimpleNamespace(get_workflow_run_blocks=get_workflow_run_blocks),+ )- assert await _recorded_watchdog_block_receipts("wr_test", "org") == [- {"label": "ran", "status": "failed"},- {"label": "waiting", "status": "queued"},- ]+ receipts = await _recorded_watchdog_block_receipts("wr_test", "org")++ assert [receipt["status"] for receipt in receipts] == ["failed", "queued"]+ assert receipts[0]["block_type"] == "CODE"+ assert receipts[0]["error_codes"] == ["user_code_error"]+ assert "NameError" in receipts[0]["failure_reason"]def _ctx(blocks: list[dict[str, Any]] | None = None) -> CopilotContext:diff --git a/tests/unit/test_copilot_watchdog.py b/tests/unit/test_copilot_watchdog.pyindex 9a1afbfa0..a82ec4296 100644--- a/tests/unit/test_copilot_watchdog.py+++ b/tests/unit/test_copilot_watchdog.py@@ -825,7 +825,18 @@ async def test_non_success_watchdog_result_types_selected_failed_block_locators(MagicMock(return_value=True),)forge_app.DATABASE.observer.get_workflow_run_blocks = AsyncMock(- return_value=[SimpleNamespace(label="click_submit", status=SimpleNamespace(value="failed"))]+ return_value=[+ WorkflowRunBlock(+ label="click_submit",+ block_type=BlockType.CODE,+ status="failed",+ workflow_run_block_id="wrb_click_submit",+ workflow_run_id="wr_paused",+ organization_id="org-1",+ created_at=datetime(2026, 4, 21, 12, 5, tzinfo=UTC),+ modified_at=datetime(2026, 4, 21, 12, 5, tzinfo=UTC),+ )+ ])observe = AsyncMock(return_value=[{"authored_selector": "#submit", "unobserved_reason": "run_page_unavailable"}])monkeypatch.setattr(run_execution, "_observe_authored_locators", observe)