Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/added/typecast-tortoise.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions changelog/changed/procrastinating-parcel.md
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 3 additions & 3 deletions temporalio/converter/_failure_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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
Expand All @@ -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"
Expand Down
77 changes: 64 additions & 13 deletions temporalio/exceptions.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down Expand Up @@ -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"""

Expand All @@ -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__(
Expand All @@ -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."""
Expand Down Expand Up @@ -198,19 +254,14 @@ 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:
"""Initialize a cancelled error."""
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."""
Expand Down
18 changes: 18 additions & 0 deletions tests/contrib/pydantic/test_pydantic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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}
Expand Down
65 changes: 65 additions & 0 deletions tests/test_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
)
from temporalio.exceptions import (
ApplicationError,
CancelledError,
FailureError,
NexusOperationError,
)
Expand Down Expand Up @@ -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",
[
Expand Down
5 changes: 4 additions & 1 deletion tests/test_serialization_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
40 changes: 40 additions & 0 deletions tests/worker/test_activity.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")


Expand Down
Loading