Skip to content

Ignore concatenated template entity fragments - #1284

Merged
frenck merged 2 commits into
mainfrom
fix/issue-1250-templated-entity-id
Jun 21, 2026
Merged

frenck merged 2 commits into
mainfrom
fix/issue-1250-templated-entity-id

Conversation

@frenckatron

Copy link
Copy Markdown
Collaborator

Description

Adjusts the template entity extraction regex to ignore entity-looking literals when they are part of a Jinja string concatenation.

This prevents partial literals like switch.camera in {{ 'switch.camera' ~ cam_id ~ '_movies' }} from being reported as an unknown entity, while keeping static template references such as {{ states('light.kitchen') }} covered.

Motivation and Context

Fixes #1250.

Spook currently treats the static part of a templated entity ID as a complete entity reference. That creates a false positive repair for valid automations using templated entity_id values.

How has this been tested?

  • uv run ruff check custom_components/spook/entity_filtering.py tests/ectoplasms/automation/repairs/test_unknown_entity_references.py
  • uv run ruff format --check custom_components/spook/entity_filtering.py tests/ectoplasms/automation/repairs/test_unknown_entity_references.py
  • uv run pylint custom_components/spook/entity_filtering.py tests/ectoplasms/automation/repairs/test_unknown_entity_references.py
  • uv run pytest -q

Screenshots (if appropriate):

Not applicable.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Other

Checklist

  • My code follows the code style of this project.
  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.

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

coderabbitai Bot commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: ac7d4919-7176-4761-86a7-8e52b7aa6eac

📥 Commits

Reviewing files that changed from the base of the PR and between 853ce89 and 106d0f3.

📒 Files selected for processing (2)
  • custom_components/spook/entity_filtering.py
  • tests/ectoplasms/automation/repairs/test_unknown_entity_references.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/ectoplasms/automation/repairs/test_unknown_entity_references.py
  • custom_components/spook/entity_filtering.py

📝 Walkthrough

Walkthrough

Refactors template entity extraction to ignore regex matches that are part of concatenated template string literals, normalizes regex capture groups into canonical domain.object_id entity IDs, and adds tests validating concatenation-aware extraction behavior.

Changes

Templated Entity Reference Detection

Layer / File(s) Summary
Template entity extraction refactoring
custom_components/spook/entity_filtering.py
Adds _STATES_DOMAIN_ENTITY_GROUPS, introduces _is_concatenated_template_match and _entity_id_from_template_match, and refactors extract_entities_from_template_regex to use re.finditer, skip concatenated-template matches, and normalize capture groups into entity IDs.
Concatenated template entity test coverage
tests/ectoplasms/automation/repairs/test_unknown_entity_references.py
Adds value-template tests for concatenated entity-id fragments (literal and helper variants), tests ensuring static entity references inside concatenated value contexts are preserved, and an action-config test asserting templated target.entity_id fragments built via concatenation are ignored.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • frenck/spook#1275: Extends test coverage for templated/concatenated entity_id extraction and aligns with the extractor behavior changes.
  • frenck/spook#977: Changes how template regex match processing handles templated entity fragments and concatenation.
  • frenck/spook#1065: Touches the same template entity-id extraction flow and helper/tests around extraction.

Suggested reviewers

  • frenck

Poem

🐰 I hopp'd through templates, sniffed each seam,
Found fragments stitched where true IDs gleam.
I taught the matcher to skip the sewn,
Now partial ids are left alone.
Hooray — no more phantom entity dream!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Ignore concatenated template entity fragments' clearly and specifically describes the main change: preventing entity-like literals within Jinja string concatenations from being treated as complete entity references.
Description check ✅ Passed The description is directly related to the changeset, explaining the problem (false positives for templated entity IDs), the solution (adjusting regex to ignore concatenated entity literals), and providing clear examples.
Linked Issues check ✅ Passed The PR successfully addresses issue #1250 by modifying entity extraction to ignore entity-looking literals in Jinja concatenations while preserving detection of static references, with comprehensive test coverage.
Out of Scope Changes check ✅ Passed All changes are directly scoped to addressing issue #1250: entity filtering refactoring and comprehensive test coverage for concatenated template entity handling.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/issue-1250-templated-entity-id

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.

@codecov-commenter

codecov-commenter commented May 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.90909% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 62.91%. Comparing base (b51ff68) to head (106d0f3).

