diff --git a/changelog/added/typecast-tortoise.md b/changelog/added/typecast-tortoise.md new file mode 100644 index 0000000000..8df9d5a440 --- /dev/null +++ b/changelog/added/typecast-tortoise.md @@ -0,0 +1 @@ +`ApplicationError` and `CancelledError` now have `detail(index, type_hint)`, which returns one detail as the given type, for example `err.detail(0, MyDataclass)`, and `raw_details`, which returns the detail payloads. diff --git a/changelog/changed/procrastinating-parcel.md b/changelog/changed/procrastinating-parcel.md new file mode 100644 index 0000000000..45a4b11de5 --- /dev/null +++ b/changelog/changed/procrastinating-parcel.md @@ -0,0 +1 @@ +A detail of `ApplicationError` or `CancelledError` that cannot be decoded now raises when it is read, instead of when the error is received. diff --git a/temporalio/converter/_failure_converter.py b/temporalio/converter/_failure_converter.py index f73aa5b7e4..250207b4b3 100644 --- a/temporalio/converter/_failure_converter.py +++ b/temporalio/converter/_failure_converter.py @@ -333,7 +333,6 @@ def from_failure( app_info = failure.application_failure_info err = temporalio.exceptions.ApplicationError( failure.message or "Application error", - *payload_converter.from_payloads_wrapper(app_info.details), type=app_info.type or None, non_retryable=app_info.non_retryable, next_retry_delay=app_info.next_retry_delay.ToTimedelta() @@ -343,6 +342,7 @@ def from_failure( int(app_info.category) ), ) + err._set_raw_details(app_info.details.payloads, payload_converter) case "timeout_failure_info": timeout_info = failure.timeout_failure_info @@ -361,9 +361,9 @@ def from_failure( case "canceled_failure_info": cancel_info = failure.canceled_failure_info err = temporalio.exceptions.CancelledError( - failure.message or "Cancelled", - *payload_converter.from_payloads_wrapper(cancel_info.details), + failure.message or "Cancelled" ) + err._set_raw_details(cancel_info.details.payloads, payload_converter) case "terminated_failure_info": err = temporalio.exceptions.TerminatedError( failure.message or "Terminated" diff --git a/temporalio/exceptions.py b/temporalio/exceptions.py index 03a623c21e..99f9c4674d 100644 --- a/temporalio/exceptions.py +++ b/temporalio/exceptions.py @@ -1,13 +1,20 @@ """Common Temporal exceptions.""" +from __future__ import annotations + import asyncio from collections.abc import Sequence from datetime import timedelta from enum import IntEnum -from typing import Any +from typing import TYPE_CHECKING, Any +import temporalio.api.common.v1 import temporalio.api.enums.v1 import temporalio.api.failure.v1 +import temporalio.types + +if TYPE_CHECKING: + from temporalio.converter import PayloadConverter class TemporalError(Exception): @@ -126,6 +133,60 @@ def __init__(self, operation_id: str, *, run_id: str | None = None) -> None: self.run_id = run_id +class _FailureDetails: + """Error details kept as payloads and decoded when first read.""" + + _details: Sequence[Any] | None = None + _raw_details: Sequence[temporalio.api.common.v1.Payload] | None = None + _payload_converter: PayloadConverter | None = None + + def _set_raw_details( + self, + payloads: Sequence[temporalio.api.common.v1.Payload], + payload_converter: PayloadConverter, + ) -> None: + # Decode when read, so a detail that cannot be decoded does not lose the whole error + self._details = None + self._raw_details = list(payloads) + self._payload_converter = payload_converter + + @property + def details(self) -> Sequence[Any]: + """User-defined details on the error. + + For an error received from Temporal, these are decoded the first time + they are read, without type hints, so a dataclass detail comes back as + a dict. Use :py:meth:`detail` to decode one with a type hint. + """ + if self._details is None: + assert self._raw_details is not None and self._payload_converter + self._details = tuple( + self._payload_converter.from_payloads(self._raw_details) + ) + return self._details + + @property + def raw_details(self) -> Sequence[temporalio.api.common.v1.Payload] | None: + """Payloads of the details for an error received from Temporal, or + ``None`` for an error created locally. + """ + return self._raw_details + + def detail( + self, index: int, type_hint: type[temporalio.types.AnyType] + ) -> temporalio.types.AnyType: + """Detail at the given index, decoded with the given type hint. + + For an error created locally, ``details[index]`` is returned as is. + + Raises: + IndexError: No detail at the given index. + """ + if self._raw_details is None or self._payload_converter is None: + return self.details[index] + return self._payload_converter.from_payload(self._raw_details[index], type_hint) + + class ApplicationErrorCategory(IntEnum): """Severity category for your application error. Maps to corresponding client-side logging/metrics behaviors""" @@ -139,7 +200,7 @@ class ApplicationErrorCategory(IntEnum): """BENIGN category errors emit DEBUG level logs and do not record metrics""" -class ApplicationError(FailureError): +class ApplicationError(_FailureDetails, FailureError): """Error raised during workflow/activity execution.""" def __init__( @@ -163,11 +224,6 @@ def __init__( self._next_retry_delay = next_retry_delay self._category = category - @property - def details(self) -> Sequence[Any]: - """User-defined details on the error.""" - return self._details - @property def type(self) -> str | None: """General error type.""" @@ -198,7 +254,7 @@ def category(self) -> ApplicationErrorCategory: return self._category -class CancelledError(FailureError): +class CancelledError(_FailureDetails, FailureError): """Error raised on workflow/activity cancellation.""" def __init__(self, message: str = "Cancelled", *details: Any) -> None: @@ -206,11 +262,6 @@ def __init__(self, message: str = "Cancelled", *details: Any) -> None: super().__init__(message) self._details = details - @property - def details(self) -> Sequence[Any]: - """User-defined details on the error.""" - return self._details - class TerminatedError(FailureError): """Error raised on workflow cancellation.""" diff --git a/tests/contrib/pydantic/test_pydantic.py b/tests/contrib/pydantic/test_pydantic.py index c3ab95f181..8d9239fbec 100644 --- a/tests/contrib/pydantic/test_pydantic.py +++ b/tests/contrib/pydantic/test_pydantic.py @@ -11,12 +11,14 @@ from pydantic import BaseModel import temporalio.contrib.pydantic +from temporalio.api.failure.v1 import Failure from temporalio.client import Client from temporalio.contrib.pydantic import ( PydanticJSONPlainPayloadConverter, PydanticPayloadConverter, pydantic_data_converter, ) +from temporalio.exceptions import ApplicationError from temporalio.worker import Worker from temporalio.worker.workflow_sandbox._restrictions import ( RestrictionContext, @@ -128,6 +130,22 @@ def test_to_json_options_exclude_unset_keeps_aliases(): assert converter.from_payload(payload, AliasModel) == AliasModel(orderId=7) +def test_application_error_detail_with_pydantic_type_hint(): + converter = pydantic_data_converter + failure = Failure() + converter.failure_converter.to_failure( + ApplicationError("boom", AliasModel(orderId=7)), + converter.payload_converter, + failure, + ) + err = converter.failure_converter.from_failure(failure, converter.payload_converter) + assert isinstance(err, ApplicationError) + assert err.details == ( + {"orderId": 7, "note": "", "ratio": 1.0, "wait": "PT1S", "data": "data"}, + ) + assert err.detail(0, AliasModel) == AliasModel(orderId=7) + + async def test_pydantic_data_converter_pickle(): restored = pickle.loads(pickle.dumps(pydantic_data_converter)) value = {"a": 1} diff --git a/tests/test_converter.py b/tests/test_converter.py index b47cadbdd0..872462c6f5 100644 --- a/tests/test_converter.py +++ b/tests/test_converter.py @@ -62,6 +62,7 @@ ) from temporalio.exceptions import ( ApplicationError, + CancelledError, FailureError, NexusOperationError, ) @@ -917,6 +918,70 @@ def test_application_error_next_retry_delay_round_trip(): assert err.next_retry_delay == next_retry_delay +def test_failure_details_with_type_hint(): + converter = DataConverter.default + detail = MyDataClass(foo="val1", bar=2, baz=SerializableEnum.FOO) + for error in [ + ApplicationError("boom", detail, "detail2"), + CancelledError("cancelled", detail, "detail2"), + ]: + failure = Failure() + converter.failure_converter.to_failure( + error, converter.payload_converter, failure + ) + err = converter.failure_converter.from_failure( + failure, converter.payload_converter + ) + assert isinstance(err, (ApplicationError, CancelledError)) + assert err.details == ( + {"foo": "val1", "bar": 2, "baz": 1}, + "detail2", + ) + # Decoded once, then reused + assert err.details is err.details + assert err.detail(0, MyDataClass) == detail + assert err.detail(1, str) == "detail2" + failure_details = ( + failure.application_failure_info.details + if isinstance(err, ApplicationError) + else failure.canceled_failure_info.details + ) + assert err.raw_details == list(failure_details.payloads) + with pytest.raises(IndexError): + err.detail(2, str) + + +def test_failure_details_with_type_hint_on_local_error(): + detail = MyDataClass(foo="val1", bar=2, baz=SerializableEnum.FOO) + err = ApplicationError("boom", detail) + assert err.raw_details is None + assert err.detail(0, MyDataClass) is detail + with pytest.raises(IndexError): + err.detail(1, MyDataClass) + + +def test_failure_details_decode_error_keeps_error(): + converter = DataConverter.default + failure = Failure() + converter.failure_converter.to_failure( + ApplicationError("boom", "detail1", "detail2", type="MyError"), + converter.payload_converter, + failure, + ) + failure.application_failure_info.details.payloads[0].metadata["encoding"] = ( + b"bad-encoding" + ) + err = converter.failure_converter.from_failure(failure, converter.payload_converter) + assert isinstance(err, ApplicationError) + assert err.message == "boom" + assert err.type == "MyError" + assert err.detail(1, str) == "detail2" + with pytest.raises(KeyError, match="Unknown payload encoding bad-encoding"): + err.detail(0, str) + with pytest.raises(KeyError, match="Unknown payload encoding bad-encoding"): + err.details + + @pytest.mark.parametrize( "handler_type,retryable_override,expected_retryable", [ diff --git a/tests/test_serialization_context.py b/tests/test_serialization_context.py index fb7db6e6e7..97bf3a9e3c 100644 --- a/tests/test_serialization_context.py +++ b/tests/test_serialization_context.py @@ -3050,7 +3050,10 @@ class PreviousRunOutcomeWorkflow: @workflow.run async def run(self, _input: str) -> None: workflow.get_last_completion_result() - workflow.get_last_failure() + last_failure = workflow.get_last_failure() + # Reading details decodes them + assert isinstance(last_failure, ApplicationError) + assert last_failure.details == ("previous-failure-detail",) def _json_payload(value: str) -> temporalio.api.common.v1.Payload: diff --git a/tests/worker/test_activity.py b/tests/worker/test_activity.py index 5b21c3d0ad..4b16f39bd4 100644 --- a/tests/worker/test_activity.py +++ b/tests/worker/test_activity.py @@ -1572,6 +1572,46 @@ async def test_activity_async_cancel( assert list(err.value.cause.cause.details) == ["cancel details"] +@dataclass +class CancellationReason: + reason: str + retry: bool + + +async def test_activity_async_cancel_detail_with_type_hint( + client: Client, + worker: ExternalWorker, + shared_state_manager: SharedStateManager, +): + wrapper = AsyncActivityWrapper() + task = asyncio.create_task( + _execute_workflow_with_activity( + client, + worker, + wrapper.run, + cancel_after_ms=50, + wait_for_cancellation=True, + shared_state_manager=shared_state_manager, + ) + ) + await wrapper.wait_info() + # Sleep 2s before trying to cancel + await asyncio.sleep(2) + await wrapper.async_handle(client, False).report_cancellation( + CancellationReason(reason="shutting down", retry=True) + ) + with pytest.raises(WorkflowFailureError) as err: + await task + assert isinstance(err.value.cause, ActivityError) + assert isinstance(err.value.cause.cause, CancelledError) + assert err.value.cause.cause.details == ( + {"reason": "shutting down", "retry": True}, + ) + assert err.value.cause.cause.detail(0, CancellationReason) == CancellationReason( + reason="shutting down", retry=True + ) + + some_context_var: ContextVar[str] = ContextVar("some_context_var", default="unset") diff --git a/tests/worker/test_workflow.py b/tests/worker/test_workflow.py index 54f64c8552..822c9cb695 100644 --- a/tests/worker/test_workflow.py +++ b/tests/worker/test_workflow.py @@ -10487,6 +10487,100 @@ async def test_activity_failure_with_encoded_payload_is_decoded_in_workflow( assert result == "Handled encrypted failure successfully" +@dataclass +class ActivityFailureDetails: + error_code: str + id: str + + +@activity.defn +async def activity_that_fails_with_dataclass_details() -> str: + raise ApplicationError( + "Activity failed intentionally", + ActivityFailureDetails(error_code="NOT_FOUND", id="test-123"), + non_retryable=True, + ) + + +@workflow.defn +class WorkflowWithFailingActivityDetailTypeHint: + @workflow.run + async def run(self) -> str: + try: + return await workflow.execute_activity( + activity_that_fails_with_dataclass_details, + schedule_to_close_timeout=timedelta(seconds=3), + retry_policy=RetryPolicy(maximum_attempts=1), + ) + except ActivityError as err: + assert isinstance(err.cause, ApplicationError) + assert err.cause.details[0] == {"error_code": "NOT_FOUND", "id": "test-123"} + assert err.cause.detail( + 0, ActivityFailureDetails + ) == ActivityFailureDetails(error_code="NOT_FOUND", id="test-123") + return "Handled typed failure details successfully" + + +async def test_activity_failure_detail_with_type_hint_in_workflow(client: Client): + config = client.config() + config["data_converter"] = dataclasses.replace( + temporalio.converter.default(), payload_codec=FakeEncryptionCodec() + ) + client = Client(**config) + + async with new_worker( + client, + WorkflowWithFailingActivityDetailTypeHint, + activities=[activity_that_fails_with_dataclass_details], + ) as worker: + result = await client.execute_workflow( + WorkflowWithFailingActivityDetailTypeHint.run, + id=f"workflow-{uuid.uuid4()}", + task_queue=worker.task_queue, + ) + assert result == "Handled typed failure details successfully" + + +@workflow.defn +class WorkflowWithUncaughtFailingActivity: + @workflow.run + async def run(self) -> str: + return await workflow.execute_activity( + activity_that_fails_with_dataclass_details, + schedule_to_close_timeout=timedelta(seconds=3), + retry_policy=RetryPolicy(maximum_attempts=1), + ) + + +async def test_activity_failure_detail_with_type_hint_in_client(client: Client): + config = client.config() + config["data_converter"] = dataclasses.replace( + temporalio.converter.default(), payload_codec=FakeEncryptionCodec() + ) + client = Client(**config) + + async with new_worker( + client, + WorkflowWithUncaughtFailingActivity, + activities=[activity_that_fails_with_dataclass_details], + ) as worker: + with pytest.raises(WorkflowFailureError) as err: + await client.execute_workflow( + WorkflowWithUncaughtFailingActivity.run, + id=f"workflow-{uuid.uuid4()}", + task_queue=worker.task_queue, + ) + assert isinstance(err.value.cause, ActivityError) + assert isinstance(err.value.cause.cause, ApplicationError) + assert err.value.cause.cause.details[0] == { + "error_code": "NOT_FOUND", + "id": "test-123", + } + assert err.value.cause.cause.detail( + 0, ActivityFailureDetails + ) == ActivityFailureDetails(error_code="NOT_FOUND", id="test-123") + + @workflow.defn class DisableLoggerSandbox: @workflow.run