Repository navigation
fix(schlage): delete untagged code before adding tagged code during tagging - #851
Conversation
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #851 +/- ##
===========================================
+ Coverage 84.14% 97.45% +13.30%
===========================================
Files 10 43 +33
Lines 801 6045 +5244
===========================================
+ Hits 674 5891 +5217
- Misses 127 154 +27
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
secondof9
left a comment
There was a problem hiding this comment.
📋 Review Summary
Tip
Review Status: 🟢 APPROVED
Change Type: 🐛 Bug Fix
Review Effort: 🟡 Medium
Core Impact: Fixes Schlage lock code tagging by reordering operations from "add-then-delete" to "delete-then-add", preventing duplicate-PIN validation collisions with Home Assistant core's Schlage service validator (schlage_code_exists).
🚦 CI & Pipeline Health Summary
| Check / Workflow Name | Status | Impact on Review |
|---|---|---|
Autolabel PR (Autolabeler) |
✅ PASSED | Labeling automation |
Autolabel PR (Autolabeler) |
⏩ SKIPPED | Duplicate/skipped run |
Prek (Python CI) |
✅ PASSED | Pre-commit checks (ruff, mypy, etc.) |
HACS Validation (Validation And Formatting) |
✅ PASSED | HACS manifest validation |
Pytest (3.14) (Python CI) |
✅ PASSED | Full test suite on Python 3.14 |
Hassfest Validation (Validation And Formatting) |
✅ PASSED | Home Assistant integration validation |
coverage (Python CI) |
✅ PASSED | Codecov coverage reporting (97.45%) |
Note
CI Pipeline Clear: All GitHub Actions workflows completed successfully.
🔍 Architectural Walkthrough
custom_components/keymaster/providers/schlage.py — Core Fix
-
_async_tag_untagged_code()(lines 384–441)- Root Cause: The original sequence called
_async_add_code(tagged_name, pin)before_async_delete_code(original_name). Since both entries shared the same PIN, Home Assistant core's Schlage validator (_validate_code_value→schlage_code_exists) rejected the add, causing tagging to fail on every coordinator refresh (issue #823). - Fix: Reordered to delete first, then add. The untagged code is removed from the lock, freeing the PIN, then the tagged replacement is added.
- Rollback: If
_async_add_code()fails after a successful delete, the method attempts to re-add the original untagged code (original_name,pin), preserving lock state. - Cancellation Safety:
asyncio.CancelledErroris explicitly caught and re-raised at both the add and rollback sites (lines 410–411, 428–429), preventing silent swallowing during shutdown or task cancellation. - Redaction Hygiene: Error messages respect
CONF_REDACT_SLOT_NAMESviaself.redact_slot_names(lines 413, 431), logging"[REDACTED]"instead of raw exception text when enabled. - Exception Boundaries: Uses
except Exception(with# noqa: BLE001) for the add/rollback paths to catch transport errors, timeouts, and non-HomeAssistantErrorexceptions fromhass.services.async_call. This is appropriate here since the goal is uniform failure handling and rollback attempt.
- Root Cause: The original sequence called
-
async_set_usercode()(lines 551–631) — Unchanged but consistent- Already used the correct delete-before-add order for replacements (lines 576–586), so no modification was needed. The pattern matches the new tagging logic.
tests/providers/test_schlage.py — Test Coverage
-
Updated Existing Tests
test_get_usercodes_untagged_assigned_slots(lines 615–629): Assertions updated to verify delete → add call order.test_get_usercodes_partial_tagging_add_failure(renamed from...delete_failure, lines 895–926): Scenario flipped to match new order; validates rollback path.test_get_usercodes_partial_tagging_rollback_failure(lines 928–962): Tests double-failure (add fails, then rollback add fails) with redaction enabled.test_get_usercodes_partial_tagging_rollback_failure_no_redaction(lines 964–999): Same scenario without redaction.test_get_usercodes_partial_tagging_rollback_then_retag_on_next_poll(lines 1001–1052): End-to-end retry test proving rollback leaves lock in a re-taggable state.
-
New Tests — Cancellation Safety
test_get_usercodes_tagging_cancelled_error_propagates(lines 1054–1074): VerifiesCancelledErrorraised during_async_add_code(after successful delete) propagates out ofasync_get_usercodes().test_get_usercodes_tagging_rollback_cancelled_error_propagates(lines 1076–1100): VerifiesCancelledErrorduring rollback_async_add_codealso propagates.
-
New Test — Stateful Core Validation
test_tagging_untagged_code_succeeds_against_core_validation(lines 1775–1795): UsesStatefulFakeSchlageLock(which mirrors HA core'sschlage_name_exists/schlage_code_existsvalidators) to prove the delete-before-add sequence succeeds where add-before-delete would collide withschlage_code_exists.
🔗 Related / Outside-Diff Context
custom_components/keymaster/providers/_base.py: Base provider class — no changes required; the fix is fully contained in the Schlage provider.- Issue #823: "Schlage lock code tagging fails on every refresh" — this PR is the direct fix.
- Issue #820: Related PIN rotation fix (PR #850) — same delete-before-add principle applied to
async_set_usercode.
⚠️ Minor Observations (Non-Blocking)
-
Inconsistent Exception Catch in Delete Path (line 399): The initial
_async_delete_codeonly catchesHomeAssistantError, but_async_delete_codecallshass.services.async_callwhich can also raise transport exceptions (timeouts, connection errors). For consistency with the add/rollback paths (lines 412, 430), consider catchingExceptionhere as well, or add a comment explaining whyHomeAssistantErroris sufficient. -
Rollback Failure Leaves Lock Without Code (lines 426–439): If both the tagged add and the rollback add fail, the lock ends up with neither the untagged nor the tagged code for that slot. The method returns
Falseand the code is omitted fromasync_get_usercodes()results (avoiding slot drift), but the lock state is now missing that code entirely until the next successful tagging attempt. This is the correct safe behavior, but worth noting in the docstring for future maintainers. -
BLE001 Suppression Justified: The
# noqa: BLE001on lines 412 and 430 is appropriate — these are top-level service-call boundaries where catching all exceptions enables the rollback attempt and structured logging.
✅ Verdict
The fix is correct, well-tested, and architecturally sound. It resolves the duplicate-PIN collision by aligning the tagging sequence with the proven delete-before-add pattern already used in async_set_usercode(). The test suite comprehensively covers success, partial failure, rollback failure, retry, cancellation propagation, and stateful core validation scenarios. All CI checks pass.
Recommendation: APPROVE and merge.
secondof9
left a comment
There was a problem hiding this comment.
📋 Review Summary
Tip
Review Status: 🟢 APPROVED
Change Type: 🐛 Bug Fix
Review Effort: 🟢 Low (re-review of addressed feedback)
Core Impact: The follow-up commit (94e5ca5) strengthens the Schlage lock code tagging fix by broadening exception handling in the initial delete path and documenting the rollback window behavior — both observations from the prior review are now resolved.
🚦 CI & Pipeline Health Summary
| Check / Workflow Name | Status | Impact on Review |
|---|---|---|
Autolabel PR (Autolabeler) |
✅ PASSED | Labeling automation |
Autolabel PR (Autolabeler) |
⏩ SKIPPED | Duplicate/skipped run |
Prek (Python CI) |
✅ PASSED | Pre-commit checks (ruff, mypy, etc.) |
HACS Validation (Validation And Formatting) |
✅ PASSED | HACS manifest validation |
Pytest (3.14) (Python CI) |
✅ PASSED | Full test suite on Python 3.14 |
Hassfest Validation (Validation And Formatting) |
✅ PASSED | Home Assistant integration validation |
coverage (Python CI) |
✅ PASSED | Codecov coverage reporting (97.45%) |
Note
CI Pipeline Clear: All 7 GitHub Actions workflows completed successfully on the latest commit (94e5ca5).
🔍 Architectural Walkthrough
custom_components/keymaster/providers/schlage.py — Follow-up Improvements
-
_async_tag_untagged_code()— Exception Handling Consistency (lines 406–419)- Previous state: Initial
_async_delete_codeonly caughtHomeAssistantError, while add/rollback paths caughtException(withCancelledErrorre-raised). - Current state: Now catches
asyncio.CancelledError(explicit re-raise) →Exception(with# noqa: BLE001) uniformly across all three failure sites (initial delete, tagged add, rollback add). - Logging improvement: Error messages now include
e.__class__.__qualname__alongside the (potentially redacted) message, providing better debuggability. - Resolution: Addresses Observation #1 from prior review — exception boundaries are now consistent.
- Previous state: Initial
-
_async_tag_untagged_code()— Rollback Window Documentation (lines 387–396, 444)- Added docstring explaining the delete-before-add strategy, the rollback attempt, and critically: "If both the tagged add and the rollback add fail, the lock temporarily has no code for this user until the next polling cycle retries tagging."
- Inline comment at line 444 reinforces this behavior for the double-failure rollback path.
- Resolution: Addresses Observation #2 from prior review — the lock-state gap is now explicitly documented for future maintainers.
tests/providers/test_schlage.py — New Test Coverage
-
test_get_usercodes_initial_delete_non_ha_error(lines 895–935)- Verifies that a non-
HomeAssistantError(e.g.,RuntimeErrorfrom transport layer) during the initial_async_delete_codeis caught, logged, and causes the code to be skipped (returns empty list) — no crash, no slot drift.
- Verifies that a non-
-
test_get_usercodes_initial_delete_cancelled_error_propagates(lines 937–971)- Verifies that
asyncio.CancelledErrorduring the initial delete propagates out ofasync_get_usercodes()without being swallowed — critical for graceful shutdown behavior.
- Verifies that
-
Both tests mirror the patterns established for the add/rollback paths, ensuring symmetrical coverage.
✅ Prior Feedback Status
| Prior Observation | Status | Resolution |
|---|---|---|
| 1. Inconsistent Exception Catch in Delete Path (line 399) | ✅ RESOLVED | Now catches Exception with CancelledError re-raise, matching add/rollback paths. |
| 2. Rollback Failure Leaves Lock Without Code (lines 426–439) | ✅ DOCUMENTED | Explicit docstring + inline comment describe the temporary gap until next poll retry. |
| 3. BLE001 Suppression Justified | ✅ CONFIRMED | Suppression remains appropriate at all three service-call boundaries. |
✅ Verdict
The follow-up commit fully addresses all prior review feedback. The exception handling is now consistent across all failure paths, the rollback window behavior is documented, and two new tests provide regression coverage for the initial delete edge cases. All CI checks pass, local test suite passes (96/96), and static analysis (ruff, mypy) is clean.
Recommendation: APPROVE and merge.
tykeal
left a comment
There was a problem hiding this comment.
schlage.py:394 — the docstring states that if both the tagged add and the rollback add fail the lock "temporarily has no code for this user until the next polling cycle retries tagging", but the original has already been deleted by then and no longer appears in get_codes, so _async_assign_untagged_codes has nothing left to discover and the PIN is permanently gone rather than retried. Confirmed by driving two polls against a fake enforcing core's validators: the second poll issues only get_codes and the lock stays empty.
schlage.py:444 — same incorrect claim in the inline comment ("until retried"). Both should say the code cannot be recovered, since the ERROR at :446 is the only trace the user ever gets.
|
Addressed in commit |
Summary
Fix Schlage lock code tagging by deleting the pre-existing untagged code before adding the tagged replacement, preventing duplicate-PIN validation collisions with Home Assistant core's Schlage service validator (
schlage_code_exists).Proposed change
When keymaster tags an untagged code discovered on a Schlage lock (
_async_tag_untagged_code), it previously called_async_add_codefor the tagged entry before deleting the untagged entry. Because the untagged entry was still present on the lock holding the same PIN, Home Assistant core's Schlage lock validator (_validate_code_value) rejected the add withschlage_code_exists, causing the tagging operation to fail on every coordinator refresh.This change:
_async_tag_untagged_code()to delete the untagged entry first, then add the tagged entry with the same PIN._async_add_code()fails, it attempts a rollback by re-adding the original untagged entry and respectsCONF_REDACT_SLOT_NAMESfor logged exception messages.asyncio.CancelledErrorwithout swallowing it during tagging or rollback.StatefulFakeSchlageLock(validating core's duplicate PIN validation rules), rollback on add failure, CancelledError propagation, and redaction hygiene.Type of change
Additional information