Skip to content

Derive catalog platform constraints from ESPHome framework metadata - #3074

Open
maniekes wants to merge 5 commits into
esphome:mainfrom
maniekes:adafruit-ble-manual-catalog
Open

maniekes wants to merge 5 commits into
esphome:mainfrom
maniekes:adafruit-ble-manual-catalog

Conversation

@maniekes

@maniekes maniekes commented Nov 16, 2026 •

Copy link
Copy Markdown

What does this implement/fix?

The catalog exposed Zephyr-only components on unsupported chips and presented the auto-loaded Zephyr framework as a configurable dependency.

Derive platform compatibility from Core's platform/framework pairs, root schema validators, and platform AUTO_LOAD metadata. Keep real component dependencies visible. Stop catalog generation with the affected component ID when known framework and platform constraints conflict. Also fail explicitly if a recognized framework validator has unreadable closure metadata; warn once if Core lacks the platform/framework enum, preserving the existing fallback.

Remove the Adafruit BLE refresh overlay. For newer Core exports, the standard schema and docs pipeline supplies optional ble_trigger (default true) and the bootloader action with its typed ID. Setting ble_trigger: false is available without the BLE server. Core requires the server when the setting is true.

The checked-in catalog was regenerated through the standard pipeline with the official enriched ESPHome 2026.11.0 schema and matching Core. The unpatched run reproduced the shipped catalog byte for byte. The generated delta is limited to the shared component index and 18 component bodies. The packaged release retains the real zephyr_ble_server dependency for Adafruit OTA. The optional ble_trigger field and manual action appear only in the newer Core export.

Related issue or feature (if applicable):

The merged companion PRs are linked below. This PR changes the common catalog generator and adds normal-CI regression tests.

Types of changes

  • Bugfix (non-breaking change which fixes an issue) — bugfix
  • New feature (non-breaking change which adds functionality) — new-feature
  • Enhancement to an existing feature — enhancement
  • Breaking change (fix or feature that would cause existing functionality to not work as expected) — breaking-change
  • Refactor (no behaviour change) — refactor
  • Documentation only — docs
  • Maintenance / chore — maintenance
  • CI / workflow change — ci
  • Dependencies bump — dependencies

Frontend coordination

  • No frontend change needed
  • Companion frontend PR: esphome/device-builder-frontend#

Uses existing catalog metadata and form controls. Core validates the conditional BLE-server requirement.

