Skip to content

python: generate the type stubs from the built module - #959

Merged
finger563 merged 4 commits into
mainfrom
python/stubs-check
Dec 1, 2026
Merged

finger563 merged 4 commits into
mainfrom
python/stubs-check

Conversation

@finger563

Copy link
Copy Markdown
Contributor

Summary

The type stub the wheel ships (espp/__init__.pyi) came from litgen's view of the headers. It failed mypy outright (about 315 problems), so mypy's stubtest couldn't run against it. It also left out everything bound by hand: rtps, socket_reactor, odrive_native, dispatcher, wdi and stream_frame.

This PR generates the stubs from the built module instead, using pybind11-stubgen. They now describe what Python really gets, including real inheritance, defaults and overloads. CI checks that they match the module, pass mypy and pass stubtest.

Stub layout

File Contents
espp/__init__.pyi the package's re-exports
espp/_espp/__init__.pyi the compiled module
espp/_espp/wdi.pyi, espp/_espp/stream_frame.pyi its submodules
  • Generator: lib/generate_stubs.py, with its tools pinned in lib/stubs-requirements.txt (pybind11 3.1.0, pybind11-stubgen 3.0.0, mypy 2.4.1).
  • litgen now writes only pybind_espp.cpp.
  • Fix-ups: the generator fixes what the module can't describe (see _FIXES), and fails if a fix stops matching anything:
    • object default values;
    • Rgb and Hsv naming each other;
    • the std::mutex task callback and std::thread::id;
    • | None on callbacks that default to None;
    • typeshed-style __hash__ and narrow == / !=;
    • wdi.HostUuid.bytes() hiding the builtin bytes.
  • The pure-Python modules (espp.rtps, espp.persistent_data) keep their inline annotations and get no stub.

Binding changes (so signatures name Python types in help() too)

  • Header order: each header is now bound before the types its signatures use:
    • logger first;
    • vector2d before bezier;
    • task before socket and event_manager;
    • rtp_packet, rtp_jpeg_packet, jpeg_header and jpeg_frame before the depacketizers.
  • FtpServer(ip, port, root): it couldn't be constructed from Python at all, because std::filesystem::path had no caster. pybind11/stl/filesystem.h now makes root accept a str or os.PathLike.
  • No longer bound (no Python call could use them):
    • Socket::Info's raw sockaddr helpers (from_sockaddr, ipv4_ptr, ipv6_ptr);
    • color_code, which returns an fmt::text_style;
    • Vector2d's operator==, which added an unreachable second __eq__ next to the one litgen derives from operator<=>.
  • persistent_data.py: VersionList's classes are typed Any, and decode() / PersistentData() are typed to accept a VersionList, which they already did at run time.

A finding, not changed here: litgen binds __eq__ as a plain method, so Vector2d_int(1, 2) == "x" raises TypeError instead of returning False. It already did on main. The stubs type it accurately (narrow argument, # type: ignore[override]).

CI

The new stubs job in python_bindings.yml:

  1. builds the module with the pinned pybind11;
  2. checks the committed stubs match (generate_stubs.py --check);
  3. runs mypy on the package;
  4. runs stubtest on espp._espp, with allowlist lib/stubtest_allowlist.txt. The allowlist covers non-constructible classes' __init__, stubgen's __all__, and pybind11's ABI marker. The per-class "metaclass differs" note is filtered out.

The build adds roughly 10 minutes, as agreed in the plan.

There's also a new test, python/typing_api_test.py, in the wheel test command. It checks that:

  • the wheel ships the stubs;
  • they cover every exported name;
  • no new C++ names appear in runtime signatures;
  • FtpServer's root, Vector2d's comparisons and Rgb/Hsv conversion work.

Test plan

  • The pinned litgen reproduces main's bindings before the change. After it, the binding set differs only by the four exclusions.
  • Local dry run of the CI steps (macOS, Python 3.13): generate_stubs.py --check reports "4 stubs match the built module", mypy -p espp --follow-imports=silent passes, and stubtest reports nothing but the 132 metaclass notes.
  • All 12 wheel test scripts pass against the rebuilt module, plus typing_api_test.py.
  • CI: the stubs job on Linux. The stubs were generated on macOS, so this confirms they're platform-independent.
  • CI: the wheel builds run typing_api_test.py, confirming the wheels include espp/_espp/*.pyi.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU

The shipped espp/__init__.pyi came from litgen's view of the headers: it
failed mypy outright (~315 problems), so stubtest could not run, and it
left out everything bound by hand (rtps, socket_reactor, odrive_native,
dispatcher, wdi, stream_frame).

The stubs are now generated from the BUILT espp._espp by pybind11-stubgen
(lib/generate_stubs.py, tools pinned in lib/stubs-requirements.txt):
espp/__init__.pyi re-exports, espp/_espp/__init__.pyi, wdi.pyi and
stream_frame.pyi describe the module. litgen writes only pybind_espp.cpp.
The generator fixes up what the module cannot describe (object defaults,
Rgb / Hsv naming each other, the std::mutex task callback, std::thread::id,
None defaults of callbacks, narrow == / !=, wdi's bytes() method) and fails
when a fix stops matching.

So that signatures name python types (help() too, not just the stubs):
- headers are bound before the types their signatures use (logger first;
  vector2d before bezier; task before socket and event_manager; rtp_packet,
  rtp_jpeg_packet, jpeg_header and jpeg_frame before the depacketizers);
- std::filesystem::path gets pybind11's caster: FtpServer(ip, port, root)
  could not be constructed from python at all, it now takes a str or
  os.PathLike;
- functions no python call can use are no longer bound: Socket::Info's
  raw sockaddr helpers and color_code (fmt::text_style), and Vector2d's
  operator==, a second __eq__ next to the one derived from operator<=>.

persistent_data.py: VersionList's classes are typed Any (they have
migrate()), and decode() / PersistentData() accept a VersionList, as they
already did at run time.

CI (python_bindings.yml, new "stubs" job): builds the module, checks the
committed stubs match, runs mypy on the package and stubtest on
espp._espp (allowlist lib/stubtest_allowlist.txt; the per-class
"metaclass differs" note is filtered). python/typing_api_test.py, in the
wheel test command, checks the wheel ships the stubs, they cover every
exported name, no new C++ names appear in signatures, and the changed
bindings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU
Copilot AI balanced review requested due to automatic review settings December 1, 2026 04:05
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

✅Static analysis result - no issues found! ✅

Comment thread python/typing_api_test.py Fixed
Comment thread python/typing_api_test.py Fixed
Comment thread lib/generate_stubs.py Fixed
Comment thread python/typing_api_test.py Fixed
Comment thread python/typing_api_test.py Fixed
The module builds against external/ (fmt, cli, ...).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU

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.

🟡 Changes recommended

The CI checkout omits required submodules, causing fresh-runner builds to fail, while unresolved typing errors and validation gaps further undermine the stub checks.

5 open issues
What changed in this PR

This PR switches ESPP’s Python type-stub generation from parsed headers to the built extension, covering hand-written bindings and aligning annotations with the exposed Python API.

Changes:

  • Adds a pinned stub generator with targeted annotation fixes.
  • Reorders bindings, enables filesystem-path conversion, and removes unusable or duplicate bindings.
  • Adds CI checks for stub consistency and typing, plus wheel-level API checks.
File Description
python/​typing_api_test.py Checks shipped stubs, exported names, signatures, and binding behavior.
python/​README.md Documents the new typing API test.
pyproject.toml Adds the typing test to wheel validation.
lib/​stubtest_allowlist.txt Records expected stubtest exceptions.
lib/​stubs-requirements.txt Pins stub-generation and validation tools.
lib/​README.md Documents the revised generation workflow.
lib/​python_bindings/​pybind_espp.cpp Regenerates reordered bindings and adds filesystem conversion.
lib/​python_bindings/​espp/​persistent_data.py Aligns annotations with supported version-list inputs.
lib/​python_bindings/​espp/​_espp/​wdi.pyi Adds generated WDI submodule types.
lib/​python_bindings/​espp/​_espp/​stream_frame.pyi Adds generated frame-codec types.
lib/​generate_stubs.py Generates, adjusts, and compares runtime-derived stubs.
lib/​autogenerate_bindings.py Limits litgen output to C++ bindings and adjusts binding order.
.github/​workflows/​python_bindings.yml Adds extension builds, stub comparison, mypy, and stubtest checks.

Review effort: Balanced

Comment thread .github/workflows/python_bindings.yml Resolved
Comment thread .github/workflows/python_bindings.yml Resolved
Comment thread lib/generate_stubs.py Resolved
Comment thread lib/generate_stubs.py Resolved
Comment thread python/typing_api_test.py Resolved
… stricter checks

From review:
- std::function members (Task / Timer / socket configs, ...) read back None
  while empty and take None: their property getters and setters say so;
- stream_frame's binary std::string parameters (StreamParser.feed,
  build_frame's payload, crc32, the Frame.payload setter) and
  Dispatcher.feed take str | bytes, so build_frame() -> feed() type-checks;
- the stubtest step fails on any exit status other than 0 / 1, and on 1
  with nothing reported (a crash during import), instead of discarding it;
- typing_api_test checks the exported names against espp's public runtime
  names (espp has no __all__, so the check never ran), tests what the two
  new fixes rely on at run time, and compares distinct equal vectors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU
Comment thread python/typing_api_test.py Fixed
Comment thread python/typing_api_test.py Fixed
Code scanning read the combined line as arithmetic (b < a "always false"
once a < b); each bound operator now has its own check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU
@finger563
finger563 merged commit a48a00b into main Dec 1, 2026
30 of 33 checks passed
@finger563
finger563 deleted the python/stubs-check branch December 1, 2026 16:16
finger563 added a commit that referenced this pull request Dec 1, 2026
…k writer (#963)

## Summary

`typed_action_alignment` kept failing on the Jazzy interop runner after #939, in the same way. The first goal succeeds, but its one feedback sample never arrives:

```
succeed: status 4, result {1.5, 7, 2.5}, feedback {-1, -1}
FAIL: the feedback's int32 and double arrived intact (line 199)
```

(run 46583796982, on #959, which only touched the Python bindings).

### Root cause

#939 made the test wait until the **server's** feedback writer has matched the client's reader. The other half of the match was still open: the **client's** feedback reader may not have matched the server's writer when the sample arrives, and a reader drops samples from a writer it doesn't know yet. The goal finishes in milliseconds, so that one sample was the only chance.

`ActionClient::wait_for_server()` waited for the three services only. `rcl_action_server_is_available()`, which rclcpp_action's `wait_for_action_server()` polls, also requires a publisher matched to the client's feedback subscription.

### Change

- **Engine:** `ActionClient::server_count()`, and so `wait_for_server()`, now also counts the writers matched to the client's feedback reader. espp's action client has no status subscription, so feedback is the one topic to add.
- **Test:** asserts `client.matched_writers(feedback_topic) >= 1` after `wait_for_server()`. It keeps #939's server-side wait, because a volatile writer only sends to readers it has matched. Nothing on the client side can observe that, and rclcpp has the same window.
- **Docs:** the header and the Python docstring are updated, and the regenerated stub differs from main by that one docstring line (`generate_stubs.py --check` passes). `rtps_rmi_ami.rst` gets a short note too.

## Test plan

- [x] `typed_action_alignment` locally (macOS, Release, as `run_interop.sh` builds it). The race doesn't reproduce here: before the fix, 0 of 100 runs idle and 0 of 200 under CPU load (2 × ncpu spinners) failed. After the fix, 0 of 200 failed. CI's Jazzy interop is where it showed up, roughly once in several runs.
- [x] The other action and RPC pc tests pass: `rtps_action_*` (cancel codes, goal flood, long goal, loopback, naming, types, worker pool) and `rtps_rpc_*` (empty reply, pending eviction, stop race).
- [x] The Python tests that use the action client pass: `rtps_bindings_smoke`, `rtps_bindings_misuse_test`, `rtps_rpc_timeouts_test`, `rtps_task_configs_test`, `typing_api_test`.
- [ ] CI: interop (Humble / Jazzy), QEMU.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU
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