Files with missing lines Patch % Lines
custom_components/spook/entity_filtering.py 90.90% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1284      +/-   ##
==========================================
+ Coverage   62.72%   62.91%   +0.18%     
==========================================
  Files         124      124              
  Lines        3147     3163      +16     
  Branches      403      406       +3     
==========================================
+ Hits         1974     1990      +16     
  Misses       1126     1126              
  Partials       47       47              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
custom_components/spook/entity_filtering.py (1)

436-446: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix concatenation heuristic dropping unquoted states.<domain>.<entity> references.

extract_entities_from_template_regex skips every ENTITY_ID_TEMPLATE_PATTERNS match whenever _is_concatenated_template_match detects the match is adjacent to ~. This suppresses the only matcher for unquoted states.<domain>.<entity>.state|attributes (pattern #2), e.g. {{ 'Label: ' ~ states.sensor.temp.state }} results in sensor.temp not being added.

🐛 Proposed fix
     for pattern in ENTITY_ID_TEMPLATE_PATTERNS:
         for match in re.finditer(pattern, template_str, re.IGNORECASE):
-            if _is_concatenated_template_match(template_str, match):
+            # The unquoted states.<domain>.<entity> access is always a
+            # complete reference; only quoted literals can be fragments.
+            if (
+                len(match.groups()) != _STATES_DOMAIN_ENTITY_GROUPS
+                and _is_concatenated_template_match(template_str, match)
+            ):
                 continue

             entity_id = _entity_id_from_template_match(match)
🤖 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 `@custom_components/spook/entity_filtering.py` around lines 436 - 446, The loop
in extract_entities_from_template_regex currently skips any match when
_is_concatenated_template_match returns True, which incorrectly suppresses
unquoted states.<domain>.<entity> references; change the logic so that before
skipping a match you special-case the "states" accessor: if match.group(0) (the
raw matched text from template_str) contains "states." or ends with ".state" /
".attributes" (i.e. the states.<domain>.<entity> pattern), do not continue —
proceed to call _entity_id_from_template_match and the subsequent
split_comma_separated_entity_ids/valid_entity_id flow; keep the existing
_is_concatenated_template_match behavior for other patterns.
🤖 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.

Outside diff comments:
In `@custom_components/spook/entity_filtering.py`:
- Around line 436-446: The loop in extract_entities_from_template_regex
currently skips any match when _is_concatenated_template_match returns True,
which incorrectly suppresses unquoted states.<domain>.<entity> references;
change the logic so that before skipping a match you special-case the "states"
accessor: if match.group(0) (the raw matched text from template_str) contains
"states." or ends with ".state" / ".attributes" (i.e. the
states.<domain>.<entity> pattern), do not continue — proceed to call
_entity_id_from_template_match and the subsequent
split_comma_separated_entity_ids/valid_entity_id flow; keep the existing
_is_concatenated_template_match behavior for other patterns.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: bd2d498d-cdfe-449d-afd5-34b070c242f5

📥 Commits

Reviewing files that changed from the base of the PR and between b51ff68 and 853ce89.

📒 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 updates Spook’s template entity-reference extraction to avoid false-positive “unknown entity” reports when an entity-looking literal is only a fragment of a Jinja string concatenation (e.g., building entity_id dynamically with ~), and adds regression tests for those scenarios.

Changes:

  • Add test coverage ensuring concatenated entity-id fragments (including helper calls like is_state(...)) do not produce static entity references.
  • Refactor template regex extraction to use re.finditer() and helper functions to reconstruct captured entity IDs.
  • Introduce concatenation-adjacency filtering to skip entity-looking literals that are part of ~ concatenations.

Reviewed changes

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

File Description
custom_components/spook/entity_filtering.py Adds helper logic to skip template regex matches that appear to be concatenated entity-id fragments.
tests/ectoplasms/automation/repairs/test_unknown_entity_references.py Adds regression tests covering concatenated entity-id fragments in templates and action targets.

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

@frenck
frenck merged commit d109531 into main Jun 21, 2026
19 checks passed
@frenck
frenck deleted the fix/issue-1250-templated-entity-id branch June 21, 2026 19:35
@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Passed Quality Gate passed

Issues
0 New issues
0 Accepted issues

Measures
0 Security Hotspots
0.0% Coverage on New Code
0.0% Duplication on New Code

See analysis details on SonarQube Cloud

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.

False positive on templated entity_id

4 participants