Backtestspydanticrun-20261013-104308#13908
ZoneInfo validation raises IsADirectoryError/OSError instead of ValidationError for some invalid keys
Our patch was judged better than the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Both patches make the same core fix: they add `OSError` to the exceptions caught in `validate_str_is_valid_iana_tz`. That covers `IsADirectoryError` and `ENAMETOOLONG` at the root, so correctness is equal. Patch B's added comment explains why `OSError` is needed, which is a small craft gain. The difference is in tests and scope. Patch B keeps the existing test file. It adds a parametrized real-input test (`'America'`, `'Europe'`, `'Etc'`, `'a' * 300`) through the model path. It also adds a monkeypatched test that forces `ZoneInfo` to raise `IsADirectoryError` and `OSError`. Whether these errors happen for real depends on Python version, OS and whether `tzdata` is installed. So the monkeypatched test is the one that reliably fails before the fix and passes after it in every CI environment. Patch A's only new regression test uses real inputs (`'America'`, `'a' * 300`). On Python 3.13+ or without `tzdata`, `'America'` already raises `ZoneInfoNotFoundError`, so that case would pass without the fix and gives weaker regression protection. Patch A also deletes `tests/test_types_zoneinfo.py` and recreates it as `tests/types/test_zoneinfo.py`. It rewrites every existing test from `BaseModel` to `TypeAdapter`, including the JSON-schema assertion. That 56-line move-and-rewrite is unrelated to the issue, obscures the actual fix in review, and changes what the existing tests cover. Patch B delivers the same fix with more robust tests and no churn.
The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.
Solve
3m 5s
Wall-clock time in the container
Full test suite
No new failures
392 passed · 4 skipped · 396 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
53vs 131 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial Checks
- I confirm that I'm using Pydantic V2
Description
Validating a ZoneInfo field with certain invalid strings raises a raw OSError subclass instead of a ValidationError:
- A tz database directory name such as
'America','Europe'or'Etc'raisesIsADirectoryErroron Python 3.10–3.12 when thetzdatapackage is installed (tzdatais a pydantic dependency on Windows and is also pulled in by e.g. pandas). CPython only started converting this case toZoneInfoNotFoundErrorin 3.13 (gh-85702). - An over-long key (e.g. 300 characters) raises
OSError: [Errno 63] File name too long(reproduced on Python 3.12 withtzdata, and on Python 3.13 on macOS without it).
validate_str_is_valid_iana_tz in pydantic/_internal/_validators.py only catches (ZoneInfoNotFoundError, ValueError, TypeError), so these errors propagate unchanged. Expected: a zoneinfo_str validation error, the same as for 'Not/AZone'. For example, in a web API that validates a user-supplied timezone, these inputs currently produce an unhandled exception instead of a validation error.
Suggested fix: add OSError to the caught exceptions. I have a small patch with a regression test ready if this is welcome.
Example Code
from zoneinfo import ZoneInfo
from pydantic import BaseModel
class Model(BaseModel):
tz: ZoneInfo
Model(tz='Not/AZone') # ValidationError (expected)
Model(tz='America') # IsADirectoryError: [Errno 21] Is a directory: '.../site-packages/tzdata/zoneinfo/America'
Model(tz='a' * 300) # OSError: [Errno 63] File name too long: '...'
Python, Pydantic & OS Version
pydantic version: 2.14.0b2
pydantic-core version: 2.49.0
pydantic-core build: profile=release pgo=false
python version: 3.12.13 (main, Jun 11 2026, 03:55:21) [Clang 22.1.3 ]
platform: macOS-15.3.1-arm64-arm-64bit
related packages: email-validator-2.3.0 typing_extensions-4.16.0
commit: e2ac21dcd
(tzdata is installed in this environment)
Disclosure: found, reproduced and the draft fix tested locally with the help of an AI coding agent (Claude Code); reviewed before filing.
The two patches
pydantic/_internal/_validators.pyindex aecf34e4..38aff7db 100644@@ -488,7 +488,10 @@ def validate_str_is_valid_iana_tz(value: Any, /) -> ZoneInfo: return value try: return ZoneInfo(value)- except (ZoneInfoNotFoundError, ValueError, TypeError):+ except (ZoneInfoNotFoundError, ValueError, TypeError, OSError):+ # `OSError` covers keys that resolve to a directory (e.g. `'America'`, raised as+ # `IsADirectoryError` on Python < 3.13 when `tzdata` is installed) or that are too long+ # for the filesystem (`ENAMETOOLONG`). raise PydanticCustomError('zoneinfo_str', 'invalid timezone: {value}', {'value': value}) tests/test_types_zoneinfo.pyindex 44ddf5d5..5205795d 100644@@ -4,6 +4,7 @@ from zoneinfo import ZoneInfo import pytest from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError+from pydantic._internal import _validators class ZoneInfoModel(BaseModel):@@ -42,6 +43,53 @@ def test_zoneinfo_parsing_fails_for_invalid_iana_tz_strs(): ] +@pytest.mark.parametrize('value', ['America', 'Europe', 'Etc', 'a' * 300])+def test_zoneinfo_parsing_fails_for_directory_and_overlong_keys(value):+ with pytest.raises(ValidationError) as ex_info:+ ZoneInfoModel(tz=value)++ assert ex_info.value.errors() == [+ {+ 'type': 'zoneinfo_str',+ 'loc': ('tz',),+ 'msg': f'invalid timezone: {value}',+ 'input': value,+ 'ctx': {'value': value},+ }+ ]+++@pytest.mark.parametrize(+ 'exc',+ [+ IsADirectoryError(21, 'Is a directory'),+ OSError(63, 'File name too long'),+ ],+ ids=['IsADirectoryError', 'OSError'],+)+def test_zoneinfo_os_errors_raise_validation_error(monkeypatch, exc):+ # Whether these errors occur for real depends on the Python version, OS and whether `tzdata`+ # is installed, so simulate them to make sure they are always converted to validation errors.+ class RaisingZoneInfo:+ def __new__(cls, key):+ raise exc++ monkeypatch.setattr(_validators, 'ZoneInfo', RaisingZoneInfo)++ with pytest.raises(ValidationError) as ex_info:+ TypeAdapter(ZoneInfo).validate_python('America')++ assert ex_info.value.errors() == [+ {+ 'type': 'zoneinfo_str',+ 'loc': (),+ 'msg': 'invalid timezone: America',+ 'input': 'America',+ 'ctx': {'value': 'America'},+ }+ ]++ def test_zoneinfo_json_schema(): assert ZoneInfoModel.model_json_schema() == { 'type': 'object',
pydantic/_internal/_validators.pyindex aecf34e49..a63b8db1b 100644@@ -488,7 +488,7 @@ def validate_str_is_valid_iana_tz(value: Any, /) -> ZoneInfo: return value try: return ZoneInfo(value)- except (ZoneInfoNotFoundError, ValueError, TypeError):+ except (ZoneInfoNotFoundError, ValueError, TypeError, OSError): raise PydanticCustomError('zoneinfo_str', 'invalid timezone: {value}', {'value': value}) tests/test_types_zoneinfo.pydeleted file mode 100644index 44ddf5d53..000000000@@ -1,56 +0,0 @@-from datetime import timezone-from zoneinfo import ZoneInfo--import pytest--from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError---class ZoneInfoModel(BaseModel):- tz: ZoneInfo---@pytest.mark.parametrize(- 'tz',- [- pytest.param(ZoneInfo('America/Los_Angeles'), id='ZoneInfoObject'),- pytest.param('America/Los_Angeles', id='IanaTimezoneStr'),- ],-)-def test_zoneinfo_valid_inputs(tz):- model = ZoneInfoModel(tz=tz)- assert model.tz == ZoneInfo('America/Los_Angeles')---def test_zoneinfo_serialization():- model = ZoneInfoModel(tz=ZoneInfo('America/Los_Angeles'))- assert model.model_dump_json() == '{"tz":"America/Los_Angeles"}'---def test_zoneinfo_parsing_fails_for_invalid_iana_tz_strs():- with pytest.raises(ValidationError) as ex_info:- ZoneInfoModel(tz='Zone/That_Does_Not_Exist')-- assert ex_info.value.errors() == [- {- 'type': 'zoneinfo_str',- 'loc': ('tz',),- 'msg': 'invalid timezone: Zone/That_Does_Not_Exist',- 'input': 'Zone/That_Does_Not_Exist',- 'ctx': {'value': 'Zone/That_Does_Not_Exist'},- }- ]---def test_zoneinfo_json_schema():- assert ZoneInfoModel.model_json_schema() == {- 'type': 'object',- 'title': 'ZoneInfoModel',- 'properties': {'tz': {'type': 'string', 'format': 'zoneinfo', 'title': 'Tz'}},- 'required': ['tz'],- }---def test_zoneinfo_union() -> None:- ta = TypeAdapter(ZoneInfo | timezone, config=ConfigDict(arbitrary_types_allowed=True))- assert ta.validate_python(timezone.utc) is timezone.utctests/types/test_zoneinfo.pynew file mode 100644index 000000000..665afcb9d@@ -0,0 +1,73 @@+from datetime import timezone+from zoneinfo import ZoneInfo++import pytest++from pydantic import ConfigDict, TypeAdapter, ValidationError+++@pytest.mark.parametrize(+ 'tz',+ [+ pytest.param(ZoneInfo('America/Los_Angeles'), id='ZoneInfoObject'),+ pytest.param('America/Los_Angeles', id='IanaTimezoneStr'),+ ],+)+def test_zoneinfo_valid_inputs(tz: ZoneInfo | str) -> None:+ ta = TypeAdapter(ZoneInfo)++ assert ta.validate_python(tz) == ZoneInfo('America/Los_Angeles')+++def test_zoneinfo_serialization() -> None:+ ta = TypeAdapter(ZoneInfo)++ assert ta.dump_json(ZoneInfo('America/Los_Angeles')) == b'"America/Los_Angeles"'+++def test_zoneinfo_parsing_fails_for_invalid_iana_tz_strs() -> None:+ ta = TypeAdapter(ZoneInfo)++ with pytest.raises(ValidationError) as exc_info:+ ta.validate_python('Zone/That_Does_Not_Exist')++ assert exc_info.value.errors(include_url=False) == [+ {+ 'type': 'zoneinfo_str',+ 'loc': (),+ 'msg': 'invalid timezone: Zone/That_Does_Not_Exist',+ 'input': 'Zone/That_Does_Not_Exist',+ 'ctx': {'value': 'Zone/That_Does_Not_Exist'},+ }+ ]+++@pytest.mark.parametrize('value', ['America', 'a' * 300])+def test_zoneinfo_os_error_is_validation_error(value: str) -> None:+ """https://github.com/pydantic/pydantic/issues/13908"""+ ta = TypeAdapter(ZoneInfo)++ with pytest.raises(ValidationError) as exc_info:+ ta.validate_python(value)++ assert exc_info.value.errors(include_url=False) == [+ {+ 'type': 'zoneinfo_str',+ 'loc': (),+ 'msg': f'invalid timezone: {value}',+ 'input': value,+ 'ctx': {'value': value},+ }+ ]+++def test_zoneinfo_json_schema() -> None:+ ta = TypeAdapter(ZoneInfo)++ assert ta.json_schema() == {'type': 'string', 'format': 'zoneinfo'}+++def test_zoneinfo_union() -> None:+ ta = TypeAdapter(ZoneInfo | timezone, config=ConfigDict(arbitrary_types_allowed=True))++ assert ta.validate_python(timezone.utc) is timezone.utc