Checklist

  • The code change is tested and works locally.
  • Pre-commit hooks pass (ruff, codespell, yaml/json/python checks).
  • Tests have been added or updated under tests/ where applicable.
  • components.index.json / definitions/components/*.json have not been hand-edited (regenerate via script/sync_components.py if a sync is needed).
  • Architecture-level changes are reflected in docs/ARCHITECTURE.md and/or docs/API.md.

The change is limited to build-time catalog generation and uses the existing runtime API and models.

Validation

  • Follow-up hardening: the missing-freevar and empty-cell regressions exercise the catalog loop, and the missing-enum test exercises the actual import and cached fallback. On the final follow-up snapshot, an independent run passed 1,200 sync-component tests with ESPHome 2026.11.0. An identical-input comparison before/after the follow-up produced the same 1,203 component entries; no generated catalog files changed. Earlier broader test results below belong to their respective preparation snapshots.

  • The release-pinned catalog and board generation repeated byte for byte. Both check_catalog runs passed. A built wheel contained the expected index and component bodies, and the installed wheel passed nRF52 picker and lazy body checks in an isolated venv with ESPHome 2026.11.0.

  • Both conflict regressions failed before the fix and passed afterward. The sync suite passed 1,527 baseline and 1,539 candidate tests. Final targeted Ruff lint and format checks passed. An independent review reconstructed the final patch on the reviewed base and passed 1,198 tests plus generator exit probes.

  • The real dev schema export, docs enrichment, full generation and check_catalog passed on the pinned and fresh Core snapshots. The fresh run built 1,238 components and 1,394 automation bodies. It verified the field, default, conditional help, nRF52 picker and typed bootloader action. The earlier same-input comparison identified 17 affected components.

  • The real older Core export retained its BLE-server dependency and omitted the new option and action.

  • The isolated Chromium smoke was attempted. A cgroup process limit prevented browser rendering from being verified.

Companion pull requests

The conditional-help wording was verified with a separate, unpublished docs patch. It is outside this Builder PR.

@github-actions github-actions Bot added the enhancement Improvement to an existing feature label Nov 16, 2026
@codspeed

codspeed Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 23.21%

❌ 1 regressed benchmark
✅ 27 untouched benchmarks
⏩ 1 skipped benchmark1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_scan_5k_no_match_case_sensitive 3.3 ms 4.2 ms -23.21%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing maniekes:adafruit-ble-manual-catalog (9f9e460) with main (50fc28c)

Open in CodSpeed

Footnotes

  1. 1 benchmark was skipped, so the baseline result was used instead. If it was deleted from the codebase, click here and archive it to remove it from the performance reports. ↩

@codecov

codecov Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.77%. Comparing base (391707a) to head (9f9e460).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##             main    #3074    +/-   ##
========================================
  Coverage   99.77%   99.77%            
========================================
  Files         300      305     +5     
  Lines       26564    27006   +442     
========================================
+ Hits        26503    26945   +442     
  Misses         61       61            
Flag Coverage Δ
py3.12 99.73% <ø> (+<0.01%) ⬆️
py3.14 99.62% <ø> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.
see 9 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@bdraco

Copy link
Copy Markdown
Member

This looks like its at the wrong altitude. We shouldn't be hard coding any of this

@esphbot

Copy link
Copy Markdown
Contributor

J. Nick Koston (@bdraco): This looks like its at the wrong altitude. We shouldn't be hard coding any of this

Agreed. Entry already exists from sync. Core PR plus docs make nightly sync produce it. Overlay script hardcodes name, description, dependencies. Next full sync undoes it. Fix dependency in core metadata instead.

@esphbot

ESPHome Bot (esphbot) commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@esphbot ESPHome Bot (esphbot) 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.

Warning

Important issues found.

  • A one-component overlay script bypasses the sync pipeline, and the next nightly sync will undo it
  • Component-specific string check hardcoded into the shared action converter

Merge upstream main and replace the scoped Adafruit BLE refresh with framework metadata in the common generator. Reject conflicting constraints and cover the behavior in the regular sync suite.
@maniekes maniekes changed the title Add scoped catalog refresh for Adafruit BLE manual bootloader entry Derive catalog platform constraints from ESPHome framework metadata Nov 24, 2026

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 packaged catalog was not regenerated and committed, so built wheels still expose unsupported-chip choices and the unwanted zephyr dependency in the dashboard.

1 open issue
What changed in this PR

This PR updates the build-time catalog generator to derive chip compatibility from ESPHome framework metadata, keeping unsupported components out of device selections.

Changes:

  • Combine platform/framework pairs, root schema validators, and platform auto-loading metadata to derive compatibility.
  • Remove implicit framework dependencies while preserving configurable dependencies, and abort generation when constraints conflict.
  • Add regression tests for compatibility, dependency filtering, schema scope, and unavailable introspection.
File Description
tests/​test_sync_components_frameworks.py Adds regression coverage for framework-derived catalog constraints.
script/​sync_components.py Derives platform restrictions, filters implicit dependencies, and rejects conflicting constraints.

Review effort: Balanced (adaptive)

Comment thread script/sync_components.py
Comment on lines +3365 to +3371
implicit_frameworks, supported_platforms = _apply_framework_constraints(
dependencies,
(introspection.get("root_frameworks") or {}).get(domain),
_platform_arm_alternatives(domain, stem if domain else top_key, dependencies)
or _derive_supported_platforms(stem if domain else top_key, dependencies, introspection),
component_id=component_id,
)
@esphbot

ESPHome Bot (esphbot) commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Code Review

⚠️ Partial review — 3 file(s) omitted due to diff size and NOT reviewed: esphome_device_builder/definitions/components/light.fastled_clockless.json, esphome_device_builder/definitions/components/light.neopixelbus.json, esphome_device_builder/definitions/components/sensor.bme680_bsec.json

PR Review — Derive catalog platform constraints from ESPHome framework metadata

Merge-ready. This PR replaces the earlier hardcoded Adafruit overlay with a general, metadata-driven fix at the right layer.

Strengths:

  • Platform limits now come from Core's own PlatformFramework pairs, only_with_framework root validators and platform AUTO_LOAD, with no per-component special cases. This resolves both findings from the previous review (the overlay script and the qualified == ... branch) and J. Nick Koston (@bdraco)'s "wrong altitude" concern.
  • Implicit framework dependencies (zephyr) are dropped, while real ones (zephyr_ble_server) are kept.
  • Conflicting constraints stop generation with the component ID. Raising SystemExit correctly gets past the per-file except Exception handler.
  • The fallback is conservative: if introspection is unavailable, the catalog metadata is left as it was, and a test covers this.
  • The tests run in normal CI with no external schema dir. They cover dependency filtering, root-level vs field-level gate scope, projection onto chip platforms, and both conflict shapes.
  • The catalog was regenerated and committed, which resolves Copilot's "regenerate the packaged catalog" comment. The generated delta matches the PR description.

Non-blocking notes:

  • _root_frameworks indexes Core's closure variable frameworks directly. A rename would crash the sync with an unhelpful KeyError.
  • About 90 lines are added to a 12k-line module. The helpers would fit in a sibling script/_*.py module.

✅ Resolved since last review (1)

Previously-flagged issues verified fixed
  • script/sync_components.py:11165 Component-specific string check hardcoded into the shared action converter

🟢 Suggestions

1. A rename of Core's closure variable would crash catalog generation with a bare KeyError
script/sync_components.py:10683

_root_frameworks finds the gate by its __qualname__ prefix. It then indexes _closure_nonlocals(schema)["frameworks"] directly.

If Core renames that captured variable but keeps the function name, every sync fails with a KeyError that does not name the component or the cause. The rest of this PR handles missing introspection gracefully: no PlatformFramework, or no loader, returns the catalog unchanged. This lookup is the one fragile point that does not.

Suggested fix:

  • Use .get("frameworks").
  • If it is missing, raise a SystemExit that names the validator, or return None (no constraint), whichever behaviour you prefer.

I could not check the installed Core's only_with_framework source in this checkout because there is no venv.

        return frozenset(_closure_nonlocals(schema)["frameworks"])
2. New framework-projection helpers add to a module far over the size cap
script/sync_components.py:10673-10746

script/sync_components.py is now 12,057 lines. AGENTS.md says a PR touching a module already over 800 lines should not make it bigger.

The four new helpers are a self-contained concept:

  • _root_frameworks
  • _platform_framework_pairs
  • _is_framework_dependency
  • _apply_framework_constraints

They only need _closure_nonlocals, _resolve_auto_load, _expand_libretiny, _target_platform_names and the loader. The repo already splits sync code into sibling modules such as script/_catalog_split.py and script/_esphome_version.py.

Moving these helpers into something like script/_framework_constraints.py would keep the growth out of the monolith and give the new tests a narrower import target. This does not block merge.


Checklist

  • No hardcoded secrets
  • Catalog bodies and indexes produced only by the sync pipeline
  • Feature logic kept out of shared modules (no per-component special cases)
  • New behaviour tested in CI
  • Graceful degradation when Core introspection changes — suggestion #1
  • Does not grow over-cap modules — suggestion #2

Silent Failure Analysis

🟠 **3. HIGH** — upstream drift caught by the per-file handler
script/sync_components.py:10673-10684

Risk: If ESPHome renames the closure variable or leaves the cell unbound, the KeyError or ValueError reaches the blanket except Exception in build_catalog (around line 1313), which logs the error and skips the whole file, so the sync drops every component in that file and still finishes green.

if getattr(schema, "__module__", None) == "esphome.config_validation" and getattr(
    schema, "__qualname__", ""
).startswith("only_with_framework."):
    return frozenset(_closure_nonlocals(schema)["frameworks"])

Fix: Check that frameworks is in the closure and raise SystemExit with an 'upstream internals changed' message, as _literal_unit_suffix and _NON_INTROSPECTABLE_UNITS already do.

🟡 **4. MEDIUM** — framework gate silently ignored when the name doesn't match
script/sync_components.py:10673-10684

Risk: Detection depends on the exact only_with_framework. qualname and on the gate sitting directly in a root vol.All, so a renamed upstream validator or a differently wrapped schema returns None and the component quietly loses its platform restriction with no warning.

if isinstance(schema, vol.All):
    gates = [...]
    return frozenset.intersection(*gates) if gates else None
if ... .startswith("only_with_framework."):
    ...
return None

Fix: When it runs, confirm that cv.only_with_framework still produces a closure with that qualname and fail loudly if it doesn't, or at least log a debug line when a schema with framework-related validators yields no gate.

🟡 **5. MEDIUM** — silent fallback on import failure
script/sync_components.py:10687-10694

Risk: If PlatformFramework is missing (for example after an ESPHome rename), every framework constraint is dropped and implicit zephyr-style dependencies stay in the catalog with no log message, and @cache locks in the empty result for the whole run.

try:
    from esphome.const import PlatformFramework
except ImportError:
    return ()
...
if not pairs or loader is None:
    return set(), platforms

Fix: Log a warning when the import fails (as _get_esphome_loader does), or raise SystemExit if a loader is present but PlatformFramework is not, since that means upstream drift rather than ESPHome being absent.


Automated review by Kōan (Claude) HEAD=b1d226e 1 min

@esphbot ESPHome Bot (esphbot) 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.

Tip

No blocking issues found — ready to merge.

@maniekes

Copy link
Copy Markdown
Author

Addressed the defensive handling suggestions in 8690741, with the test-isolation follow-up in 9f9e460:

  • A recognized framework validator with a missing frameworks free variable or an empty closure cell now aborts generation with the component and validator identified. The per-file handler can no longer swallow these failures and omit a component.
  • A missing PlatformFramework import now warns once per cache while retaining the previous fallback behavior.
  • Regression tests cover the catalog-loop failure path and the actual import/cache branch.
  • The closure regression also passes independently with a cold cache across four hash seeds; its synthetic manifest is scoped to the target component.

Kept this follow-up limited to the generator and existing test file: no helper extraction, generic wrapper traversal, or catalog regeneration. The same-input comparison preserves all 1,203 generated component entries; an independent run of the final snapshot passed 1,200 sync-component tests on Core 2026.11.0.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement Improvement to an existing feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants