Skip to content

[zigpy/ZHA] Strict typing and py.typed markers across the zigpy libraries #87

Open
0 of 1 issue completed

Description

@zigpy-review-bot

Summary

Most zigpy libraries are not type-checked in a way that catches anything today. bellows, zigpy-deconz, zigpy-xbee and zigpy-zigate set ignore_errors = true. zigpy-znp and zha-quirks turn off 12 and 14 error codes globally. Where a mypy hook exists, it is mirrors-mypy in an isolated environment (zha-quirks' has no zigpy installed, so zigpy resolves to Any there), and zigpy-deconz has had no mypy hook since its ruff migration. zigpy and zigpy-ziggurat are already checked strictly, zha with most strict flags, and zigpy ships a py.typed marker.

This issue tracks prepared branches that give every library the same setup zha and zigpy use, then fix most of the recorded errors, and finally ship py.typed:

  • Baseline: mypy runs in the project environment (so zigpy's real types are seen), with strict = true. Today's errors are recorded as autogenerated per-module overrides, by a tools/regenerate_mypy_ignores.py modelled on zha's.
  • Fixes: real type errors fixed and the overrides shrunk: all of them in zigpy-deconz and zigpy-xbee, most of them in bellows, zigpy-znp and zigpy-zigate, and the shared patterns in zha-quirks, whose bulk depends on zigpy's own typing (below).
  • Marker: a py.typed marker and its package-data entry.

Typing them surfaced real bugs, each fixed on its own branch with a test. The ZHA and Home Assistant side of the same initiative (zha's own py.typed, and HA's ZHA integration type-checking against it) is tracked in #86.

All branches below are pushed but no PRs are open yet. Each went through review rounds (an independent reviewer plus a second model) until both came back clean, and the PR texts are drafted. The zha-quirks marker and the zigpy branch in the last two rows are steps 6 and 3 of #86 and are requested from there.

Per library

Library Branches (stacked in this order) Recorded errors: baseline → after fixes Bug-fix branches
bellows on zigpy/bellows#761: typing-baseline → typing-fixes → py-typed 1,539 → 283 cli-bad-option-usage
zigpy-znp typing-baseline → typing-fixes → typing-fixes-2 → py-typed 1,535 → 79 cstruct-eq-non-struct
zigpy-deconz typing-baseline → typing-fixes → py-typed 323 → 0 uart-trailing-escape, address-endpoint-nwk-and-ieee
zigpy-xbee on zigpy/zigpy-xbee#181: typing-baseline → typing-fixes → py-typed 182 → 0 unhandled-frame-crash, serial-flow-control
zigpy-zigate on zigpy/zigpy-zigate#167: typing-baseline → typing-fixes → py-typed 340 → 109 fix-api-attribute-errors, fix-cli-tool, fix-command-status-only-return
zigpy-ziggurat py-typed (already strict) – –
zha-device-handlers typing-baseline → typing-fixes; marker separately: py-typed 4,114 → 3,706 –
zigpy backup-manager-iter (BackupManager.__iter__) see below –

Notes on the stacks:

zigpy itself

zigpy's own typing is the biggest lever left: zigpy/zigpy#1827 (draft) fixes zigpy's suppressed errors, including the cluster_id / ZCLAttributeDef typing. Measured against zha-quirks with zigpy/zigpy#1827 merged onto zigpy dev, the quirks baseline drops from 4,114 to 1,862 errors. The libraries' remaining inline type: ignore comments are mostly zigpy annotation gaps that recur across libraries:

  • ControllerApplication.connection_lost(exc: Exception): asyncio passes None on a clean close.
  • Struct.replace(**kwargs: dict[str, Any]): should be Any.
  • EUI64.UNKNOWN: set after the class body, so undeclared.
  • Channels.from_channel_list: annotates cls as an instance.
  • The type constructors (FixedIntType.__new__, the enum metaclass __call__, the ZDO deserializer): unannotated, so every uint8_t(...) is an untyped call. Most libraries exempt zigpy.types through untyped_calls_exclude.
  • NetworkInfo / NodeInfo / Key and ZigbeePacket fields typed uint8_t / NWK / PanId and the like, which reject plain ints and None (NetworkInfo.channel, ZigbeePacket.tsn, an optional ZigbeePacket.dst).
  • Endpoint.device_type, BaseDevice.zdo, ControllerApplication._tasks against HasTasksProtocol.
  • FixedList[T, n] / LVList[T, L] and StructField(...) declarations don't work as types (valid-type, misc).
  • ZCLCommandDef.schema doesn't admit dict schemas, and the cluster_id / ZCLAttributeDef typing that Fix all current mypy ignores zigpy#1827 changes.

Bugs found

Each fixed bug has its own branch and a test that fails without the fix:

  • zha: ZigbeeDevice.issue_cluster_command never passed the manufacturer code on to zigpy; see [ZHA/Core] Ship py.typed in zha and type-check Home Assistant's ZHA integration against it #86.
  • bellows: bellows config raised TypeError instead of a usage error (click.BadOptionUsage called without the option name).
  • zigpy-znp: comparing a CStruct with a plain object() (any object whose class is a base of the struct's) raised AttributeError instead of returning False.
  • zigpy-deconz:
    • a UART frame ending in an escape byte raised TypeError in data_received, and the next frame stayed in the buffer;
    • DeconzAddressEndpoint.serialize wrote the NWK address as the IEEE address for NWK_AND_IEEE, so an APS data confirm with that destination mode would raise TypeError in the payload-length check and leave its request unresolved. The library never sends that mode itself, so this needs the firmware to report it.
  • zigpy-xbee:
    • frames without a handler (route information, RX, RX I/O, extended status, node identification) raised TypeError from the UART callback;
    • since Zigpy serial protocol zigpy-xbee#177 the serial port opens with xonxoff set to the baudrate, so software flow control is always on and the flow_control setting is ignored. The fix changes runtime behaviour and asks for a hardware test.
  • zigpy-zigate:
    • get_time_server, set_tx_power and the frame-failure handler would raise AttributeError. All three are latent today: the two API methods are only called by the CLI, which can't be imported, and the handler's clause is never reached;
    • the zigpy-zigate CLI could not be imported since Implement zigpy 0.60.0 changes zigpy-zigate#150;
    • command() returned the status payload when the wanted response didn't arrive within the first timeout, so version(), get_network_key() and others returned the wrong value. Network formation and resets keep their tolerance for a late or missing confirmation.

Found but not fixed, because they need a decision:

  • bellows:
    • bellows join always raises TypeError (zha_security takes keyword-only arguments);
    • the CLI's async commands fail on Python 3.14 (asyncio.get_event_loop() with no loop);
    • AshProtocol.data_received's reject check reads the raw chunk instead of the frame.
  • zigpy-zigate: the flasher imports pyserial, which is no longer a dependency.
  • zigpy-xbee: AT_COMMANDS maps NI, DA and ND to the zigpy.types module, and the package's __version__ is hard-coded.
  • zigpy-deconz: requires-python still says 3.8, though zigpy needs 3.11.
  • zha-quirks: change_entity_metadata(new_entity_category=EntityType.STANDARD) would store a value HA's EntityCategory rejects. No quirk passes it today.

Opening the PRs

Each branch has a drafted PR text. A maintainer can have the bot open them from this thread, one library per comment, for example:

@zigpy-review-bot open the typing PRs for zigpy/zigpy-deconz from this issue: the bug-fix branches as separate PRs, and zigpy-bot/typing-baseline, zigpy-bot/typing-fixes and zigpy-bot/py-typed as a stacked chain.
@zigpy-review-bot open the PR for zigpy-bot/py-typed in zigpy/zigpy-ziggurat from this issue.

The bot opens a stacked chain with GitHub's stack feature where the bot owns every PR in it; a bellows or zigpy-xbee chain is stacked on that library's ruff-migration PR. zigpy/zigpy-zigate#167 lives on the bot's fork, which a GitHub stack can't include, so the zigpy-zigate chain is chained by hand ("Stacked on" lines), and its baseline PR is retargeted to dev once zigpy/zigpy-zigate#167 merges.

How the numbers were measured
  • Recorded errors are the totals of the generated override block, from each repo's tools/regenerate_mypy_ignores.py. That is mypy 2.4.1 with --strict --warn-unreachable and the repo's untyped_calls_exclude, against zigpy 2.4.1. zha-quirks used its locked zigpy 2.4.0; zigpy dev gives the same result.
  • Every typing branch tip passes the repo's pre-commit (with the new local mypy hook), its full test suite, and the regen tool reproducing its block unchanged. The bug-fix branches are based on dev and pass its test suite and its hooks; zigpy-zigate's autoflake8 hook can't be installed any more, and Replace black, isort, flake8 and pyupgrade with ruff zigpy-zigate#167 removes it.
  • The CI path was checked the way zigpy's shared workflow sets it up: uv sync --group ci, or requirements_test.txt plus -e ., then pre-commit run --all-files in the activated venv.
  • Typing fixes were checked for behaviour neutrality: serialization round trips, struct field and command definitions compared before and after, and exception paths. Where an assert replaces an AttributeError on None, the PR text says so.
  • The Fix all current mypy ignores zigpy#1827 figures come from an editable install of that branch merged onto zigpy dev, used for type measurement only.

Sub-issues

Sub-issues

0 of 1 Issues completed
Loading 1 sub-issues

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Fields

    Priority

    None yet

    Area

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions