Skip to content

Ignore entity ID prefixes in templates - #1306

Merged
frenck merged 3 commits into
mainfrom
fix/template-prefix-literals
Jun 22, 2026
Merged

frenck merged 3 commits into
mainfrom
fix/template-prefix-literals

Conversation

@frenckatron

Copy link
Copy Markdown
Collaborator

Summary

Fixes #1090 by ignoring entity-like strings that are used as string-prefix or string-suffix checks in Jinja templates.

A template such as entity.entity_id.startswith('binary_sensor.proxmox') uses binary_sensor.proxmox as a prefix, not as a concrete entity ID. Spook now keeps that out of the unknown entity repair while still detecting actual entity references.

Validation

  • uv run pytest tests/ectoplasms/automation/repairs/test_unknown_entity_references.py -q
  • uv run ruff format --check custom_components/spook/entity_filtering.py tests/ectoplasms/automation/repairs/test_unknown_entity_references.py
  • uv run ruff check --output-format=github custom_components/spook/entity_filtering.py tests/ectoplasms/automation/repairs/test_unknown_entity_references.py
  • uv run --with pre-commit pre-commit run pylint --files custom_components/spook/entity_filtering.py tests/ectoplasms/automation/repairs/test_unknown_entity_references.py

@frenckatron frenckatron added the bugfix Inconsistencies or issues which will cause a problem for users or implementors. label Jun 22, 2026
@coderabbitai

coderabbitai Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@frenckatron, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 10 minutes and 5 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 48f25c96-ae32-4802-aade-e2fbc65d2906

📥 Commits

Reviewing files that changed from the base of the PR and between 7ad2d24 and 262c959.

📒 Files selected for processing (1)
  • custom_components/spook/entity_filtering.py
📝 Walkthrough

Walkthrough

A new helper predicate _is_string_method_argument_match is added to entity_filtering.py to detect quoted entity-like literals used as arguments to string methods (e.g., startswith('binary_sensor.proxmox')). The existing extract_entities_from_template_regex filter is extended to skip these matches in addition to concatenated literals. Three new tests assert that extract_entities_from_value returns an empty set for startswith and endswith templates with various input patterns.

Changes

String-method argument false positive fix

Layer / File(s) Summary
New predicate and extraction filter update
custom_components/spook/entity_filtering.py
Adds _is_string_method_argument_match (lines 421–435) to identify entity-like literals at string method argument positions, wires it into the skip condition of extract_entities_from_template_regex (lines 464–466) to skip matches identified as string method arguments.
Test coverage for string-method argument skipping
tests/ectoplasms/automation/repairs/test_unknown_entity_references.py
Adds three new async tests: test_value_template_ignores_entity_id_prefix_string_match (lines 69–82), test_value_template_ignores_entity_id_prefix_string_match_grouped (lines 83–90), and test_value_template_ignores_entity_id_suffix_string_match (lines 92–99), each verifying that templates using startswith or endswith with entity-like literals return an empty entity set.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • frenck/spook#977: Modifies the same template/entity-reference extraction path in entity_filtering.py to prevent template string expressions from being misidentified as entity IDs.
  • frenck/spook#1284: Also modifies custom_components/spook/entity_filtering.py and the same test file to prevent templated string fragments from being interpreted as complete entity IDs.
  • frenck/spook#1275: Adds the same golden-path test suite for automation unknown-entity-reference extraction behavior in the same test file.

Suggested reviewers

  • frenck

Poem

🐇 Hoppity hop through the template maze,
A startswith prefix caused quite a daze —
"That's not an entity!" the rabbit cried,
A new little predicate guards the inside.
No more false alarms for binary_sensor.proxmox! 🎉

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: ignoring entity ID strings used as prefixes in template methods like startswith().
Description check ✅ Passed The description clearly relates to the changeset, explaining the fix for issue #1090 regarding false positive unknown entity warnings.
Linked Issues check ✅ Passed The PR fulfills issue #1090 requirements by introducing logic to distinguish entity-like strings used in prefix/suffix checks from actual entity references.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the entity filtering logic and corresponding tests required for issue #1090.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/template-prefix-literals

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot 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.

🧹 Nitpick comments (1)
tests/ectoplasms/automation/repairs/test_unknown_entity_references.py (1)

69-80: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Add a companion endswith test for symmetry with the new predicate.

The implementation now explicitly handles both startswith and endswith, but only the prefix path is covered here. A suffix-case test will lock the full contract and prevent regressions.

Suggested test addition
+async def test_value_template_ignores_entity_id_suffix_string_match(
+    hass: HomeAssistant,
+) -> None:
+    """String suffix checks are not complete entity references."""
+    template = (
+        "{% for entity in states.binary_sensor if "
+        "entity.entity_id.endswith('.proxmox') %}"
+        "{{ entity.state }}"
+        "{% endfor %}"
+    )
+
+    assert await extract_entities_from_value(hass, template) == set()
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/ectoplasms/automation/repairs/test_unknown_entity_references.py` around
lines 69 - 80, Add a new async test function that mirrors
test_value_template_ignores_entity_id_prefix_string_match but uses the endswith
method instead of startswith to verify that string suffix checks are also not
recognized as complete entity references and return an empty set. This ensures
the endswith path is tested symmetrically with the prefix test and prevents
regressions in the implementation that handles both startswith and endswith
predicates.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@tests/ectoplasms/automation/repairs/test_unknown_entity_references.py`:
- Around line 69-80: Add a new async test function that mirrors
test_value_template_ignores_entity_id_prefix_string_match but uses the endswith
method instead of startswith to verify that string suffix checks are also not
recognized as complete entity references and return an empty set. This ensures
the endswith path is tested symmetrically with the prefix test and prevents
regressions in the implementation that handles both startswith and endswith
predicates.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: ae6efcb8-4b6c-4d98-b299-b2e2b102d358

📥 Commits

Reviewing files that changed from the base of the PR and between 2237ddf and e6d0763.

📒 Files selected for processing (2)
  • custom_components/spook/entity_filtering.py
  • tests/ectoplasms/automation/repairs/test_unknown_entity_references.py

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.

Pull request overview

This PR addresses false-positive “Unknown entities used” repairs by teaching Spook’s template regex extractor to ignore entity-like strings when they are used as prefix/suffix arguments in Jinja string checks (e.g., startswith()), rather than as concrete entity references.

Changes:

  • Add regex-side filtering to skip entity-like literals used as arguments to .startswith() / .endswith() in templates.
  • Add a regression test ensuring a startswith('binary_sensor.proxmox') prefix check does not yield an entity reference.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
custom_components/spook/entity_filtering.py Adds _is_string_method_argument_match and integrates it into template entity extraction to avoid false positives from prefix/suffix checks.
tests/ectoplasms/automation/repairs/test_unknown_entity_references.py Adds a regression test for templates using entity.entity_id.startswith(...) to ensure no entities are extracted.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

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.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

@frenck
frenck merged commit 978034b into main Jun 22, 2026
20 checks passed
@frenck
frenck deleted the fix/template-prefix-literals branch June 22, 2026 17:16
@sonarqubecloud

Copy link
Copy Markdown

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

Labels

bugfix Inconsistencies or issues which will cause a problem for users or implementors.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Spook reports a false positive “Unknown entities used” warning when using a Jinja template with startswith() to filter entities.

3 participants