Skip to content

Bug: PydanticSerializer can't replay results from models with field aliases, so idempotent retries raise ValidationError #8936

Backlog

Description

@aimanmalib

Expected Behaviour

A function decorated with @idempotent_function(..., output_serializer=PydanticSerializer) should return the saved model on a repeated call, whatever field aliases the model uses.

Current Behaviour

When the return model has a field alias (Field(alias="orderId") or alias_generator=to_camel, common for camelCase APIs) and does not set populate_by_name=True, the first call works but every repeated call with the same idempotency key raises pydantic.ValidationError. The function result was saved, yet the retry fails instead of returning it.

PydanticSerializer.to_dict() in aws_lambda_powertools/utilities/idempotency/serialization/pydantic.py stores model_dump(mode="json"), which uses field names (order_id). from_dict() calls model_validate(data), which expects the aliases (orderId) unless the model allows population by name. The saved record never matches what the model accepts.

Code snippet

import warnings

from pydantic import BaseModel, Field

from aws_lambda_powertools.utilities.idempotency import IdempotencyConfig, idempotent_function
from aws_lambda_powertools.utilities.idempotency.exceptions import (
    IdempotencyItemAlreadyExistsError,
    IdempotencyItemNotFoundError,
)
from aws_lambda_powertools.utilities.idempotency.persistence.base import BasePersistenceLayer
from aws_lambda_powertools.utilities.idempotency.serialization.pydantic import PydanticSerializer

warnings.simplefilter("ignore")


class InMemoryPersistence(BasePersistenceLayer):
    def __init__(self):
        super().__init__()
        self.items = {}

    def _get_record(self, idempotency_key):
        if idempotency_key not in self.items:
            raise IdempotencyItemNotFoundError
        return self.items[idempotency_key]

    def _put_record(self, data_record):
        if data_record.idempotency_key in self.items:
            raise IdempotencyItemAlreadyExistsError(old_data_record=self.items[data_record.idempotency_key])
        self.items[data_record.idempotency_key] = data_record

    def _update_record(self, data_record):
        self.items[data_record.idempotency_key] = data_record

    def _delete_record(self, data_record):
        self.items.pop(data_record.idempotency_key, None)


class Order(BaseModel):
    order_id: str = Field(alias="orderId")


persistence = InMemoryPersistence()


@idempotent_function(
    data_keyword_argument="order_id",
    persistence_store=persistence,
    config=IdempotencyConfig(),
    output_serializer=PydanticSerializer,
)
def create_order(order_id: str) -> Order:
    return Order(orderId=order_id)


print(create_order(order_id="abc"))  # order_id='abc'
print(next(iter(persistence.items.values())).response_data)  # {"order_id": "abc"}
print(create_order(order_id="abc"))  # pydantic ValidationError: orderId Field required

Output:

order_id='abc'
{"order_id": "abc"}
pydantic_core._pydantic_core.ValidationError: 1 validation error for Order
orderId
  Field required [type=missing, input_value={'order_id': 'abc'}, input_type=dict]

The in-memory store only stands in for DynamoDB so the snippet runs without AWS; the failure is in the serializer round trip, not in the store.

Possible Solution

Dump with aliases so the saved dict is what model_validate() accepts: data.model_dump(mode="json", by_alias=True) in PydanticSerializer.to_dict(). I checked the round trip for four models: plain fields, Field(alias=...), alias_generator=to_camel, and populate_by_name=True with an alias. With by_alias=True all four validate back; today the first two fail. Models without aliases dump the same dict as before, and records already saved for populate_by_name=True models keep validating by name, so existing records stay readable.

Happy to send a PR with a regression test if this is assigned to me.

Steps to Reproduce

  1. pip install "aws-lambda-powertools[parser]" boto3
  2. Save the snippet above as repro.py and run python repro.py.
  3. The second create_order(order_id="abc") call raises ValidationError instead of returning the saved Order.

Did you run the reproduction yourself?

Yes, I ran it and saw the failure

Powertools for AWS Lambda (Python) version

3.41.0 (PyPI), and develop at 0bbc252

AWS Lambda function runtime

3.13

Packaging format used

PyPi

Debugging logs

Reproduced locally with Python 3.13 (PyPI 3.41.0) and Python 3.12 (develop 0bbc252e), pydantic 2.14.4.
Written with help from Claude Code; I ran the snippet and the alias round-trip check myself.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions