Skip to content

Fix Python consumer instance and input typing - #171

Merged
leileizhang (lei9444) merged 5 commits into
mainfrom
lei9444-python-consumer-typing
Sep 20, 2026
Merged

leileizhang (lei9444) merged 5 commits into
mainfrom
lei9444-python-consumer-typing

Conversation

@lei9444

@lei9444 leileizhang (lei9444) commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fix the Python consumer typing contracts behind four release-audit cases, the related collection-subscript input omission, and subclass-preserving interface factories without changing native dispatch, public runtime APIs, canonical interface identities, or JavaScript output. This is an independent change based on 34eb6246627c671113a501c00edc8e3317fc8b3d; it does not include the JS native-wrapper or GDI/USER32 work.

  • Separate interface instance protocols from class-level projection factories. from_value and IBuffer.from_bytes remain available on the interface class through its stub metaclass. _DynWinRTProjector describes the already-bound factory method, preserving typed as_interface(...) calls without requiring runtime-class instances to expose an unrelated factory. Inherited from_value retains the actual receiving subclass instead of returning a fixed base-interface type.
  • Give Object inputs a precise native-wrapper protocol (_obj: DynWinRTValue) alongside raw DynWinRTValue. Apply the input contract to methods, setters, arrays, and collection inputs; keep outputs as DynWinRTValue | None. Generated runtime annotation support uses the same protocol definition. Arbitrary Python objects, unboxed strings, invalid _obj values, unrelated interfaces/classes, and class objects remain rejected. Ordinary Object parameters do not implicitly box None; collection dunders retain their existing nullable ABC signatures, not a new runtime conversion.
  • Return Self from generated context managers so base Like protocols accept derived wrappers and preserve the entered type. Closing and Literal[False] exception behavior are unchanged.
  • Use input types rather than read-result types for collection keys and mutations, including PropertySet/IMap subscript assignment and vector item assignment, slice assignment, and insert. Read/iteration outputs remain unchanged. Integer assignment takes one item; slice assignment takes an iterable of items.

The Button.content contract was already narrow before its consumer rejection became exposed; this fixes that typing mismatch with the existing working marshaling, not a newly changed native setter. No Any, casts, ignore comments, legacy marker fallbacks, or handwritten generated stubs were added. Affected Python snapshots were regenerated through the existing snapshot update mechanism.

Consumer evidence

Generated before/after from the same pinned inputs. The actual sample sources were copied unchanged into isolated generated packages. Every check explicitly includes the generated package with mypy --strict --no-incremental --follow-imports=normal; no imported-library errors are suppressed.

Original consumer Before: main errors After: source stubs After: installed wheel stubs Files checked per run
Async file I/O: StorageFile into IStorageFile 3 0 0 327
Text-to-speech: stream into IRandomAccessStream 1 0 0 2,501
WinUI code-only Tic-Tac-Toe: TextBlock into Button.content 2 0 0 2,471
Composition: ContainerVisual into set_reference_parameter 1 0 0 505

The original 22-seed closure remains clean after both follow-ups: 2,631 stubs, strict mypy zero errors with both source and installed stubs. The earlier audit also compiled all 2,629 generated Python implementations. Inputs are Windows SDK 10.0.26100.0 (Windows.winmd SHA256 11191cbcc796e520d47547b3f986be94a48556fe336d4e63334596d9f31a7806), WinUI 2.3.0, and InteractiveExperiences 2.1.3, using the same six hash-verified WinMD files as the audit. No SDK restore/download was performed.

Collection input follow-up

Commit 17d94036 addresses the confirmed existing declaration omission: properties["uri"] = uri and mapping["uri"] = uri already work at runtime, but their stubs reused the narrower read-result type. The shared collection declaration helper now uses a separate input annotation for subscript keys, mutation values, and vector insertion. This covers concrete classes, Like protocols, standalone interfaces, and embedded interfaces while preserving the existing nullable collections.abc contract. Native nulls still use DynWinRTValue.null_value(); no implicit None boxing or runtime behavior was added.

The actual SDK regression reproduces four rejected Uri assignments across PropertySet/Like/standalone-map/embedded-map before the fix, then passes strict mypy with source and installed stubs. Additional synthetic consumers cover Object keys, independently generated derived wrappers, vector scalar/slice assignment, insertion, append, exact unchanged read types, and rejected wrong identities/input shapes. The independent PropertySet/IMap native control checks wrapper/raw/null-carrier round trips and requires both its success marker and a successful process exit.

A separately reported Python probe that printed its completion marker before exiting with 0xC0000005 remains unattributed and paused pending its original script. These declaration-only follow-ups do not change the runtime or claim that the normal controls resolve that report.

Subclass factory P2

Commit 5fc91889 separately fixes the P2 that was not addressed by 17d94036: the metaclass from_value declaration returned a fixed interface name. Its signature now binds the existing type variable to the receiving class: from_value(cls: type[_InterfaceT], obj: DynWinRTValue) -> _InterfaceT. Factories remain outside instance Protocols; no descriptor, Any, cast, or new runtime API is needed.

The real SDK IBuffer regression reproduces eight errors before this fix and passes after it with both source and installed runtime stubs. It checks base interfaces, TaggedBuffer, a second-level subclass, type[TaggedBuffer] factory variables, _DynWinRTProjector[TaggedBuffer], and as_interface(TaggedBuffer). Six negative cases reject wrong inputs and attempts to treat a base/static-factory result as a subclass. TaggedBuffer.from_bytes(...) intentionally still returns IBuffer, matching the existing static factory. Native checks verify exact subclass types, inherited members, cached identities, and a successful process exit. All 2,629 generated Python runtime files are byte-identical before/after this P2 fix; only declarations changed.

Validation

On native Windows ARM64, Python 3.13.15 and mypy 1.20.2, with this checkout's generator and an offline/locked-built matching wheel installed locally with --no-index:

  • Complete codegen suite after the subclass fix: 902 passed, 0 failed, 1 existing ignored, 0 filtered, across 43 test-suite results, using cargo test -p dynwinrt-codegen --offline --locked --no-fail-fast -- --nocapture --test-threads=2. DYNWINRT_REQUIRE_MYPY, DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME, DYNWINRT_REQUIRE_TSC, DYNWINRT_REQUIRE_WIN32_METADATA, and DYNWINRT_TEST_INSTALLED_RUNTIME were all enabled. No missing-dependency skip messages. The ignored test is the existing opt-in metadata review-artifact exporter.
  • This includes all Unify Python projection symbol naming #165 symbol-mapping and Fix Python closed generic interface identity markers #167 canonical-marker regressions, all five source/installed-stub and native consumer tests, all 14 cross-language implementation-naming tests, and JS/Python snapshots. Earlier selected integration/snapshot and unit-check evidence is retained separately.
  • Before the collection/subclass follow-ups, 10 related tests passed under the coverage build profile: observable vectors, collection factories, property-name collisions, and write-only properties. Earlier IBuffer/composable-factory and wheel typing-package checks also passed. Formatting and patch whitespace checks passed.
  • Durable strict positive/negative consumers cover same-package and independently generated identities, exact factory/result types, native Object inputs, base/derived context managers, and 32 negative controls across synthetic, collection, and subclass-factory consumers. DYNWINRT_TEST_INSTALLED_RUNTIME=1 runs the consumer checks with both source and installed runtime stubs.
  • Generated synthetic native controls passed for wrapper/raw/null Object marshaling, arrays, factory and as_interface calls, runtime type-hint resolution, exact context-manager identity, exception propagation, close counts, and rejected invalid Object inputs.
  • The actual async-file sample completed its 48-character native round trip. Text-to-speech completed synthesis only (audio/wav, 91,566 bytes); no playback.
  • All 362 generated JS package files for Uri, DataWriter, and HttpClient were byte-identical in the original before/after audit; the collection/subclass follow-ups change Python declarations/tests/documentation only.

