Repository navigation
fix(python): enforce inherited-generic field types in TypeChatValidator - #553
Closed
0xARX (0xArx) wants to merge 1 commit into
Closed
0xARX (0xArx) wants to merge 1 commit into
0xARX (0xArx) wants to merge 1 commit into
Conversation
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.
Contributor
There was a problem hiding this comment.
🟡 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) |
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Fixes #550.
Problem
TypeChatValidatorsilently accepted values whose types were wrong for fields that come from a specialised generic base class. For example:The root cause is that Pydantic's
TypeAdapter(IntBox)builds its JSON schema from the generic base (Box) and therefore does not constrain theitemfield toint.Fix
On construction,
TypeChatValidatornow detects when the target type is a dataclass whose annotations still contain TypeVars after aget_type_hints()call. It walks__orig_bases__to build a TypeVar → concrete-type mapping, then usesdataclasses.make_dataclassto create a structurally identical class with every TypeVar replaced by its concrete type. A secondpydantic.TypeAdapteris 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.ValidationErrorwith the correct path and message when a value is wrong. The original adapter then runs to produce aSuccessvalue 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.pycovering:IntBox(Box[int])— valid int, invalid string, invalid float, missing fieldStrListBox(ListBox[str])— valid list, list with wrong element typesIntBoxChild(IntBox)— transitive TypeVar inheritance (two hops)IntBox), not the resolved copy