Skip to content

fix(python): enforce inherited-generic field types in TypeChatValidator - #553

Closed
0xARX (0xArx) wants to merge 1 commit into
microsoft:mainfrom
0xArx:fix/validator-inherited-generic-dataclass
Closed

0xARX (0xArx) wants to merge 1 commit into
microsoft:mainfrom
0xArx:fix/validator-inherited-generic-dataclass

Conversation

@0xArx

Copy link
Copy Markdown

Fixes #550.

Problem

TypeChatValidator silently accepted values whose types were wrong for fields that come from a specialised generic base class. For example:

from dataclasses import dataclass
from typing import Generic, TypeVar

T = TypeVar("T")

@dataclass
class Box(Generic[T]):
    item: T

@dataclass
class IntBox(Box[int]):
    pass

v = TypeChatValidator(IntBox)
result = v.validate_object({"item": "bad"})
# Before this fix: Success(value=IntBox(item='bad'))  ← wrong

The root cause is that Pydantic's TypeAdapter(IntBox) builds its JSON schema from the generic base (Box) and therefore does not constrain the item field to int.

Fix

On construction, TypeChatValidator now detects when the target type is a dataclass whose annotations still contain TypeVars after a get_type_hints() call. It walks __orig_bases__ to build a TypeVar → concrete-type mapping, then uses dataclasses.make_dataclass to create a structurally identical class with every TypeVar replaced by its concrete type. A second pydantic.TypeAdapter is built for this resolved copy.

At validation time the resolved adapter runs first; because it carries the concrete-type schema, it raises a proper pydantic.ValidationError with the correct path and message when a value is wrong. The original adapter then runs to produce a Success value typed as the original class.

The resolution is skipped when the class is still generic itself (i.e. some TypeVars survive substitution), leaving those cases unchanged.

Tests

Eleven new tests are added to tests/test_validator.py covering:

  • IntBox(Box[int]) — valid int, invalid string, invalid float, missing field
  • StrListBox(ListBox[str]) — valid list, list with wrong element types
  • IntBoxChild(IntBox) — transitive TypeVar inheritance (two hops)
  • Return type is the original class (IntBox), not the resolved copy

Pydantic's TypeAdapter uses the generic base class's JSON schema when
validating a specialised subclass such as IntBox(Box[int]), so it does
not constrain fields whose types come from TypeVar substitution.
TypeChatValidator therefore accepted values like {"item": "bad"} for
IntBox even though item must be an int (issue microsoft#550).

Fix: on construction, detect dataclasses whose annotations still contain
TypeVars after a type_hints() call, build a TypeVar→concrete-type mapping
by walking __orig_bases__, and create a structurally equivalent dataclass
via dataclasses.make_dataclass with every TypeVar replaced.  A second
Pydantic TypeAdapter is built for this resolved copy.  At validation time
the resolved adapter is run first (raising a proper ValidationError with
correct path/message information when types do not match) and then the
original adapter produces a Success value typed as the original class.

The resolution is skipped when the class is itself still generic (i.e.
some TypeVars survive substitution), leaving those cases unchanged.
Copilot AI balanced review requested due to automatic review settings December 1, 2026 10:20

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The validator loses dataclass field options, overwrites TypeVar bindings, and discards resolved values, causing construction failures, rejection of valid inputs, and incorrectly typed results.

3 open issues
What changed in this PR

This PR addresses #550 by adding runtime checks for inherited generic dataclass fields in Python’s TypeChatValidator, following the earlier prompt-schema fix.

Changes:

  • Resolves inherited type variables into concrete annotations on a temporary dataclass.
  • Adds a preliminary validation pass while retaining the original class for returned values.
  • Adds eleven regression tests covering scalar and list fields, transitive inheritance, missing fields, and return-class identity.
File Description
python/​tests/​test_validator.py Adds inherited-generic fixtures and validation regression tests.
python/​src/​typechat/​_internal/​validator.py Adds type-variable resolution and a second validation adapter.

Review effort: Balanced

type_args = tuple(_substitute_typevars(a, current_map) for a in get_args(base))
if type_params and len(type_params) == len(type_args):
new_map = dict(zip(type_params, type_args))
result.update(new_map)
Comment on lines +96 to +101
if f.default is not dataclasses.MISSING:
fields_spec.append((f.name, resolved_type, f.default))
elif f.default_factory is not dataclasses.MISSING: # type: ignore[misc]
fields_spec.append((f.name, resolved_type, dataclasses.field(default_factory=f.default_factory))) # type: ignore[misc]
else:
fields_spec.append((f.name, resolved_type))
Comment on lines +151 to 152
self._resolved_adapter.validate_json(json_str, strict=True)
typed_dict = self._adapted_type.validate_json(json_str, strict=True)
@0xArx

Copy link
Copy Markdown
Author

Closing this since I can't sign the CLA. The issue and the review notes above (kw_only fields, reused TypeVars, keeping the resolved values) should help whoever picks up #550.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Python: runtime validator accepts a string for an inherited dataclass field specialized to int

2 participants