Skip to content

Fix TypeError for inherited Annotated fields with unhashable metadata - #556

Merged
robgruen merged 5 commits into
microsoft:mainfrom
shubhambhar007:fix/543-unhashable-annotated-metadata
Dec 4, 2026
Merged

robgruen merged 5 commits into
microsoft:mainfrom
shubhambhar007:fix/543-unhashable-annotated-metadata

Conversation

@shubhambhar007

Copy link
Copy Markdown
Contributor

Closes #543

Inherited annotations were collected into a set, so Annotated metadata that is not hashable (for example a dict) raised TypeError: unhashable type: 'dict'.

This follows the fix suggested in the issue:

  • base_attributes is now OrderedDict[str, list[object]] and collects hints with setdefault(prop, []).append(type_hint).
  • attribute_identical_in_all_bases compares with all(base_hint == type_hint for base_hint in base_attributes[attr_name]).

Behaviour is unchanged for hashable hints: identical annotations across bases are still omitted from the subclass, and differing ones are still redeclared.

Tests (python/tests/test_unhashable_annotated_metadata.py) cover inherited dictionary metadata (the reproduction from the issue, including validation), identical base annotations, and conflicting base annotations. The three tests fail on the previous code with the reported TypeError and pass now.

Checked locally on Python 3.12: full suite passes (828 passed), and mypy and black report the same results as before the change. ruff and black are clean on the new test file.

Store inherited annotations in lists and compare them with == instead of
hashing them, so Annotated metadata such as dicts no longer raises.

Closes microsoft#543
Copilot AI balanced review requested due to automatic review settings December 2, 2026 09:35

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.

🟢 Approval recommended

No active review issues were identified in the change supporting inherited Annotated fields with unhashable metadata.

No open issues 🎉

What changed in this PR

Fixes #543 by allowing inherited Annotated fields with unhashable metadata in Python-to-TypeScript schema conversion.

Changes:

  • Replaces set-based annotation collection with lists and equality comparisons.
  • Adds regression tests for dictionary metadata, validation, and identical or conflicting inherited annotations.
File Description
python/​tests/​test_unhashable_annotated_metadata.py Adds regression coverage for unhashable metadata and inheritance behavior.
python/​src/​typechat/​_internal/​ts_conversion/​python_type_to_ts_nodes.py Removes hashing requirements when comparing inherited annotations.

Review effort: Balanced

@robgruen

robgruen commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Copilot resolve the merge conflicts in this pull request

Resolve the annotation collection conflict while preserving cached base type hints from the InitVar change.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings December 2, 2026 21:28

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.

🟢 Approval recommended

No active review issues were identified for the fix supporting inherited annotations with unhashable metadata.

No open issues 🎉

Review effort: Balanced

@robgruen robgruen 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.

Thanks for fixing #543, Shubham Bhardwaj (@shubhambhar007). All three new regression tests fail on main and pass on this revision. Could you also preserve the existing behavior for hashable annotations before we merge? I left a runnable example and a suggested hash check on the comparison below.

