Backtestspydanticrun-20261022-024030#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.
The production change is byte-for-byte identical in both patches: adding `OSError` to the caught exceptions in `validate_str_is_valid_iana_tz`, which is the root-cause fix the issue asks for. Both pass all independent tests. The difference is in tests and scope. Patch A deletes `tests/test_types_zoneinfo.py` and recreates it as `tests/types/test_zoneinfo.py`, rewriting every existing test from `BaseModel` to `TypeAdapter` form. That file move and rewrite is unrelated churn that obscures the actual fix in the diff and changes the `loc` and assertions of pre-existing tests for no reason tied to the issue. Its only regression test is environment-dependent: on Python 3.13 `'America'` raises `ZoneInfoNotFoundError` and would pass even without the fix, and whether `'a'*300` hits `ENAMETOOLONG` depends on platform and tzdata presence. Patch B appends to the existing test file, adds the same environment-dependent cases (plus `Etc`), and crucially adds a monkeypatched test that forces `IsADirectoryError` and a plain `OSError` out of `ZoneInfo`, guaranteeing the new except branch is exercised on every CI configuration. The monkeypatch targets the module-global `ZoneInfo` name that the validator looks up at call time, so it works. B also adds a short comment explaining why `OSError` is caught, which helps future readers. B is better on tests, scope, and craft.
Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.
Solve
3m 17s
Wall-clock time in the container
Full test suite
No new failures
391 passed · 4 skipped · 395 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
60vs 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..4e6b98b5 100644@@ -488,7 +488,9 @@ 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 e.g. `IsADirectoryError` for tz database directory names such as `America`+ # (Python < 3.13 with `tzdata` installed) and "File name too long" for over-long keys. raise PydanticCustomError('zoneinfo_str', 'invalid timezone: {value}', {'value': value}) tests/test_types_zoneinfo.pyindex 44ddf5d5..76532678 100644@@ -54,3 +54,59 @@ def test_zoneinfo_json_schema(): def test_zoneinfo_union() -> None: ta = TypeAdapter(ZoneInfo | timezone, config=ConfigDict(arbitrary_types_allowed=True)) assert ta.validate_python(timezone.utc) is timezone.utc+++@pytest.mark.parametrize(+ 'value',+ [+ pytest.param('America', id='tz-database-directory'),+ pytest.param('Etc', id='tz-database-directory-etc'),+ pytest.param('a' * 300, id='over-long-key'),+ ],+)+def test_zoneinfo_parsing_fails_for_os_error_keys(value: str) -> None:+ 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',+ [+ pytest.param(IsADirectoryError(21, 'Is a directory'), id='IsADirectoryError'),+ pytest.param(OSError(63, 'File name too long'), id='OSError'),+ ],+)+def test_zoneinfo_os_error_raises_validation_error(monkeypatch: pytest.MonkeyPatch, exc: OSError) -> None:+ """`ZoneInfo` can raise `OSError` subclasses depending on the Python version, platform and+ whether `tzdata` is installed; these must be reported as validation errors.+ """+ from pydantic._internal import _validators++ class RaisingZoneInfo(ZoneInfo):+ def __new__(cls, key: str) -> ZoneInfo:+ raise exc++ monkeypatch.setattr(_validators, 'ZoneInfo', RaisingZoneInfo)++ with pytest.raises(ValidationError) as ex_info:+ ZoneInfoModel(tz='America')++ assert ex_info.value.errors() == [+ {+ 'type': 'zoneinfo_str',+ 'loc': ('tz',),+ 'msg': 'invalid timezone: America',+ 'input': 'America',+ 'ctx': {'value': 'America'},+ }+ ]
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