[Bug] Annotated constraints and validators on workflow/activity/handler parameters are ignored by the Pydantic data converter
Los mantenedores suelen responder en 1 día
@tconley1428 ya está trabajando en esto.
Desde el 22/10/2026.
Evaluación
Este issue todavía no se ha evaluado.
Descripción
What are you really trying to do?
Validate workflow and activity arguments with Pydantic constraints without wrapping every argument in a model, for example:
@workflow.run
async def run(self, qty: PositiveInt, sku: Annotated[str, AfterValidator(strip_upper)]) -> str: ...
with pydantic_data_converter (the README says it supports "all types supported by Pydantic").
Describe the bug
Annotated[...] metadata on the parameters and return type of workflows, activities, signals, queries and updates never reaches the payload converter. temporalio.common._type_hints_from_func calls typing.get_type_hints(func) without include_extras=True, so every Annotated[T, ...] is reduced to T before it is stored as arg_types/ret_type. With the Pydantic converter this means:
qty: PositiveInt(orAnnotated[int, Field(gt=0)]) accepts-5Annotated[str, AfterValidator(...)]never runs its validator- the same applies to activity parameters, signal/query/update parameters, and to return types (decoded by the caller)
The identical annotations on a Pydantic model field are enforced, so def run(self, order: Order) rejects a bad quantity while def run(self, qty: PositiveInt) accepts it.
The Annotated-in-sandbox problem fixed in #1914 (#1897) had the same symptom (constraints silently dropped) but a different cause; this one happens outside the sandbox path too.
Minimal Reproduction
import asyncio
import uuid
from datetime import timedelta
from typing import Annotated
from pydantic import AfterValidator, BaseModel, PositiveInt
from temporalio import activity, workflow
from temporalio.client import Client, WorkflowFailureError
from temporalio.contrib.pydantic import pydantic_data_converter
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker
Sku = Annotated[str, AfterValidator(lambda s: s.strip().upper())]
class Order(BaseModel):
qty: PositiveInt
sku: Sku
@activity.defn
async def reserve(qty: PositiveInt, sku: Sku) -> str:
return f"activity got qty={qty!r} sku={sku!r}"
@workflow.defn
class ParamWorkflow:
@workflow.run
async def run(self, qty: PositiveInt, sku: Sku) -> str:
res = await workflow.execute_activity(
reserve,
args=[qty, " " + sku.lower() + " "],
start_to_close_timeout=timedelta(seconds=10),
)
return f"workflow got qty={qty!r} sku={sku!r}; {res}"
@workflow.defn
class ModelWorkflow:
@workflow.run
async def run(self, order: Order) -> str:
return f"workflow got {order!r}"
async def task_failure(handle) -> str | None:
async for ev in handle.fetch_history_events():
if ev.HasField("workflow_task_failed_event_attributes"):
return ev.workflow_task_failed_event_attributes.failure.message
return None
async def main():
async with await WorkflowEnvironment.start_local(
data_converter=pydantic_data_converter
) as env:
client: Client = env.client
async with Worker(
client,
task_queue="tq",
workflows=[ParamWorkflow, ModelWorkflow],
activities=[reserve],
):
print(
"valid args:",
await client.execute_workflow(
ParamWorkflow.run,
args=[3, " abc-1 "],
id=str(uuid.uuid4()),
task_queue="tq",
),
)
for name, run, kwargs in [
("params", ParamWorkflow.run, {"args": [-5, "abc"]}),
("model field", ModelWorkflow.run, {"arg": {"qty": -5, "sku": "abc"}}),
]:
handle = await client.start_workflow(
run,
id=str(uuid.uuid4()),
task_queue="tq",
task_timeout=timedelta(seconds=2),
execution_timeout=timedelta(seconds=5),
**kwargs,
)
try:
print(f"qty=-5 as {name}: result:", await handle.result())
except WorkflowFailureError as e:
print(
f"qty=-5 as {name}: not accepted ({type(e.cause).__name__}),",
"task failure:",
(await task_failure(handle) or "none")[:40],
)
if __name__ == "__main__":
asyncio.run(main())
Output on current main (646d70f5):
valid args: workflow got qty=3 sku=' abc-1 '; activity got qty=3 sku=' abc-1 '
qty=-5 as params: result: workflow got qty=-5 sku='abc'; activity got qty=-5 sku=' abc '
qty=-5 as model field: not accepted (TimeoutError), task failure: Failed decoding arguments
Expected: the first line shows sku='ABC-1' in both places, and the second line is rejected like the third (workflow task fails with Failed decoding arguments, caused by 1 validation error for constrained-int ... Input should be greater than 0).
The hints the converter receives, from _type_hints_from_func(reserve), are ([<class 'int'>, <class 'str'>], <class 'str'>).
Environment/Versions
- OS and processor: macOS (Darwin 25.3.0), arm64
- Temporal Version: temporalio
mainat 646d70f5 (pyproject version 1.34.0), with the 1.34.0 wheel's bridge extension; Python 3.12.14, pydantic 2.14.1 / pydantic-core 2.50.1; local dev server v1.8.3 (server 1.32.0) viaWorkflowEnvironment.start_local() - Are you using Docker or Kubernetes or building Temporal from source? No
Additional context
Cause: temporalio/common.py _type_hints_from_func (hints = get_type_hints(func)), consumed by activity.py, workflow/_definition.py and workflow/_handlers.py (run, signal, query, update, and dynamic variants).
I have a working change on a branch and would like to agree on the behaviour before opening a PR, because it is user-visible:
- Keep
Annotatedin the stored hints (get_type_hints(..., include_extras=True)), let the Pydantic converter hand the full hint to itsTypeAdapter(it already does), and make the default converter ignoreAnnotatedmetadata (unwrap to the underlying type, as it effectively does today). Only the Pydantic converter changes behaviour. This is what I have implemented. Cost: custom converters that inspecttype_hintthemselves would now seeAnnotated[...]for parameters that use it (previously they saw the stripped type), and a Pydantic user whose arguments violated anAnnotatedconstraint that was silently ignored will now get failed workflow tasks (the same as they would with the constraint on a model field). - Same as 1 but opt-in for Pydantic, e.g. a flag on
PydanticPayloadConverter/PydanticJSONPlainPayloadConverter(default off to keep today's behaviour). Avoids the behaviour change but means the documented "all types supported by Pydantic" needs an extra switch. - Keep stripping hints for everyone and document that
Annotatedmetadata on top-level parameters is not honoured (wrap values in a model). No code change.
Related: default-converter value_to_type also fails on Annotated nested inside generics today (e.g. list[Annotated[int, "x"]] raises Unserializable type); option 1 fixes that as a side effect.
Which of these would you prefer? Happy to send the PR for option 1 (or 2).
- Lenguaje dominante
- Python
- Estrellas
- 1.2k
- Forks
- 269
- Merge medio
- 1 d 11 h
- PR fusionados (30 d)
- 68
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Sin plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de temporalio/sdk-python
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
temporalio/sdk-python#496 ·
Los mantenedores suelen responder en 1 día
-
[Bug] Retried `ActivityHandle.terminate()` can fail after the activity is already terminatedPosiblemente ocupada @maciejdudko la tomó hace 1 día. Abierto
temporalio/sdk-python#2008 · 1 asignado ·
Los mantenedores suelen responder en 1 día
-
Proposal: handle SIGTERM by default to initiate graceful worker shutdownPosiblemente ocupada @eamsden la tomó hace 15 días. Abierto
temporalio/sdk-python#1948 · 1 asignado ·
Los mantenedores suelen responder en 1 día
-
Cloud CI Skips Nexus TestsQuizá libre de nuevo @tconley1428 la tomó hace 73 días y no hay ningún pull request abierto. Abierto
temporalio/sdk-python#1704 · 1 asignado ·
Los mantenedores suelen responder en 1 día
-
Windows ARM64 wheel supportAbierto
Dificultad 4/5 3-5 días Aptitud para principiantes 45/100
temporalio/sdk-python#1592 · 8 comentarios ·
Los mantenedores suelen responder en 1 día
Todos los issues de temporalio/sdk-python
Issues similares
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 77/100
AstrBotDevs/AstrBot#10720 ·
Los mantenedores suelen responder en 1 día
-
fix(xiaomi): curated picker list still offers six ids that return 400 (plan-limited vs retired)Abiertocause/upstream comp/cli P2 provider/other tool/file type/bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
NousResearch/hermes-agent#143900 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 1/5 1-3 horas Aptitud para principiantes 85/100
WLAN-Pi/wlanpi-profiler#341 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 77/100
Los mantenedores suelen responder en 1 día