Skip to content

CallbackData: an explicit None in an optional field with a default unpacks as the default #2005

Closed

Description

@art-at-ent

Checklist

  • I am sure the error is coming from aiogram code
  • I have searched in the issue tracker for similar bug reports, including closed ones

Operating system

Ubuntu 24.04

Python version

3.12.3

aiogram version

3.31.0

Expected behavior

openspec/specs/filters/spec.md says CallbackData "SHALL serialize and parse structured callback payloads with type validation". It doesn't say which types, or what an empty part means when parsing. Optional fields are supported (#1368, #1370), so I'd expect unpack(pack(x)) == x for them, including when the value is None and the field has a non-None default.

Current behavior

pack() writes None as an empty part, and unpack() turns an empty part back into the field's default. So None silently becomes the default: no error, and the .filter() handler gets the wrong value. This happens for int | None = 1, bool | None = True, Color | None = Color.RED and str | None = "experiment".

Steps to reproduce

from aiogram.filters.callback_data import CallbackData

class PageCallback(CallbackData, prefix="page"):
    page: int | None = 1

packed = PageCallback(page=None).pack()   # "page:"
PageCallback.unpack(packed)               # PageCallback(page=1), expected PageCallback(page=None)

Code example

from enum import Enum

import pytest

from aiogram.filters.callback_data import CallbackData
from aiogram.types import CallbackQuery, User


class Color(str, Enum):
    RED = "red"
    BLUE = "blue"


class PageCallback(CallbackData, prefix="page"):
    page: int | None = 1


class ToggleCallback(CallbackData, prefix="toggle"):
    enabled: bool | None = True


class ColorCallback(CallbackData, prefix="color"):
    color: Color | None = Color.RED


class TextCallback(CallbackData, prefix="text"):
    foo: str | None = "experiment"


class TestCallbackDataOptionalWithDefault:
    @pytest.mark.parametrize(
        "instance",
        [
            PageCallback(page=None),
            ToggleCallback(enabled=None),
            ColorCallback(color=None),
            TextCallback(foo=None),
        ],
    )
    def test_explicit_none_survives_round_trip(self, instance: CallbackData):
        packed = instance.pack()
        assert type(instance).unpack(packed) == instance

    async def test_filter_passes_none_to_handler(self):
        callback_query = CallbackQuery(
            id="1",
            from_user=User(id=42, is_bot=False, first_name="test"),
            data=PageCallback(page=None).pack(),
            chat_instance="test",
        )

        result = await PageCallback.filter()(callback_query)

        assert result == {"callback_data": PageCallback(page=None)}

Logs

FAILED test_explicit_none_survives_round_trip[instance0] - assert PageCallback(page=1) == PageCallback(page=None)
FAILED test_explicit_none_survives_round_trip[instance1] - assert ToggleCallback(enabled=True) == ToggleCallback(enabled=None)
FAILED test_explicit_none_survives_round_trip[instance2] - assert ColorCallback(color=<Color.RED: 'red'>) == ColorCallback(color=None)
FAILED test_explicit_none_survives_round_trip[instance3] - assert TextCallback(foo='experiment') == TextCallback(foo=None)
FAILED test_filter_passes_none_to_handler - {'callback_data': PageCallback(page=1)} != {'callback_data': PageCallback(page=None)}

Additional information

The cause is in unpack (callback_data.py#L128-L137). An empty part in a "nullable" field becomes field.default, and _check_field_is_nullable (L196-L209) treats any field that has a default as nullable. That fallback came with #1493 (v3.19.0); before it, the branch set None, and these round trips worked. For a non-str field, an empty part can only come from None, because pack() writes defaults out literally.


Disclosure: I'm building Entalpa. I found this while checking a finding from its Spec score, which flagged that the "Callback data factory" requirement says "with type validation" without saying which types or how they are validated. If you'd like to see what else it flags in aiogram's specs, you can import a public OpenSpec repo and run the assessment yourself.

Activity

  1. added
    bug
    on Nov 10, 2026
  2. added a commit that references this issue on Nov 15, 2026
    44303fc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions