Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions bindings/py/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ Generated package manifests pin `dynwinrt` to the exact version of
Do not mix generated bindings with an older runtime wheel. Upgrade to the
matching runtime version and regenerate all Python bindings together; generated
interface overloads fail explicitly when a required native guard is missing.
Generated Python packages record the full producer version separately.
Upgrades, downgrades, and legacy unstamped output require manually cleaning
the dedicated codegen output and regenerating the complete bindings selection;
incompatible generation fails without changing existing output.
See the [producer-version and path contracts](../../tools/dynwinrt-codegen/python/README.md#producer-version-and-regeneration).

Generated `IReference<T>` values are projected as `T | None`; native values,
`None`, and generated `IReference_*` wrappers are accepted as inputs.
Expand Down
61 changes: 54 additions & 7 deletions eng/release/python/test_generated_python_long_paths.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ if ($root.Length -ne 104) {
}
$source = Join-Path $root "source\generated_bindings"
$wheelDirectory = Join-Path $root "wheels"
$install = Join-Path $root "installed"
$sourceInstall = Join-Path $root "from-source"
$install = Join-Path $root ("i" * (135 - $root.Length - 1))

try {
Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue
Expand All @@ -33,9 +34,17 @@ try {
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

$modules = Get-ChildItem -LiteralPath $source -File -Filter *.py
$tooLong = $modules | Where-Object { $_.BaseName.Length -gt 120 }
$tooLong = $modules | Where-Object { $_.BaseName.Length -gt 56 }
if ($tooLong) {
throw "Generated Python module exceeds 120 characters: $($tooLong[0].Name)"
throw "Generated Python module exceeds 56 UTF-16 code units: $($tooLong[0].Name)"
}
$tooLong = Get-ChildItem -LiteralPath $source -File -Recurse |
Where-Object {
$_.Extension -in @(".py", ".pyi") -and
$_.FullName.Substring($source.Length + 1).Length -gt 60
}
if ($tooLong) {
throw "Generated Python relative source path exceeds 60 UTF-16 code units: $($tooLong[0].Name)"
}
if (-not ($modules | Where-Object { $_.BaseName -match "_[0-9a-f]{16}$" })) {
throw "Long-path fixture did not generate a hashed Python module"
Expand All @@ -55,7 +64,7 @@ try {

$buildBaseMatch = Select-String `
-LiteralPath (Join-Path $source "setup.cfg") `
-Pattern "^build-base\s*=\s*(.+)$"
-Pattern "^build_base\s*=\s*(.+)$"
if (-not $buildBaseMatch) {
throw "Generated setup.cfg does not define a scoped build cache"
}
Expand Down Expand Up @@ -112,7 +121,7 @@ try {
}
$newBuildBaseMatch = Select-String `
-LiteralPath (Join-Path $source "setup.cfg") `
-Pattern "^build-base\s*=\s*(.+)$"
-Pattern "^build_base\s*=\s*(.+)$"
$newBuildBase = $newBuildBaseMatch.Matches[0].Groups[1].Value.Trim()
if ($newBuildBase -eq $initialBuildBase) {
throw "Generated file layout change did not rotate the scoped build cache"
Expand Down Expand Up @@ -145,7 +154,7 @@ try {
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$renamedBuildBaseMatch = Select-String `
-LiteralPath (Join-Path $source "setup.cfg") `
-Pattern "^build-base\s*=\s*(.+)$"
-Pattern "^build_base\s*=\s*(.+)$"
$renamedBuildBase = $renamedBuildBaseMatch.Matches[0].Groups[1].Value.Trim()
if ($renamedBuildBase -eq $preRenameBuildBase) {
throw "Output package rename did not rotate the scoped build cache"
Expand All @@ -154,6 +163,15 @@ try {
throw "Output package rename deleted the old build cache"
}

& $Python -m pip install $source --no-deps --target $sourceInstall
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& $Python (Join-Path $PSScriptRoot "verify_generated_python_install.py") `
--source $source `
--install $sourceInstall `
--package renamed_bindings `
--check-uri
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

& $Python -m pip wheel $source --no-deps --wheel-dir $wheelDirectory
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$wheel = Get-ChildItem -LiteralPath $wheelDirectory -Filter *.whl -File |
Expand All @@ -165,11 +183,40 @@ try {
& $Python (Join-Path $PSScriptRoot "verify_generated_python_install.py") `
--source $source `
--install $install `
--package renamed_bindings
--package renamed_bindings `
--check-uri
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& $Python -m compileall -q -o 0 -o 1 -o 2 (Join-Path $install "renamed_bindings")
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$tooLong = Get-ChildItem -LiteralPath (Join-Path $install "renamed_bindings") -File -Recurse |
Where-Object { $_.FullName.Length -gt 259 }
if ($tooLong) {
throw "Installed Python source/stub/cache exceeds 259 UTF-16 code units: $($tooLong[0].FullName)"
}
if (Test-Path -LiteralPath (Join-Path $install "generated_bindings")) {
throw "Renamed wheel retained the old generated_bindings package"
}

$untypedSource = Join-Path $root "untyped_bindings"
$untypedWheels = Join-Path $root "untyped-wheels"
& $Codegen generate `
--class-name Windows.Foundation.Uri,Windows.Devices.Enumeration.DeviceInformationCustomPairing `
--lang py --no-pyi --output $untypedSource
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& $Python -m pip wheel $untypedSource --no-deps --wheel-dir $untypedWheels
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$untypedWheel = Get-ChildItem -LiteralPath $untypedWheels -Filter *.whl -File |
Select-Object -First 1
if (-not $untypedWheel) { throw "Untyped generated bindings wheel was not created" }
& $Python -m pip install $untypedWheel.FullName --no-deps --target $install
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& $Python (Join-Path $PSScriptRoot "verify_generated_python_install.py") `
--source $untypedSource --install $install --package untyped_bindings --check-uri
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
if ((Get-ChildItem (Join-Path $install "untyped_bindings") -Filter *.pyi -File -Recurse) -or
(Test-Path (Join-Path $install "untyped_bindings\py.typed"))) {
throw "Untyped wheel retained stubs or a py.typed marker"
}
} finally {
Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue
}
80 changes: 80 additions & 0 deletions eng/release/python/verify_generated_python_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@

import argparse
import importlib
import os
import subprocess
import sys
import sysconfig
import tempfile
from pathlib import Path


Expand Down Expand Up @@ -40,11 +44,73 @@ def module_name(package: str, relative: Path) -> str:
return ".".join((package, *parts))


def check_uri_typing(package: str, install: Path, typed: bool) -> None:
environment = dict(os.environ)
environment.pop("MYPYPATH", None)
if install not in {
Path(sysconfig.get_path(name)).resolve() for name in ("purelib", "platlib")
}:
environment["MYPYPATH"] = str(install)
with tempfile.TemporaryDirectory(prefix="dtype-") as temporary:
directory = Path(temporary)
module = "windows.foundation" if typed else "windows__foundation__uri"
imports = f"from {package}.{module} import Uri\n"
result_type = "Uri" if typed else "Uri | None"
valid = (
imports
+ f"def consume(uri: Uri) -> {result_type}:\n"
+ " host: str = uri.host\n"
+ " return uri.combine_uri('sub/page')\n"
)
if typed:
valid += (
f"from {package}.windows.foundation.uri import Uri as PerTypeUri\n"
f"from {package}.windows__foundation__uri import Uri as FlatUri\n"
"uri: Uri = PerTypeUri('https://example.com')\n"
"other: Uri = FlatUri('https://example.com')\n"
)
invalid = (
imports
+ f"def reject(uri: Uri) -> {result_type}:\n"
+ " return uri.combine_uri(123)\n"
)
for name, source in [("valid", valid), ("invalid", invalid)]:
consumer = directory / f"{name}.py"
consumer.write_text(source, encoding="utf-8")
command = [
sys.executable,
"-m",
"mypy",
"--strict",
"--no-incremental",
"--no-pretty",
"--show-error-codes",
"--cache-dir",
str(directory / "m"),
str(consumer),
]
if not typed:
command.extend(["--follow-untyped-imports", "--follow-imports=silent"])
result = subprocess.run(
command,
capture_output=True,
text=True,
env=environment,
)
errors = [line for line in result.stdout.splitlines() if ": error:" in line]
expected = 0 if name == "valid" else 1
if result.returncode != expected or len(errors) != expected:
raise RuntimeError(result.stdout + result.stderr)
if name == "invalid" and not errors[0].endswith("[arg-type]"):
raise RuntimeError(result.stdout + result.stderr)


def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--source", type=Path, required=True)
parser.add_argument("--install", type=Path, required=True)
parser.add_argument("--package", required=True)
parser.add_argument("--check-uri", action="store_true")
args = parser.parse_args()

source = args.source.resolve()
Expand All @@ -71,6 +137,20 @@ def main() -> None:
}
for name in sorted(modules):
importlib.import_module(name)
if args.check_uri:
from dynwinrt import RoApartment

namespace = importlib.import_module(f"{args.package}.windows.foundation")
per_type = importlib.import_module(f"{args.package}.windows.foundation.uri")
flat = importlib.import_module(f"{args.package}.windows__foundation__uri")
assert namespace.Uri is per_type.Uri is flat.Uri
with RoApartment():
uri = namespace.Uri("https://example.com/compact-paths")
assert uri.host == "example.com"
assert uri._obj.is_released()
check_uri_typing(
args.package, args.install.resolve(), (installed / "py.typed").exists()
)
print(f"verified {len(expected)} files and imported {len(modules)} modules")


Expand Down
24 changes: 9 additions & 15 deletions tests/e2e/runners/py_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -2970,10 +2970,8 @@ async def read_all(stream):
)

formatter_module = importlib.import_module(
implementation_module_name(
pkg_name,
'Windows.Globalization.NumberFormatting',
'DecimalFormatter',
namespace_module_name(
pkg_name, 'Windows.Globalization.NumberFormatting'
)
)
interface_values = []
Expand Down Expand Up @@ -3761,13 +3759,12 @@ def observe_value(sender, args):
elif kind == 'nested_struct_runtime':
from typing import get_type_hints

module = importlib.import_module(
implementation_module_name(
pkg_name, namespace, 'Direct3DSurfaceDescription'
)
namespace_module = importlib.import_module(
namespace_module_name(pkg_name, namespace)
)
descriptor_type = getattr(module, 'Direct3DSurfaceDescription')
nested_type = getattr(module, 'Direct3DMultisampleDescription')
descriptor_type = getattr(namespace_module, 'Direct3DSurfaceDescription')
nested_type = getattr(namespace_module, 'Direct3DMultisampleDescription')
module = importlib.import_module(descriptor_type.__module__)
pixel_format = generated_type(pkg_name, 'DirectXPixelFormat')
pack = getattr(module, 'pack_direct3_d_surface_description')
unpack = getattr(module, 'unpack_direct3_d_surface_description')
Expand All @@ -3776,6 +3773,7 @@ def observe_value(sender, args):
globalns={
**vars(module),
'DirectXPixelFormat': pixel_format,
'Direct3DMultisampleDescription': nested_type,
},
)
if (
Expand Down Expand Up @@ -3837,11 +3835,7 @@ def observe_value(sender, args):
'TypedEventHandler_IMemoryBufferReference_Object'
)
delegate_module = importlib.import_module(
implementation_module_name(
pkg_name,
'Windows.Foundation',
delegate_name,
)
namespace_module_name(pkg_name, 'Windows.Foundation')
)
delegate_iid = getattr(
delegate_module,
Expand Down
25 changes: 16 additions & 9 deletions tools/dynwinrt-codegen/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,9 +175,20 @@ layout, ownership, or cleanup information. See the

The output directory belongs to codegen; do not store handwritten files in it.
After changing metadata files, SDK versions, or reference inputs, regenerate the
complete output. Python module components longer than 120 characters are
shortened with a stable readable prefix and hash suffix while public type names
remain unchanged.
complete output. Python module stems are selectively shortened to a 56-unit
UTF-16 relative-path budget, including namespace directories for public facades.
Public type names, namespace exports, and ordinary short module imports remain
unchanged; direct imports of shortened long modules must migrate. Compact,
layout-scoped setuptools build and wheel staging paths leave additional room
for source installation and bytecode caches.

Python output records the complete producer `generator_version` in
`.dynwinrt-generator.json`. A different version, an unstamped generated package,
or corrupt producer metadata fails before changing existing output: manually
clean the dedicated output and regenerate the entire selection, or use fresh
output. Equal versions retain incremental behavior. This includes preview
versions and downgrades, but cannot detect unversioned same-version development
changes. See the [regeneration contract](python/README.md#producer-version-and-regeneration).

That component budget does not constrain an arbitrary output root. On Windows,
Python generation warns once about final `.py`/`.pyi` paths of 260 or more
Expand All @@ -190,12 +201,8 @@ their owning interfaces through incremental renames. Python's package-level
root exports drop an interface and its helpers when its short name becomes
ambiguous, while namespace imports remain available. Python's
heterogeneous interface-pair union is generated from validated inventory
records, not inferred from `.pyi` text. The first typed incremental generation
over an older inventory needs the original WinMD/`--ref` inputs for interfaces
whose implementation records are missing. If those inputs are unavailable,
generation fails atomically and leaves the previous output usable: supply the
listed metadata and retry, or fully regenerate the package. New inventories
retain these records, and `--no-pyi` does not require this typing migration.
records, not inferred from `.pyi` text. New inventories retain these records;
older producer versions require full regeneration as described above.
After `--no-pyi`, include the earlier types when regenerating with stubs enabled
(or fully regenerate the package). A typed append fails rather than publishing
imports of missing retained declarations or dropping interfaces from the union.
Expand Down
48 changes: 43 additions & 5 deletions tools/dynwinrt-codegen/python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,28 @@ complete output. Regenerate with the updated generator to pick up these
consumer typing contracts, and use the matching runtime package and its stubs.
No runtime API change or consumer cast is required.

### Producer version and regeneration

`.dynwinrt-generator.json` records `generator_version`, the complete generator
package version, including any prerelease/preview suffix. This is a producer
stamp, not the generated distribution version, runtime dependency version, or
the type inventory's `schema_version`.

New/empty output and non-generated user content need no stamp. Existing generated
output must have a valid stamp matching the running generator exactly.
Same-version generation retains the existing incremental behavior.
A different version (including a downgrade), missing stamp on generated
artifacts, or corrupt stamp causes an unsuccessful exit **before existing output
is changed**, also in `--dry-run`. Manually clean the dedicated output directory
and regenerate the **entire bindings selection**, or use a fresh output directory;
do not remove or edit only the stamp. The generator never automatically deletes
or migrates incompatible output.

Every generator upgrade therefore requires full regeneration, followed by
rebuilding/reinstalling the affected packages with the matching runtime.
Unversioned development changes with the same package version are not detected
by this check; use fresh output for those changes too.

### Closed-generic stub migration

Python stubs now identify closed generic interfaces by their complete semantic
Expand Down Expand Up @@ -212,11 +234,26 @@ closed identity, even when their local projection names differ.
- Some APIs require their Windows component, package identity, or framework
bootstrap to be present at runtime.

Python module components longer than 120 characters are shortened with a stable
readable prefix and hash suffix while public type names remain unchanged.
Python implementation module stems use a 56 UTF-16-code-unit budget. Public
per-type module stems use the remaining budget after their namespace directories.
Only over-budget names are shortened with a readable prefix and stable hash of
the complete type identity. Public type names, namespace exports, and ordinary
short per-type and flat-module imports remain unchanged. Direct imports of
shortened long modules must migrate; no unsafe long-filename shims are emitted.

### Windows path length

The relative stem budget allows up to 60 UTF-16 code units for `.pyi` source paths
and reserves space for optimized CPython 3.11–3.14 `__pycache__` filenames and
their atomic-write temporary suffixes. For example, it fits the legacy 259-unit
limit with a 130-unit site-packages prefix and a 16-unit package name, including
a maximum-width 64-bit temporary identifier. Deep metadata namespaces may exceed this
budget even with a minimal basename; their namespace hierarchy is not flattened.
Generated `setup.cfg` also shortens the isolated setuptools build cache to
`.b/<layout-and-package-hash>` and wheel staging to `.b/<same-hash>/w`, avoiding
the extra default `bdist.<platform>/wheel` nesting. Cache isolation still tracks
the source layout and import package name.

A short module name does not guarantee a short **absolute** path. In deep
checkouts, codegen can successfully write files that ordinary Python imports,
mypy, or pip cannot open. CPython supports long paths on appropriately
Expand All @@ -234,9 +271,10 @@ shorter the output root needs to be. Relative `--output` paths are resolved
from the current directory; temporary transactional staging paths are not
counted. `--dry-run` checks the requested projection's planned source paths,
aggregating all selected namespaces into one warning; `--no-pyi` excludes
stubs. This is a **compatibility risk diagnostic**:
generation still succeeds, and module names, imports, layout, and bytes are
unchanged.
stubs. This remains a **compatibility risk diagnostic**: generation still
succeeds without a further root-dependent naming change. The deterministic
module budget and compact staging do not guarantee arbitrary checkout,
package-name, build-temporary-directory, or venv depths.

Prefer a shorter checkout such as `C:\src\dynwinrt`, or generate directly into
a short root and run consumers there:
Expand Down
Loading
Loading