Skip to content

fix(schlage): delete untagged code before adding tagged code during tagging - #851

Merged
firstof9 merged 3 commits into
FutureTense:mainfrom
firstof9:fix/823-schlage-tag-untagged-delete-first
Nov 5, 2026
Merged

firstof9 merged 3 commits into
FutureTense:mainfrom
firstof9:fix/823-schlage-tag-untagged-delete-first

Conversation

@firstof9

@firstof9 firstof9 commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator

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_code for 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 with schlage_code_exists, causing the tagging operation to fail on every coordinator refresh.

This change:

  1. Reorders _async_tag_untagged_code() to delete the untagged entry first, then add the tagged entry with the same PIN.
  2. If _async_add_code() fails, it attempts a rollback by re-adding the original untagged entry and respects CONF_REDACT_SLOT_NAMES for logged exception messages.
  3. Propagates asyncio.CancelledError without swallowing it during tagging or rollback.
  4. Adds tests exercising successful tagging against StatefulFakeSchlageLock (validating core's duplicate PIN validation rules), rollback on add failure, CancelledError propagation, and redaction hygiene.

Type of change

  • Bugfix (non-breaking change which fixes an issue)

Additional information

@github-actions github-actions Bot added the bugfix Fixes a bug label Nov 4, 2026
@codecov-commenter

codecov-commenter commented Nov 4, 2026 •

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 97.45%. Comparing base (cdb4922) to head (1847489).
⚠️ Report is 413 commits behind head on main.
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

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     
Flag Coverage Δ
python 97.45% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 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.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@secondof9 secondof9 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📋 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.CancelledError is 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_NAMES via self.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-HomeAssistantError exceptions from hass.services.async_call. This is appropriate here since the goal is uniform failure handling and rollback attempt.
  • 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): Verifies CancelledError raised during _async_add_code (after successful delete) propagates out of async_get_usercodes().
    • test_get_usercodes_tagging_rollback_cancelled_error_propagates (lines 1076–1100): Verifies CancelledError during rollback _async_add_code also propagates.
  • New Test — Stateful Core Validation

    • test_tagging_untagged_code_succeeds_against_core_validation (lines 1775–1795): Uses StatefulFakeSchlageLock (which mirrors HA core's schlage_name_exists / schlage_code_exists validators) to prove the delete-before-add sequence succeeds where add-before-delete would collide with schlage_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)

  1. Inconsistent Exception Catch in Delete Path (line 399): The initial _async_delete_code only catches HomeAssistantError, but _async_delete_code calls hass.services.async_call which can also raise transport exceptions (timeouts, connection errors). For consistency with the add/rollback paths (lines 412, 430), consider catching Exception here as well, or add a comment explaining why HomeAssistantError is sufficient.

  2. 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 False and the code is omitted from async_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.

  3. BLE001 Suppression Justified: The # noqa: BLE001 on 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.

@firstof9
firstof9 requested a review from tykeal November 4, 2026 18:12

@secondof9 secondof9 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📋 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_code only caught HomeAssistantError, while add/rollback paths caught Exception (with CancelledError re-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.
  • _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., RuntimeError from transport layer) during the initial _async_delete_code is caught, logged, and causes the code to be skipped (returns empty list) — no crash, no slot drift.
  • test_get_usercodes_initial_delete_cancelled_error_propagates (lines 937–971)

    • Verifies that asyncio.CancelledError during the initial delete propagates out of async_get_usercodes() without being swallowed — critical for graceful shutdown behavior.
  • 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 tykeal left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@firstof9

firstof9 commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed in commit 1847489. Updated both the docstring and the inline comment to accurately reflect that if both the tagged add and rollback add fail, the original code has already been deleted and cannot be recovered automatically (the code is lost from the lock and won't be rediscovered on subsequent polls).

@firstof9
firstof9 requested a review from tykeal November 5, 2026 14:12

@tykeal tykeal left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@firstof9
firstof9 merged commit 98b15ea into FutureTense:main Nov 5, 2026
7 checks passed
@firstof9
firstof9 deleted the fix/823-schlage-tag-untagged-delete-first branch November 5, 2026 14:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bugfix Fixes a bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Schlage: tagging any pre-existing code still fails — add-then-delete collides with duplicate-PIN validation

4 participants