Environment provenance and limits: initial full-suite attempts were blocked by missing local JS build artifacts; that limitation is retained in the original evidence, not confused with the remote assertion failures below. For the complete codegen runs, JS validation dependencies were restored with npm ci --offline --ignore-scripts, and the 18-file ARM64 production artifact built from 34eb624 was copied read-only into this worktree's ignored dist. Every copied file was hash-verified; native binary SHA256 is 75d16e0c9facfdd36ab3b9f3a15562940e3e4b9df47bd79ddc97b6166abdcf45. JS/core sources and Cargo manifests/lockfile have no differences from that artifact's source commit. TypeScript is 5.9.3; Win32Metadata is the hash-verified cached 71.0.14-preview input. This is a production artifact, not test-hooks. The complete mixed-language coverage pipeline and full two-language E2E were not run locally; a coverage-profile test run is not a coverage-pipeline success. No local WinUI startup, audio playback, notification/auth flow, or non-ARM64 execution is claimed.

CI follow-up

The first two remote CI attempts exposed two missed legacy test assertions; both test-rust and coverage stopped on the same assertion in each attempt. They were real test regressions, not the local JS environment limitation:

  • 1813cddf updates the observable-vector factory assertion to check the exact native-wrapper input union in both .py and .pyi, the existing unwrap operation, and unchanged nullable raw-value outputs.
  • 90146b54 replaces a brittle total-property-decorator count (2, now 3 because of _obj) with individual checks of qualified decorators, nullable Object output types, and the non-null native _obj capability. It does not merely increase the count.

Those two follow-ups are test-only. No production logic, coverage threshold, exclusion, or negative-input control was weakened. Before/failure and after/pass logs are retained. The subsequent coverage warning about unexecuted JS binding source followed the early Rust-test failure; no coverage rule was changed to mask it. Consult the checks tab for the latest commit's remote result rather than treating local success as remote success.

Migration

Regenerate complete Python packages with this generator and use/reinstall the matching runtime package and stubs. Do not patch individual .pyi files. The #167 full-regeneration migration for packages exchanging closed generic protocols remains intact, including canonical markers and the absence of legacy compatibility fallbacks. No consumer casts or runtime API changes are required.

Separate interface instance protocols from wrapper factories, model native Object inputs without widening outputs, and use Self for context-manager covariance. Add strict same-package, independent-package, SDK, and native lifetime regressions.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@github-actions

github-actions Bot commented Sep 20, 2026 •

Copy link
Copy Markdown

Mixed-language test coverage

Workflow status: ✅ Passed

Layer Lines Functions Branches/regions
Rust, including native .pyd/.node 86.26% 81.26% 85.89% regions
Python aggregate 71.06% n/a 37.9% branches
Python runtime 99.12% n/a 97.37% branches
Generated Python WinRT projections 70.05% n/a 27.07% branches
Generated Python WinRT implementations 72.3% n/a 47.04% branches
JavaScript aggregate 22.14% 25.22% 57.85% branches
JavaScript runtime 44.27% 45.76% 78.99% branches
Generated WinRT projections 22.96% 18.72% 54.88% branches
Generated WinRT implementations 48.66% 59.76% 61.14% branches
Generated Classic COM projections 11.92% 23.97% 54.2% branches

View workflow run and download full HTML/LCOV/XML reports

Update the stale factory expectation shared by test-rust and coverage. Assert matching generated Python implementation and stub input types, native-wrapper unwrapping, and unchanged nullable raw-value outputs.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Cover qualified decorators and unchanged nullable Object outputs individually, including the native wrapper's read-only _obj property. Avoid a brittle total that changed with the added input protocol capability.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Use projected input contracts for collection keys and mutation values while preserving raw nullable outputs and existing ABC contracts. Distinguish scalar and slice assignment, and cover PropertySet, generated maps, typed vectors, independent identities, invalid inputs, and native null carriers.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Bind metaclass from_value to its receiving interface class through the existing TypeVar instead of fixing its return to the base interface. Keep factories outside instance protocols and preserve independent static factory results. Add exact subclass, projector, wrong-input, and native identity regressions.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@lei9444
leileizhang (lei9444) merged commit 226cb99 into main Sep 20, 2026
33 of 34 checks passed
@lei9444
leileizhang (lei9444) deleted the lei9444-python-consumer-typing branch September 20, 2026 08:56
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.

2 participants