Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-7939): surface FileParserBlock failures in workflow run outputs (#5964)
Shuchang Zhengab3faf076a44
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.pyindex 98d06f3aa..f62a36db1 100644--- a/skyvern/forge/sdk/workflow/models/block.py+++ b/skyvern/forge/sdk/workflow/models/block.py@@ -5005,6 +5005,35 @@ class FileParserBlock(Block):)return llm_response+ async def _record_failure(+ self,+ workflow_run_context: WorkflowRunContext,+ workflow_run_id: str,+ workflow_run_block_id: str,+ organization_id: str | None,+ failure_reason: str,+ ) -> BlockResult:+ # SKY-7939: also surface the failure in `outputs.<block_label>` so callers+ # can tell which block failed without cross-referencing the timeline.+ error_codes = self.get_failure_error_codes()+ failure_output: dict[str, Any] = {+ "status": BlockStatus.failed.value,+ "failure_reason": failure_reason,+ "errors": [+ {"error_code": code, "reasoning": failure_reason, "confidence_float": 1.0} for code in error_codes+ ],+ }+ await self.record_output_parameter_value(workflow_run_context, workflow_run_id, failure_output)+ return await self.build_block_result(+ success=False,+ failure_reason=failure_reason,+ output_parameter_value=failure_output,+ status=BlockStatus.failed,+ workflow_run_block_id=workflow_run_block_id,+ organization_id=organization_id,+ error_codes=error_codes or None,+ )+async def execute(self,workflow_run_id: str,@@ -5032,14 +5061,12 @@ class FileParserBlock(Block):try:self.format_potential_template_parameters(workflow_run_context)except Exception as e:- return await self.build_block_result(- success=False,- failure_reason=f"Failed to format jinja template: {str(e)}",- output_parameter_value=None,- status=BlockStatus.failed,- workflow_run_block_id=workflow_run_block_id,- organization_id=organization_id,- error_codes=self.get_failure_error_codes() or None,+ return await self._record_failure(+ workflow_run_context,+ workflow_run_id,+ workflow_run_block_id,+ organization_id,+ f"Failed to format jinja template: {str(e)}",)try:@@ -5054,14 +5081,12 @@ class FileParserBlock(Block):# Validate the file typeself.validate_file_type(self.file_url, file_path)except Exception as e:- return await self.build_block_result(- success=False,- failure_reason=f"Failed to download or validate file: {str(e)}",- output_parameter_value=None,- status=BlockStatus.failed,- workflow_run_block_id=workflow_run_block_id,- organization_id=organization_id,- error_codes=self.get_failure_error_codes() or None,+ return await self._record_failure(+ workflow_run_context,+ workflow_run_id,+ workflow_run_block_id,+ organization_id,+ f"Failed to download or validate file: {str(e)}",)LOG.debug(@@ -5092,14 +5117,12 @@ class FileParserBlock(Block):elif self.file_type == FileType.DOCX:parsed_data = await self._parse_docx_file(file_path)else:- return await self.build_block_result(- success=False,- failure_reason=f"Unsupported file type: {self.file_type}",- output_parameter_value=None,- status=BlockStatus.failed,- workflow_run_block_id=workflow_run_block_id,- organization_id=organization_id,- error_codes=self.get_failure_error_codes() or None,+ return await self._record_failure(+ workflow_run_context,+ workflow_run_id,+ workflow_run_block_id,+ organization_id,+ f"Unsupported file type: {self.file_type}",)# If json_schema is provided, use AI to extract structured data@@ -5121,14 +5144,12 @@ class FileParserBlock(Block):)final_data = ai_extracted_dataexcept Exception as e:- return await self.build_block_result(- success=False,- failure_reason=f"Failed to extract data with AI: {str(e)}",- output_parameter_value=None,- status=BlockStatus.failed,- workflow_run_block_id=workflow_run_block_id,- organization_id=organization_id,- error_codes=self.get_failure_error_codes() or None,+ return await self._record_failure(+ workflow_run_context,+ workflow_run_id,+ workflow_run_block_id,+ organization_id,+ f"Failed to extract data with AI: {str(e)}",)else:# Return raw parsed datadiff --git a/tests/unit/workflow/test_file_parser_error_code.py b/tests/unit/workflow/test_file_parser_error_code.pyindex 7a3c40dc1..0640c807f 100644--- a/tests/unit/workflow/test_file_parser_error_code.py+++ b/tests/unit/workflow/test_file_parser_error_code.py@@ -49,6 +49,8 @@ def _mock_workflow_run_context() -> MagicMock:ctx = MagicMock()ctx.has_parameter.return_value = Falsectx.has_value.return_value = False+ # Failure paths now call record_output_parameter_value, which awaits this method.+ ctx.register_output_parameter_value_post_execution = AsyncMock()return ctx@@ -282,3 +284,144 @@ class TestBuildBlockResultPassesErrorCodes:call_kwargs = app.DATABASE.observer.update_workflow_run_block.call_args[1]assert call_kwargs["error_codes"] is Noneassert result.error_codes == []+++class TestFileParserBlockRecordsOutputOnFailure:+ """+ SKY-7939: even when the block fails, an output should be recorded so it+ appears as `outputs.<block_label>` in the workflow run response, with a+ failed status and the error info. Without this, downstream consumers+ can't tell *which* block failed from `outputs` alone.+ """++ @staticmethod+ def _recorded_value(mock_record: AsyncMock) -> dict | None:+ """Return the `value` argument from the (single) record call, or None."""+ if not mock_record.await_count:+ return None+ call = mock_record.await_args+ if call is None:+ return None+ if "value" in call.kwargs:+ return call.kwargs["value"]+ # positional: (workflow_run_context, workflow_run_id, value)+ if len(call.args) >= 3:+ return call.args[2]+ return None++ def _assert_failure_output_shape(self, value: dict | None, failure_substring: str) -> None:+ assert value is not None, "record_output_parameter_value was not called on failure"+ assert value["status"] == BlockStatus.failed.value+ assert failure_substring.lower() in value["failure_reason"].lower()+ assert value["errors"], "errors list should be non-empty"+ assert value["errors"][0]["error_code"] == "FILE_PARSER_ERROR"+ assert value["errors"][0]["reasoning"] == value["failure_reason"]++ @pytest.mark.asyncio+ async def test_jinja_failure_records_failed_output(self) -> None:+ block = _make_file_parser_block(file_url="{{ invalid }}")+ mock_ctx = _mock_workflow_run_context()++ with patch.object(FileParserBlock, "get_workflow_run_context", return_value=mock_ctx):+ with patch.object(+ FileParserBlock, "format_potential_template_parameters", side_effect=Exception("Jinja error")+ ):+ with patch.object(+ FileParserBlock, "record_output_parameter_value", new_callable=AsyncMock+ ) as mock_record:+ result = await block.execute(+ workflow_run_id="wr_test",+ workflow_run_block_id="wrb_test",+ organization_id="org_test",+ )++ assert result.success is False+ recorded = self._recorded_value(mock_record)+ self._assert_failure_output_shape(recorded, "jinja")+ # build_block_result must also receive the same payload so it ends up on the WorkflowRunBlock row.+ assert result.output_parameter_value == recorded++ @pytest.mark.asyncio+ async def test_download_failure_records_failed_output(self) -> None:+ block = _make_file_parser_block(file_url="https://example.com/missing.csv")+ mock_ctx = _mock_workflow_run_context()++ with patch.object(FileParserBlock, "get_workflow_run_context", return_value=mock_ctx):+ with patch.object(FileParserBlock, "format_potential_template_parameters"):+ with patch(+ "skyvern.forge.sdk.workflow.models.block.download_file",+ side_effect=Exception("Download failed"),+ ):+ with patch.object(+ FileParserBlock, "record_output_parameter_value", new_callable=AsyncMock+ ) as mock_record:+ result = await block.execute(+ workflow_run_id="wr_test",+ workflow_run_block_id="wrb_test",+ organization_id="org_test",+ )++ assert result.success is False+ recorded = self._recorded_value(mock_record)+ self._assert_failure_output_shape(recorded, "download or validate")+ assert result.output_parameter_value == recorded++ @pytest.mark.asyncio+ async def test_unsupported_file_type_records_failed_output(self) -> None:+ block = _make_file_parser_block(file_url="https://example.com/file.csv")+ mock_ctx = _mock_workflow_run_context()++ with patch.object(FileParserBlock, "get_workflow_run_context", return_value=mock_ctx):+ with patch.object(FileParserBlock, "format_potential_template_parameters"):+ with patch(+ "skyvern.forge.sdk.workflow.models.block.download_file",+ return_value="/tmp/test_file",+ ):+ with patch.object(FileParserBlock, "_detect_file_type_from_url", return_value="unsupported_type"):+ with patch.object(FileParserBlock, "validate_file_type"):+ with patch.object(+ FileParserBlock, "record_output_parameter_value", new_callable=AsyncMock+ ) as mock_record:+ result = await block.execute(+ workflow_run_id="wr_test",+ workflow_run_block_id="wrb_test",+ organization_id="org_test",+ )++ assert result.success is False+ recorded = self._recorded_value(mock_record)+ self._assert_failure_output_shape(recorded, "unsupported")+ assert result.output_parameter_value == recorded++ @pytest.mark.asyncio+ async def test_ai_extraction_failure_records_failed_output(self) -> None:+ block = _make_file_parser_block(file_url="https://example.com/file.csv")+ block.json_schema = {"type": "object", "properties": {"name": {"type": "string"}}}+ mock_ctx = _mock_workflow_run_context()++ with patch.object(FileParserBlock, "get_workflow_run_context", return_value=mock_ctx):+ with patch.object(FileParserBlock, "format_potential_template_parameters"):+ with patch(+ "skyvern.forge.sdk.workflow.models.block.download_file",+ return_value="/tmp/test.csv",+ ):+ with patch.object(FileParserBlock, "validate_file_type"):+ with patch.object(FileParserBlock, "_parse_csv_file", return_value=[{"name": "Alice"}]):+ with patch.object(FileParserBlock, "_extract_with_ai", side_effect=Exception("LLM error")):+ with patch.object(+ FileParserBlock, "record_output_parameter_value", new_callable=AsyncMock+ ) as mock_record:+ result = await block.execute(+ workflow_run_id="wr_test",+ workflow_run_block_id="wrb_test",+ organization_id="org_test",+ )++ assert result.success is False+ # AI extraction path is special: parsed CSV success may have called record once;+ # we only require that the *last* record call carries the failure output.+ assert mock_record.await_count >= 1+ last_call = mock_record.await_args_list[-1]+ recorded = last_call.kwargs.get("value") if "value" in last_call.kwargs else last_call.args[2]+ self._assert_failure_output_shape(recorded, "extract data with ai")+ assert result.output_parameter_value == recorded