identical to those declared in all base types.
"""
return attr_name in base_attributes and len(base_attributes[attr_name]) == 1 and type_hint in base_attributes[attr_name]
return attr_name in base_attributes and all(base_hint == type_hint for base_hint in base_attributes[attr_name])

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.

This == can now run for annotations that the old set lookup could distinguish without comparing. Here's a case I reproduced on Python 3.14; it doesn't make any network requests:

from typing import Annotated

from httpx import URL
from typing_extensions import TypedDict
from typechat import python_type_to_typescript_schema

class Linked(TypedDict):
    name: Annotated[str, URL("https://adatum.com/schema")]

class Described(TypedDict):
    name: Annotated[str, "Display name\nShown to the user."]

class Child(Linked, Described):
    count: int

result = python_type_to_typescript_schema(Child)
assert not result.errors
print(result.typescript_schema_str)

On main, Child redeclares name: string; with the two-line description. On cf86109, httpx.URL.__eq__ tries to parse that description as a URL, so schema generation raises httpx.InvalidURL. Both annotations are hashable and their hashes differ, so the set never invoked == for this pair.

Would you keep the list for unhashable metadata, but give the comparison a hash shortcut? Identical objects can match immediately. For other pairs, if both hash() calls succeed and the hashes differ, treat the hints as different without calling ==. If the hashes match, or either hint is unhashable (hash() raises TypeError), fall back to ==. That way a hash collision doesn't imply equality, and the dictionary case still works.

Could you also add a regression test that checks name: string; is redeclared in the child interface for this example? Thanks!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks, reproduced on 3.12 with httpx 0.29: httpx.InvalidURL from URL.__eq__ on the old head.

Done in 3985faf, as you suggested. The list stays, so unhashable metadata still works, and hints_match now does:

  • identical objects match immediately;
  • if both hints hash and the hashes differ, they are different and == is not called;
  • if the hashes match, or hash() raises TypeError, it falls back to == (so a collision never implies equality).

Tests added in test_unhashable_annotated_metadata.py:

  • your example (URL vs a two-line description), asserting name: string; is redeclared in the child interface;
  • a metadata class whose __eq__ raises, to show it is not called when the hashes differ;
  • two classes with a constant hash, to show == is still used when hashes match (equal ones are omitted, different ones are redeclared).

The new NeverCompared test fails on the previous revision. Full suite passes locally (878), and your script now generates the schema.

Compare identical objects directly. When both hints are hashable and their
hashes differ, treat them as different without calling __eq__, as the old set
lookup did; metadata such as httpx.URL can raise from __eq__. Fall back to ==
when the hashes match or a hint is unhashable.

Adds the httpx.URL example from review and tests that __eq__ is not called for
hints that hash differently and is still used when hashes match.
Copilot AI balanced review requested due to automatic review settings December 3, 2026 06:32

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.

🟢 Approval recommended

No active review issues were identified for the change supporting inherited annotations with unhashable metadata.

No open issues 🎉

Review effort: Balanced

@robgruen

robgruen commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Shubham Bhardwaj (@shubhambhar007) , can you look into the build failures please. I think once we get those working we can get this merged.

The repo's pyright config enables reportImplicitOverride and
reportMissingSuperCall, which flagged NeverCompared and SameHash. Mark
__hash__ and __eq__ with @OverRide and call super().__init__().
Copilot AI balanced review requested due to automatic review settings December 4, 2026 17:58

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.

🟢 Approval recommended

No active review issues are blocking approval.

No open issues 🎉

Review effort: Balanced

@shubhambhar007

Copy link
Copy Markdown
Contributor Author

robgruen the build failure was pyright (all four Python versions); Node.js CI was green. It was only in my new test file: the repo's strict pyright config enables reportImplicitOverride and reportMissingSuperCall, and the helper classes NeverCompared and SameHash in python/tests/test_unhashable_annotated_metadata.py had __init__, __hash__ and __eq__ without them (6 errors, no source files involved).

Fixed in 1be4dbd: @override (from typing_extensions, since the project supports 3.11) on __hash__ and __eq__, and super().__init__() in both __init__s.

I reproduced the same 6 errors locally with the CI-pinned pyright 1.1.358 against the previous head, and it reports 0 errors on this one with both --pythonversion 3.12 and 3.11. pytest is 878 passed. The workflows on the new commit need approval to run, since this is a fork PR.

Python 3.14 evaluates annotations again inside get_type_hints, and typing's
Annotated cache compares the equal NeverCompared tag, which raised. It still
raises for a different tag, which is the case the test guards.
Copilot AI balanced review requested due to automatic review settings December 4, 2026 18:42
@shubhambhar007

Copy link
Copy Markdown
Contributor Author

Update: with the workflows approved, pyright passed on 3.11, 3.12 and 3.13, and the 3.14 job failed in a test I added (test_hashable_annotations_that_hash_differently_are_redeclared_without_comparing), not in pyright (0 errors) and not in the converter.

Cause: Python 3.14 evaluates annotations lazily and again inside get_type_hints, so Annotated[str, NeverCompared("a")] is evaluated a second time and typing's Annotated cache compares it with the cached equal one. My test helper's __eq__ always raised, so it tripped there. Fixed in cbbe6cb: NeverCompared.__eq__ now returns True for the same tag and still raises for a different tag, which is the case the test guards.

Verified on CPython 3.14.10 and 3.12: pytest is 878 passed on both, and pyright 1.1.358 is 0 errors on 3.11, 3.12, 3.13 and 3.14. I also checked the guard still bites: with the hash shortcut removed from hints_match, the test fails on both 3.12 and 3.14.

The new commit needs the workflows approved once more to run.

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.

🟢 Approval recommended

No active review issues are reported for the change supporting inherited Annotated fields with unhashable metadata.

No open issues 🎉

Review effort: Balanced

@robgruen robgruen 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.

Thank you for the fix

@robgruen
robgruen merged commit 148e637 into microsoft:main Dec 4, 2026
8 checks passed
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 schema conversion crashes on inherited Annotated fields with unhashable metadata

3 participants