From 7a3f66764475c047836cb42f28ca0d91e428421c Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Fri, 9 Oct 2026 22:41:42 +0800 Subject: [PATCH 1/3] Fix Python collection reference comparison Compare native collection references by guarded canonical COM identity across projected and raw views, preserving ordinary Python value equality and native error propagation. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: ed3ecfbc-fdc5-473b-aa81-2a6721f7b7b6 --- .github/workflows/build.yml | 5 +- bindings/py/README.md | 14 + bindings/py/python/dynwinrt/values.py | 29 +- bindings/py/src/lib.rs | 122 ++++++- .../py/tests/test_collection_comparison.py | 345 ++++++++++++++++++ bindings/py/tests/test_object_value_view.py | 37 ++ .../src/codegen/winrt/python/stubs.rs | 4 +- .../tests/python_consumer_typing_test.rs | 274 ++++++++++++++ 8 files changed, 808 insertions(+), 22 deletions(-) create mode 100644 bindings/py/tests/test_collection_comparison.py diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 869eed99..6f9ed238 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -564,12 +564,15 @@ jobs: --test implementation_naming_test ` --test python_overload_legacy_compat_test ` --test python_released_implementation_test - - name: Test generated nullable collection values + - name: Test generated collection protocols shell: pwsh run: | $env:DYNWINRT_TEST_PYTHON = (Resolve-Path .\bindings\py\.venv\Scripts\python.exe).Path $env:DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME = '1' $env:DYNWINRT_REQUIRE_MYPY = '1' + cargo test -p dynwinrt-codegen --test python_consumer_typing_test ` + collection_comparisons_preserve_native_identity_and_python_value_semantics -- --exact + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } cargo test -p dynwinrt-codegen --test python_consumer_typing_test ` mutable_collection_mutators_accept_none -- --exact if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } diff --git a/bindings/py/README.md b/bindings/py/README.md index c3a3bdac..0d9a7bca 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -162,6 +162,20 @@ and iterators work with `iter()` and `next()`. Mutable vectors support indexing, slicing, assignment, insertion, and deletion; mutable maps support standard mapping assignment and deletion. +Sequence containment, `index()`, `count()`, and `remove()`, mapping equality, +and value/item-view membership compare WinRT references by canonical COM +identity, including different generated class/interface views and raw +`DynWinRTValue` carriers of the same object. This is reference identity, not a +runtime class's `equals()` or content comparison. Python scalars and generated +structs retain their normal equality, and released or wrong-thread native +access still raises. Wrapper/value `==` and hashing outside these collection +operations are unchanged. + +Raw `Object` collections do not implicitly box or unbox for comparison: +different boxes remain different references. An opt-in `object_value_view()` +compares its converted Python values normally and any remaining native +references by COM identity. + Method inputs accept normal Python sequences and mappings in place of compatible WinRT collection interfaces, subject to the producer limits below. Byte arrays accept `bytes` and `bytearray`; GUID, diff --git a/bindings/py/python/dynwinrt/values.py b/bindings/py/python/dynwinrt/values.py index 46f7c542..143ec175 100644 --- a/bindings/py/python/dynwinrt/values.py +++ b/bindings/py/python/dynwinrt/values.py @@ -30,9 +30,18 @@ import operator import struct -from collections.abc import Callable, Iterable, Iterator, Mapping, MutableMapping +from collections.abc import ( + Callable, + Iterable, + Iterator, + ItemsView, + Mapping, + MutableMapping, + ValuesView, +) from datetime import datetime, timedelta from enum import IntEnum +from importlib import import_module as _import_module from typing import ( TYPE_CHECKING, Any, @@ -50,6 +59,8 @@ from dynwinrt import DynWinRTType, DynWinRTValue, WinGUID, to_winrt_object, unbox_object +_native = _import_module("dynwinrt.dynwinrt") + if TYPE_CHECKING: from _typeshed import SupportsKeysAndGetItem @@ -790,7 +801,9 @@ class ObjectValueView(Mapping[_K, WinRTObjectValue]): ``datetime.datetime``. Other errors propagate. Every operation goes to the map; the view holds no WinRT reference of its - own. ``raw`` is the generated map, whose values stay native. + own. ``raw`` is the generated map, whose values stay native. Equality and + value/item membership compare remaining native references by COM identity; + converted Python values retain their normal equality. """ __slots__ = ("_map", "_preserve_type") @@ -833,6 +846,18 @@ def __len__(self) -> int: def __contains__(self, key: object) -> bool: return key in self._map + def __eq__(self, other: object) -> bool: + mapping_equal: Callable[[object, object], bool] = _native._dynwinrt_mapping_equal + return mapping_equal(self, other) + + def items(self) -> ItemsView[_K, WinRTObjectValue]: + view: ItemsView[_K, WinRTObjectValue] = _native._WinRTItemsView(self) + return view + + def values(self) -> ValuesView[WinRTObjectValue]: + view: ValuesView[WinRTObjectValue] = _native._WinRTValuesView(self) + return view + def __repr__(self) -> str: options = ", preserve_type=True" if self._preserve_type else "" return f"dynwinrt.values.{type(self).__name__}({self._map!r}{options})" diff --git a/bindings/py/src/lib.rs b/bindings/py/src/lib.rs index 8bba4e28..ccad8189 100644 --- a/bindings/py/src/lib.rs +++ b/bindings/py/src/lib.rs @@ -26,10 +26,12 @@ from collections.abc import ( Coroutine as _Coroutine, Iterable as _Iterable, Iterator as _Iterator, + ItemsView as _ItemsView, Mapping as _Mapping, MutableMapping as _MutableMapping, MutableSequence as _MutableSequence, Sequence as _Sequence, + ValuesView as _ValuesView, ) from datetime import datetime as _datetime, timedelta as _timedelta, timezone as _timezone from itertools import count as _count @@ -515,16 +517,65 @@ def _dynwinrt_preflight_non_null_collection(self, values): native._validate_non_null_collection_input(raw, *contract) return items -class _WinRTSequenceMixin(_Sequence): - def __len__(self): - return self.size +_dynwinrt_no_collection_identity = object() +_dynwinrt_collection_iunknown = None - def __getitem__(self, index): - if isinstance(index, slice): - return [self.get_at(i) for i in range(*index.indices(len(self)))] - return self.get_at(_dynwinrt_normalize_index(index, len(self))) +def _dynwinrt_collection_identity(value): + if value is None: + return None + native = getattr(value, '_obj', value) + if not isinstance(native, DynWinRTValue): + return _dynwinrt_no_collection_identity + global _dynwinrt_collection_iunknown + if _dynwinrt_collection_iunknown is None: + _dynwinrt_collection_iunknown = WinGUID.parse( + '00000000-0000-0000-c000-000000000046' + ) + # The probe checks lifetime/thread access even for scalar and null carriers. + if native._try_query_interface(_dynwinrt_collection_iunknown): + identity = native.cast(_dynwinrt_collection_iunknown) + try: + return identity.as_raw() + finally: + identity.release() + return None if native.is_null() else _dynwinrt_no_collection_identity + +def _dynwinrt_collection_equal(left, right): + left_identity = _dynwinrt_collection_identity(left) + right_identity = _dynwinrt_collection_identity(right) + if ( + left_identity is not _dynwinrt_no_collection_identity + and right_identity is not _dynwinrt_no_collection_identity + ): + return left_identity == right_identity + return left is right or left == right + +def _dynwinrt_collection_key(key): + identity = _dynwinrt_collection_identity(key) + if identity is _dynwinrt_no_collection_identity: + return key + if identity is None: + return None + return (_dynwinrt_no_collection_identity, identity) + +def _dynwinrt_mapping_equal(left, right): + if not isinstance(right, _Mapping): + return NotImplemented + # Retain native keys while their canonical identities are dictionary keys. + left_pairs = list(left.items()) + right_pairs = list(right.items()) + left_items = { + _dynwinrt_collection_key(key): value for key, value in left_pairs + } + right_items = { + _dynwinrt_collection_key(key): value for key, value in right_pairs + } + return left_items.keys() == right_items.keys() and all( + _dynwinrt_collection_equal(value, right_items[key]) + for key, value in left_items.items() + ) -class _WinRTMutableSequenceMixin(_MutableSequence): +class _WinRTSequenceMixin(_Sequence): def __len__(self): return self.size @@ -533,6 +584,31 @@ class _WinRTMutableSequenceMixin(_MutableSequence): return [self.get_at(i) for i in range(*index.indices(len(self)))] return self.get_at(_dynwinrt_normalize_index(index, len(self))) + def __contains__(self, value): + return any(_dynwinrt_collection_equal(item, value) for item in self) + + def index(self, value, start=0, stop=None): + start = _index(start) + if start < 0: + start = max(0, len(self) + start) + if stop is not None: + stop = _index(stop) + if stop < 0: + stop += len(self) + while stop is None or start < stop: + try: + item = self[start] + except IndexError: + break + if _dynwinrt_collection_equal(item, value): + return start + start += 1 + raise ValueError + + def count(self, value): + return sum(1 for item in self if _dynwinrt_collection_equal(item, value)) + +class _WinRTMutableSequenceMixin(_WinRTSequenceMixin, _MutableSequence): def __setitem__(self, index, value): if isinstance(index, slice): items = list(self) @@ -577,6 +653,19 @@ class _WinRTIteratorMixin(_Iterator): self.move_next() return value +class _WinRTItemsView(_ItemsView): + def __contains__(self, item): + key, value = item + try: + candidate = self._mapping[key] + except KeyError: + return False + return _dynwinrt_collection_equal(candidate, value) + +class _WinRTValuesView(_ValuesView): + def __contains__(self, value): + return any(_dynwinrt_collection_equal(item, value) for item in self) + class _WinRTMappingMixin(_Mapping): def __len__(self): return self.size @@ -590,19 +679,16 @@ class _WinRTMappingMixin(_Mapping): raise KeyError(key) return self.lookup(key) -class _WinRTMutableMappingMixin(_MutableMapping): - def __len__(self): - return self.size + def __eq__(self, other): + return _dynwinrt_mapping_equal(self, other) - def __iter__(self): - for pair in self._iter_pairs(): - yield pair.key + def items(self): + return _WinRTItemsView(self) - def __getitem__(self, key): - if not self.has_key(key): - raise KeyError(key) - return self.lookup(key) + def values(self): + return _WinRTValuesView(self) +class _WinRTMutableMappingMixin(_WinRTMappingMixin, _MutableMapping): def __setitem__(self, key, value): self.insert(key, value) diff --git a/bindings/py/tests/test_collection_comparison.py b/bindings/py/tests/test_collection_comparison.py new file mode 100644 index 00000000..7e344a18 --- /dev/null +++ b/bindings/py/tests/test_collection_comparison.py @@ -0,0 +1,345 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Collection-only comparison, including guarded native reference identity.""" + +from dataclasses import dataclass +from datetime import datetime, timedelta, timezone +from enum import IntEnum +import gc +import threading +from types import SimpleNamespace +from uuid import UUID +import weakref + +import pytest + +from dynwinrt import ( + DynWinRTArray, + DynWinRTImplementation, + DynWinRTImplementationMethod, + DynWinRTInterfacePlan, + DynWinRTMethodSig, + DynWinRTType, + DynWinRTValue, + RoApartment, + WinGUID, +) +from dynwinrt.dynwinrt import ( + _WinRTMappingMixin, + _WinRTMutableMappingMixin, + _WinRTMutableSequenceMixin, + _WinRTSequenceMixin, + _dynwinrt_collection_equal, +) +from dynwinrt.values import Point, Rect, Size + + +class SequenceProjection(_WinRTSequenceMixin): + def __init__(self, items): + self._items = list(items) + + @property + def size(self): + return len(self._items) + + def get_at(self, index): + return self._items[index] + + +class MutableSequenceProjection(SequenceProjection, _WinRTMutableSequenceMixin): + def remove_at(self, index): + del self._items[index] + + +class MappingProjection(_WinRTMappingMixin): + def __init__(self, items): + self._items = dict(items) + + @property + def size(self): + return len(self._items) + + def has_key(self, key): + return key in self._items + + def lookup(self, key): + return self._items[key] + + def _iter_pairs(self): + return (SimpleNamespace(key=key) for key in self._items) + + +class MutableMappingProjection(MappingProjection, _WinRTMutableMappingMixin): + def insert(self, key, value): + self._items[key] = value + + def remove(self, key): + del self._items[key] + + +class Index: + def __init__(self, value): + self.value = value + + def __index__(self): + return self.value + + +class Number(IntEnum): + NEGATIVE = -1 + HIGH_BIT = 0x80000000 + + +@dataclass +class Fields: + number: int + text: str + + +@pytest.mark.parametrize("projection", [SequenceProjection, MutableSequenceProjection]) +@pytest.mark.parametrize( + "value", + [ + None, True, 17, Number.NEGATIVE, Number.HIGH_BIT, "text", + UUID("01234567-89ab-cdef-0123-456789abcdef"), + datetime(2026, 1, 1, tzinfo=timezone.utc), timedelta(seconds=3), + Point(1, 2), Size(3, 4), Rect(1, 2, 3, 4), Fields(7, "field"), + ], +) +def test_projected_values_keep_python_equality(projection, value): + sequence = projection([value, value]) + assert value in sequence + assert sequence.index(value) == 0 + assert sequence.count(value) == 2 + for mapping_type in (MappingProjection, MutableMappingProjection): + mapping = mapping_type({"value": value}) + assert mapping == {"value": value} and {"value": value} == mapping + assert value in mapping.values() and ("value", value) in mapping.items() + assert mapping != [("value", value)] + with pytest.raises(TypeError): + hash(mapping) + + +@pytest.mark.parametrize("start", [-20, -3, -1, 0, 1, 4, 20, 2**80]) +@pytest.mark.parametrize("stop", [None, -20, -1, 0, 2, 4, 20, 2**80]) +@pytest.mark.parametrize("projection", [SequenceProjection, MutableSequenceProjection]) +def test_index_bounds_and_first_match_agree_with_python_list(projection, start, stop): + values = [1, 2, 1, 3] + sequence = projection(values) + try: + expected = values.index(1, start) if stop is None else values.index(1, start, stop) + except ValueError: + with pytest.raises(ValueError): + sequence.index(1, Index(start), None if stop is None else Index(stop)) + else: + assert sequence.index(1, Index(start), None if stop is None else Index(stop)) == expected + + +def test_invalid_bounds_and_duplicate_removal(): + sequence = MutableSequenceProjection([1, 2, 1]) + for arguments in ((1, 0.5), (1, 0, 2.5), (1, None)): + with pytest.raises(TypeError): + sequence.index(*arguments) + sequence.remove(1) + assert list(sequence) == [2, 1] and sequence.index(1) == 1 + with pytest.raises(ValueError): + sequence.remove(4) + assert list(sequence) == [2, 1] + + +def test_nan_identity_and_reverse_equality_are_ordinary_python_comparisons(): + nan = float("nan") + different_nan = float("nan") + sequence = MutableSequenceProjection([nan]) + assert nan in sequence and sequence.count(nan) == 1 + assert different_nan not in sequence and sequence.count(different_nan) == 0 + assert MappingProjection({"nan": nan}) == {"nan": nan} + assert MappingProjection({"nan": nan}) != {"nan": different_nan} + + class Reverse: + def __eq__(self, other): + return other == 17 or isinstance(other, MappingProjection) + + assert Reverse() in SequenceProjection([17]) + assert MappingProjection({"number": 17}) == {"number": Reverse()} + assert MappingProjection({}) == Reverse() + + class NullKey: + def __eq__(self, other): + return other is None + + def __hash__(self): + return hash(None) + + assert MappingProjection({None: 17}) == {NullKey(): 17} + assert MappingProjection({nan: 17}) == {nan: 17} + assert MappingProjection({nan: 17}) != {different_nan: 17} + + +def test_comparison_and_native_read_errors_are_not_hidden(): + class BadEquality: + def __eq__(self, other): + raise RuntimeError("comparison failed") + + class BadRead(SequenceProjection): + def get_at(self, index): + raise OSError("read failed") + + bad = BadEquality() + for operation in ( + lambda: 1 in SequenceProjection([bad]), + lambda: SequenceProjection([bad]).index(1), + lambda: MutableSequenceProjection([bad]).remove(1), + lambda: MappingProjection({"bad": bad}) == {"bad": 1}, + lambda: 1 in BadRead([1]), + lambda: BadRead([1]).index(1), + ): + with pytest.raises((RuntimeError, OSError), match="failed"): + operation() + + +def native_reference(): + """Full SDK IStringable and IClosable plans with distinct interface pointers.""" + plans = [] + for name, iid, method, signature in ( + ( + "Windows.Foundation.IStringable", "96369f54-8eb6-48f0-abce-c1b211e627c3", + "ToString", DynWinRTMethodSig().add_out(DynWinRTType.hstring()), + ), + ( + "Windows.Foundation.IClosable", "30d5a829-7fa4-4026-83bb-d75bae4ea99e", + "Close", DynWinRTMethodSig(), + ), + ): + typ = DynWinRTType.register_interface(name, WinGUID.parse(iid)).add_method( + method, signature + ) + plans.append(DynWinRTInterfacePlan.create( + name, typ, [DynWinRTImplementationMethod(method, 6, signature)] + )) + + class Handler: + calls = 0 + + def dispatch(self, interface, slot, args): + self.calls += 1 + return [DynWinRTValue.from_hstring("live")] if interface == 0 else [] + + handler = Handler() + owner = DynWinRTImplementation.create(plans, handler.dispatch) + raw = owner.to_value() + alias = raw.cast(WinGUID.parse("30d5a829-7fa4-4026-83bb-d75bae4ea99e")) + return handler, owner, raw, alias + + +def test_canonical_identity_does_not_call_content_methods_or_consume_source(): + with RoApartment(): + handler, owner, raw, alias = native_reference() + retained = weakref.ref(handler) + assert raw.as_raw() != alias.as_raw() + assert raw.identity_raw() == alias.identity_raw() + projected = SimpleNamespace(_obj=raw) + assert _dynwinrt_collection_equal(projected, alias) + assert not _dynwinrt_collection_equal(raw, DynWinRTValue.null_value()) + assert _dynwinrt_collection_equal(None, DynWinRTValue.null_value()) + for projection in (SequenceProjection, MutableSequenceProjection): + sequence = projection([alias, None, alias]) + assert projected in sequence and sequence.index(raw, 1) == 2 + assert sequence.count(projected) == 2 + for projection in (MappingProjection, MutableMappingProjection): + mapping = projection({alias: raw}) + assert mapping == {raw: alias} + assert projected in mapping.values() and (alias, projected) in mapping.items() + assert not raw.is_released() and not alias.is_released() + assert handler.calls == 0 + alias.release() + owner.release() + assert raw.identity_raw() != 0 + raw.release() + del handler, owner + gc.collect() + assert retained() is None + + +def test_released_native_values_never_compare_as_live_null_or_same_object(): + with RoApartment(): + handler, owner, raw, alias = native_reference() + raw.release() + for operation in ( + lambda: _dynwinrt_collection_equal(raw, raw), + lambda: _dynwinrt_collection_equal(raw, None), + lambda: raw in SequenceProjection([alias]), + lambda: SequenceProjection([alias]).index(raw), + lambda: MutableSequenceProjection([raw]).remove(alias), + lambda: MappingProjection({"value": raw}) == {"value": alias}, + lambda: raw in MappingProjection({"value": alias}).values(), + lambda: ("value", raw) in MappingProjection({"value": alias}).items(), + ): + with pytest.raises(RuntimeError, match="has been released"): + operation() + assert alias.identity_raw() != 0 and handler.calls == 0 + alias.release() + owner.release() + + +def test_nonagile_identity_normalization_rejects_foreign_native_access(): + with RoApartment(): + handler, owner, raw, alias = native_reference() + # Received carriers use the native agility policy, unlike implementation owners. + received = DynWinRTArray.from_object_values([raw], DynWinRTType.object()) + guarded = received.get(0) + guarded_alias = guarded.cast( + WinGUID.parse("30d5a829-7fa4-4026-83bb-d75bae4ea99e") + ) + errors = [] + + def worker(): + try: + with RoApartment(): + for operation in ( + lambda: _dynwinrt_collection_equal(guarded, guarded), + lambda: guarded in SequenceProjection([guarded_alias]), + lambda: MappingProjection({"value": guarded}) == {"value": guarded_alias}, + ): + with pytest.raises(RuntimeError, match="owning COM apartment thread"): + operation() + except BaseException as error: + errors.append(error) + + thread = threading.Thread(target=worker) + thread.start() + thread.join(10) + assert not thread.is_alive() and not errors, errors + assert handler.calls == 0 and raw.identity_raw() == alias.identity_raw() + guarded_alias.release() + guarded.release() + received.release() + alias.release() + raw.release() + owner.release() + + +def test_agile_identity_normalization_preserves_foreign_access_and_source(): + with RoApartment(): + native = DynWinRTValue.activation_factory("Windows.Foundation.Uri") + assert native._try_query_interface( + WinGUID.parse("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90") + ) + alias = native.cast(WinGUID.parse("00000000-0000-0000-c000-000000000046")) + errors = [] + + def worker(): + try: + with RoApartment(): + assert _dynwinrt_collection_equal(native, alias) + assert native in SequenceProjection([alias]) + assert MappingProjection({"value": native}) == {"value": alias} + except BaseException as error: + errors.append(error) + + thread = threading.Thread(target=worker) + thread.start() + thread.join(10) + assert not thread.is_alive() and not errors, errors + assert not native.is_released() and native.identity_raw() == alias.identity_raw() diff --git a/bindings/py/tests/test_object_value_view.py b/bindings/py/tests/test_object_value_view.py index 4f2d5a53..951bf881 100644 --- a/bindings/py/tests/test_object_value_view.py +++ b/bindings/py/tests/test_object_value_view.py @@ -621,6 +621,43 @@ def test_dict_and_equality_use_converted_values(): assert view != [("count", 5)] +def test_equality_and_membership_preserve_remaining_native_reference_identity(): + properties = property_set() + native = uri() + alias = native.cast(WinGUID.parse("00000000-0000-0000-c000-000000000046")) + different = uri() + view = object_value_view(properties) + view["uri"] = native + view["count"] = 5 + view["null"] = None + readonly = properties.get_view() + for mapping in (properties, readonly): + count = properties["count"] + expected = {"uri": alias, "count": count, "null": DynWinRTValue.null_value()} + assert mapping == mapping and mapping == expected and expected == mapping + assert native in mapping.values() and ("uri", alias) in mapping.items() + assert different not in mapping.values() + assert ("uri", different) not in mapping.items() + assert mapping != {"uri": native, "count": to_winrt_object(5), "null": None} + assert mapping != {"uri": native, "count": 5, "null": None} + for converted in (view, object_value_view(readonly)): + assert converted == converted + assert converted == {"uri": alias, "count": 5, "null": None} + assert converted != {"uri": different, "count": 5, "null": None} + assert native in converted.values() and ("uri", alias) in converted.items() + assert 5 in converted.values() and ("count", 5) in converted.items() + assert different not in converted.values() + assert not native.is_released() and not alias.is_released() + + +def test_converted_nan_keeps_python_equality_instead_of_raw_box_identity(): + view = object_value_view(property_set()) + view["nan"] = float("nan") + assert view.raw == view.raw + assert view != view and float("nan") not in view.values() + assert ("nan", float("nan")) not in view.items() + + def test_mutable_mapping_methods(): view = object_value_view(property_set()) view.update({"a": 1}, b="x") diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs index 95524302..597d4660 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs @@ -1359,6 +1359,7 @@ fn collection_protocol_stubs( | super::collections::CollectionKind::MutableSequence => { let mut result = format!( "\n{indent}def __len__(self) -> int: ...\n\ + {indent}def __contains__(self, value: object) -> bool: ...\n\ {indent}@overload\n\ {indent}def __getitem__(self, index: int) -> {item_type}: ...\n\ {indent}@overload\n\ @@ -1404,7 +1405,8 @@ fn collection_protocol_stubs( let mut result = format!( "\n{indent}def __len__(self) -> int: ...\n\ {indent}def __iter__(self) -> Iterator[{key_type}]: ...\n\ - {indent}def __getitem__(self, key: {item_input}) -> {value_type}: ...\n" + {indent}def __getitem__(self, key: {item_input}) -> {value_type}: ...\n\ + {indent}def __eq__(self, other: object) -> bool: ...\n" ); if kind == super::collections::CollectionKind::MutableMapping { let value_input = iface diff --git a/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs b/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs index 8eda636e..27602291 100644 --- a/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs +++ b/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs @@ -1102,6 +1102,280 @@ print("collection-subscript-native-ok", flush=True) } } +#[test] +fn collection_comparisons_preserve_native_identity_and_python_value_semantics() { + let winmd = Path::new( + r"C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd", + ); + if !winmd.is_file() || !has_mypy() || !has_implementation_runtime() { + eprintln!("Skipping SDK collection comparisons: metadata, mypy or runtime unavailable."); + return; + } + let fixture = Fixture::new(); + let output = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")) + .args(["generate", "--winmd"]) + .arg(winmd) + .args([ + "--class-name", + "Windows.Data.Json.JsonArray,Windows.Data.Json.JsonObject,Windows.Data.Json.JsonValue,\ + Windows.Foundation.Collections.PropertySet,Windows.Foundation.Collections.StringMap,\ + Windows.Foundation.Uri,Windows.Devices.Geolocation.Geopoint,\ + Windows.UI.Xaml.ResourceDictionary", + "--lang", + "py", + "--output", + ]) + .arg(fixture.0.join("sdk")) + .output() + .unwrap(); + assert!(output.status.success(), "{}", diagnostics(&output)); + let imports = r#"from typing import assert_type +from dynwinrt import DynWinRTValue +from dynwinrt.values import object_value_view +from sdk.windows.data.json import IJsonValue, JsonArray, JsonObject, JsonValue +from sdk.windows.foundation import Uri +from sdk.windows.foundation.collections import IMap_String_Object, PropertySet +"#; + typecheck( + &fixture, + &["sdk"], + &format!( + r#"{imports} +def valid(value: JsonValue, interface: IJsonValue, array: JsonArray, + mapping: JsonObject, properties: PropertySet, uri: Uri) -> None: + array.append(value) + assert_type(value in array, bool) + assert_type(array.index(value, -3, 3), int) + assert_type(array.count(interface), int) + array.remove(value) + view = array.get_view() + if view is not None: + assert_type(view.index(value), int) + assert_type(view.count(value), int) + assert_type(mapping == {{"value": value}}, bool) + assert_type(value in mapping.values(), bool) + assert_type(("value", value) in mapping.items(), bool) + assert_type(properties == {{"uri": uri}}, bool) + assert_type(properties == properties, bool) + assert_type(properties == properties.as_interface(IMap_String_Object), bool) + assert_type(properties.get_view() == properties.get_view(), bool) + assert_type(object_value_view(properties) == {{"uri": uri}}, bool) + assert_type(properties["uri"], DynWinRTValue | None) +"# + ), + &[], + ); + typecheck( + &fixture, + &["sdk"], + &format!( + r#"{imports} +def invalid(array: JsonArray, properties: PropertySet, uri: Uri) -> None: + array.append(None) + array.append(uri) + properties["implicit"] = 1 + raw: DynWinRTValue = properties["nullable"] +"# + ), + &["[arg-type]", "[arg-type]", "[assignment]", "[assignment]"], + ); + fs::write( + fixture.0.join("comparison_runtime.py"), + r#"from collections.abc import Mapping, MutableMapping, MutableSequence, Sequence +import math +from dynwinrt import DynWinRTType, DynWinRTValue, RoApartment, release_projected, to_winrt_object +from dynwinrt.values import object_value_view +from sdk.windows.data.json import IJsonValue, JsonArray, JsonObject, JsonValue +from sdk.windows.devices.geolocation import BasicGeoposition, Geopoint +from sdk.windows.foundation import IStringable, Uri +from sdk.windows.foundation.collections import ( + IMap_Object_Object, IMap_String_Object, IMapView_String_Object, PropertySet, StringMap, +) +from sdk.windows__data__json__json_array import IID_IJsonValue, IVector_IJsonValue + +class Index: + def __init__(self, value): + self.value = value + def __index__(self): + return self.value + +def raises(error_type, operation): + try: + operation() + except error_type: + return + raise AssertionError(f"{error_type.__name__} was not raised") + +with RoApartment(): + value = JsonValue.create_string_value("same") + different = JsonValue.create_string_value("same") + other = JsonValue.create_string_value("other") + array = JsonArray() + array.extend([other, value, value, other]) + mutable = IVector_IJsonValue.from_value(array._obj) + readonly = array.get_view() + assert isinstance(array, MutableSequence) and isinstance(readonly, Sequence) + interface = value.as_interface(IJsonValue) + assert interface._obj.identity_raw() == value._obj.identity_raw() + assert value._obj.identity_raw() != different._obj.identity_raw() + assert value._obj != interface._obj and value != interface + for sequence in (array, mutable, readonly): + assert sequence.index_of(value) == (1, True) + for candidate in (value, interface, value._obj): + assert candidate in sequence and sequence.count(candidate) == 2 + assert sequence.index(candidate) == 1 + assert sequence.index(candidate, 2) == 2 + assert sequence.index(candidate, Index(-3), Index(-1)) == 1 + raises(ValueError, lambda: sequence.index(candidate, 2, 2)) + raises(ValueError, lambda: sequence.index(candidate, 3, 20)) + assert different not in sequence and sequence.count(different) == 0 + raises(ValueError, lambda: sequence.index(different)) + assert None not in sequence + array.remove(value) + assert array.index(value) == 1 and len(array) == 3 + mutable.remove(value._obj) + assert value not in array and len(array) == 2 + raises(ValueError, lambda: array.remove(different)) + assert not value._obj.is_released() and value.get_string() == "same" + try: + value in readonly + except OSError as error: + assert error.winerror == -2147483636 # RO_E_CHANGED_STATE + else: + raise AssertionError("mutating JsonArray did not invalidate its native view") + readonly = array.get_view() + released_json = value.as_interface(IJsonValue) + release_projected(released_json) + for sequence in (array, mutable, readonly): + raises(RuntimeError, lambda: released_json in sequence) + raises(RuntimeError, lambda: sequence.index(released_json)) + raises(RuntimeError, lambda: sequence.count(released_json)) + raises(RuntimeError, lambda: array.remove(released_json)) + assert value.get_string() == "same" + interface = value.as_interface(IJsonValue) + + nullable = IVector_IJsonValue.from_value(DynWinRTValue.create_vector( + [DynWinRTValue.null_value(), value._obj, DynWinRTValue.null_value()], + DynWinRTType.interface(IID_IJsonValue), + )) + assert None in nullable and DynWinRTValue.null_value() in nullable + assert nullable.index(DynWinRTValue.null_value(), 1) == 2 + assert nullable.count(None) == 2 + nullable.remove(DynWinRTValue.null_value()) + assert nullable[0].get_string() == "same" and nullable[1] is None + json_null = JsonValue.create_null_value() + array.append(json_null) + assert json_null in array and None not in array + before = array.stringify() + raises(TypeError, lambda: array.extend([value, None])) + raises(TypeError, lambda: mutable.append(DynWinRTValue.null_value())) + assert array.stringify() == before + + json_map = JsonObject() + json_map["value"] = value + for mapping in (json_map, json_map.get_view()): + assert mapping == mapping and mapping == {"value": value} + assert mapping == {"value": interface} and mapping == {"value": value._obj} + assert mapping != {"value": different} + assert value in mapping.values() and ("value", value) in mapping.items() + before = json_map.stringify() + raises(TypeError, lambda: json_map.__setitem__("bad", None)) + assert json_map.stringify() == before + + uri = Uri("https://example.com/same") + other_uri = Uri("https://example.com/same") + stringable = uri.as_interface(IStringable) + assert uri.equals(other_uri) + assert uri._obj.identity_raw() != other_uri._obj.identity_raw() + object_keys = IMap_Object_Object.create({uri: uri, None: None}) + for mapping in (object_keys, object_keys.get_view()): + assert mapping == {stringable: uri._obj, None: None} + assert mapping == mapping and mapping != {other_uri: uri, None: None} + assert uri in mapping and stringable in mapping + assert (stringable, uri) in mapping.items() + box = to_winrt_object(1) + properties = PropertySet() + properties["uri"] = uri + properties["box"] = box + properties["null"] = None + mutable_map = properties.as_interface(IMap_String_Object) + readonly_map = properties.get_view() + typed_readonly = IMapView_String_Object.from_value(readonly_map._obj) + expected = {"uri": stringable, "box": box, "null": DynWinRTValue.null_value()} + for mapping in (properties, mutable_map, readonly_map, typed_readonly): + assert isinstance(mapping, Mapping) + assert mapping == mapping and mapping == expected and expected == mapping + assert mapping == properties and properties == mapping + assert uri in mapping.values() and ("uri", stringable) in mapping.items() + assert other_uri not in mapping.values() and ("uri", other_uri) not in mapping.items() + assert ("missing", uri) not in mapping.items() + assert mapping != {"uri": other_uri, "box": box, "null": None} + assert mapping != {"uri": uri, "box": to_winrt_object(1), "null": None} + assert mapping != {"uri": uri, "box": 1, "null": None} + assert mapping != {"uri": uri} and mapping != list(expected.items()) + raises(TypeError, lambda: hash(mapping)) + assert isinstance(mutable_map, MutableMapping) + assert not isinstance(readonly_map, MutableMapping) + assert properties["box"] != properties["box"] + + converted = object_value_view(properties) + converted_readonly = object_value_view(readonly_map) + for view in (converted, converted_readonly): + assert view == view and view == converted + assert view == {"uri": uri, "box": 1, "null": None} + assert view != {"uri": other_uri, "box": 1, "null": None} + assert uri in view.values() and ("uri", stringable) in view.items() + assert 1 in view.values() and ("box", 1) in view.items() + converted["nan"] = float("nan") + assert math.isnan(converted["nan"]) and converted != converted + del converted["nan"] + readonly_map = properties.get_view() + converted_readonly = object_value_view(readonly_map) + assert converted == converted_readonly + assert uri.absolute_uri == other_uri.absolute_uri + assert not uri._obj.is_released() and not box.is_released() + + strings = StringMap() + strings["key"] = "text" + assert strings == {"key": "text"} and {"key": "text"} == strings + assert strings.get_view() == strings + assert "text" in strings.values() and ("key", "text") in strings.items() + position = BasicGeoposition(latitude=1, longitude=2, altitude=3) + point = Geopoint(position) + assert point.position == position and position != BasicGeoposition() + + expected["uri"] = uri._obj + released = uri.as_interface(IStringable) + release_projected(released) + for operation in ( + lambda: properties == {"uri": released, "box": box, "null": None}, + lambda: released in properties.values(), + lambda: ("uri", released) in properties.items(), + lambda: converted == {"uri": released, "box": 1, "null": None}, + ): + raises(RuntimeError, operation) + assert uri.absolute_uri == "https://example.com/same" + release_projected(properties) + raises(RuntimeError, lambda: properties == properties) + raises(RuntimeError, lambda: converted == converted) + assert readonly_map == expected and uri.absolute_uri == "https://example.com/same" +print("collection-comparison-native-ok", flush=True) +"#, + ) + .unwrap(); + let output = Command::new(python()) + .args(["-B", "comparison_runtime.py"]) + .current_dir(&fixture.0) + .output() + .unwrap(); + assert!(output.status.success(), "{}", diagnostics(&output)); + assert!( + String::from_utf8_lossy(&output.stdout).contains("collection-comparison-native-ok"), + "{}", + diagnostics(&output) + ); +} + #[test] fn thread_pool_abi_names_keep_precise_callable_and_native_inputs() { let winmd = Path::new( From 0f4f8a6bfc99e5bf16da5f3af435419cbe9e1c52 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Fri, 9 Oct 2026 23:01:45 +0800 Subject: [PATCH 2/3] Preserve mapping cardinality across native key aliases Keep all mapping entries during canonical key normalization and require one-to-one matches, preventing distinct Python alias keys from collapsing into a falsely equal mapping. Cover both operand directions, mutable/read-only native maps, and same/different alias values. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: ed3ecfbc-fdc5-473b-aa81-2a6721f7b7b6 --- bindings/py/README.md | 2 ++ bindings/py/src/lib.rs | 22 ++++++++++--------- .../py/tests/test_collection_comparison.py | 10 +++++++++ .../tests/python_consumer_typing_test.rs | 16 ++++++++++++++ 4 files changed, 40 insertions(+), 10 deletions(-) diff --git a/bindings/py/README.md b/bindings/py/README.md index 0d9a7bca..7e85cb9d 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -170,6 +170,8 @@ runtime class's `equals()` or content comparison. Python scalars and generated structs retain their normal equality, and released or wrong-thread native access still raises. Wrapper/value `==` and hashing outside these collection operations are unchanged. +Mapping equality also preserves entry counts: distinct Python keys are not +collapsed into one entry just because they alias the same native reference. Raw `Object` collections do not implicitly box or unbox for comparison: different boxes remain different references. An opt-in `object_value_view()` diff --git a/bindings/py/src/lib.rs b/bindings/py/src/lib.rs index ccad8189..e3e650f7 100644 --- a/bindings/py/src/lib.rs +++ b/bindings/py/src/lib.rs @@ -564,16 +564,18 @@ def _dynwinrt_mapping_equal(left, right): # Retain native keys while their canonical identities are dictionary keys. left_pairs = list(left.items()) right_pairs = list(right.items()) - left_items = { - _dynwinrt_collection_key(key): value for key, value in left_pairs - } - right_items = { - _dynwinrt_collection_key(key): value for key, value in right_pairs - } - return left_items.keys() == right_items.keys() and all( - _dynwinrt_collection_equal(value, right_items[key]) - for key, value in left_items.items() - ) + left_keys = [_dynwinrt_collection_key(key) for key, _ in left_pairs] + right_values = {} + for key, value in right_pairs: + right_values.setdefault(_dynwinrt_collection_key(key), []).append(value) + if len(left_pairs) != len(right_pairs): + return False + # Identity normalization must match entries one-to-one, not collapse aliases. + for key, (_, value) in zip(left_keys, left_pairs): + candidates = right_values.pop(key, ()) + if len(candidates) != 1 or not _dynwinrt_collection_equal(value, candidates[0]): + return False + return not right_values class _WinRTSequenceMixin(_Sequence): def __len__(self): diff --git a/bindings/py/tests/test_collection_comparison.py b/bindings/py/tests/test_collection_comparison.py index 7e344a18..3ec0dfe1 100644 --- a/bindings/py/tests/test_collection_comparison.py +++ b/bindings/py/tests/test_collection_comparison.py @@ -251,6 +251,16 @@ def test_canonical_identity_does_not_call_content_methods_or_consume_source(): mapping = projection({alias: raw}) assert mapping == {raw: alias} assert projected in mapping.values() and (alias, projected) in mapping.items() + for aliased_keys in ( + {raw: raw, alias: raw}, + {raw: None, alias: raw}, + {raw: raw, alias: None}, + ): + assert len(mapping) == 1 and len(aliased_keys) == 2 + assert mapping != aliased_keys and aliased_keys != mapping + same_size = projection({alias: raw, None: None}) + assert len(same_size) == len(aliased_keys) + assert same_size != {raw: raw, alias: None} assert not raw.is_released() and not alias.is_released() assert handler.calls == 0 alias.release() diff --git a/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs b/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs index 27602291..0ba92ae1 100644 --- a/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs +++ b/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs @@ -1287,12 +1287,28 @@ with RoApartment(): stringable = uri.as_interface(IStringable) assert uri.equals(other_uri) assert uri._obj.identity_raw() != other_uri._obj.identity_raw() + single_key = IMap_Object_Object.create({uri: uri}) + for mapping in (single_key, single_key.get_view()): + single_alias = {stringable: uri} + assert len(mapping) == 1 + assert mapping == single_alias and single_alias == mapping + for aliased_keys in ( + {uri: uri, stringable: uri}, + {uri: other_uri, stringable: uri}, + {uri: uri, stringable: other_uri}, + {uri._obj: uri, stringable._obj: uri}, + ): + assert len(aliased_keys) == 2 + assert mapping != aliased_keys and aliased_keys != mapping + assert mapping[uri].identity_raw() == uri._obj.identity_raw() object_keys = IMap_Object_Object.create({uri: uri, None: None}) for mapping in (object_keys, object_keys.get_view()): assert mapping == {stringable: uri._obj, None: None} assert mapping == mapping and mapping != {other_uri: uri, None: None} assert uri in mapping and stringable in mapping assert (stringable, uri) in mapping.items() + assert mapping != {uri: uri, stringable: None} + assert {uri: uri, stringable: None} != mapping box = to_winrt_object(1) properties = PropertySet() properties["uri"] = uri From b3c115b6a35bb495c129c08b8ac780ace500cbec Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Sat, 10 Oct 2026 00:42:03 +0800 Subject: [PATCH 3/3] Update Python sequence containment snapshot Keep the Uri dependency golden aligned with the concrete sequence containment declaration, including WwwFormUrlDecoder's class, protocol, and embedded read-only view. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: ed3ecfbc-fdc5-473b-aa81-2a6721f7b7b6 --- .../tests/snapshots/uri_pyi/www_form_url_decoder.pyi | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/www_form_url_decoder.pyi b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/www_form_url_decoder.pyi index cab1e75a..c97e2123 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/www_form_url_decoder.pyi +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/www_form_url_decoder.pyi @@ -33,6 +33,7 @@ class WwwFormUrlDecoderLike(_WwwFormUrlDecoderIdentity, Protocol): def _obj(self) -> DynWinRTValue: ... def __len__(self) -> int: ... + def __contains__(self, value: object) -> bool: ... @overload def __getitem__(self, index: int) -> IWwwFormUrlDecoderEntry | None: ... @overload @@ -59,6 +60,7 @@ class WwwFormUrlDecoder(_WwwFormUrlDecoderIdentity, Sequence[IWwwFormUrlDecoderE def _obj(self) -> DynWinRTValue: ... def __len__(self) -> int: ... + def __contains__(self, value: object) -> bool: ... @overload def __getitem__(self, index: int) -> IWwwFormUrlDecoderEntry | None: ... @overload @@ -89,6 +91,7 @@ class IVectorView_IWwwFormUrlDecoderEntry(Sequence[IWwwFormUrlDecoderEntry | Non def _obj(self) -> DynWinRTValue: ... def __len__(self) -> int: ... + def __contains__(self, value: object) -> bool: ... @overload def __getitem__(self, index: int) -> IWwwFormUrlDecoderEntry | None: ... @overload