Skip to content

fix(coordinator): evaluate slot schedule limits in HA configured time zone - #856

Merged
firstof9 merged 2 commits into
FutureTense:mainfrom
firstof9:fix/855-slot-active-ha-timezone
Nov 9, 2026
Merged

firstof9 merged 2 commits into
FutureTense:mainfrom
firstof9:fix/855-slot-active-ha-timezone

Conversation

@firstof9

@firstof9 firstof9 commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fix KeymasterCoordinator._is_slot_active to evaluate slot schedule limits (day of week and time of day) against Home Assistant's configured time zone via homeassistant.util.dt.now() rather than Python's datetime.now() / process clock.

Proposed change

Previously, _is_slot_active evaluated slot active status using datetime.now().time() and datetime.now().astimezone().weekday(). In environments like Docker or Home Assistant Container without a host TZ variable set, the process clock runs in UTC while Home Assistant is configured with a local time zone (e.g. America/Los_Angeles).

This caused:

  1. Time-of-day limits: datetime.now().time() returned UTC time and was compared directly against local time_start / time_end, causing slots to become inactive many hours early or late.
  2. Day-of-week limits: datetime.now().astimezone().weekday() used the process time zone (UTC), causing weekday rollover at UTC midnight rather than local midnight.
  3. Date ranges: Date range comparison is now evaluated consistently against now = dt_util.now() (though stored values were already tz-aware).
  4. Single sample: Sampling now once removes any potential race condition across midnight between the previous multiple datetime.now() calls.

This PR:

  • Imports and uses homeassistant.util.dt.now() in _is_slot_active to obtain the current datetime in HA's configured time zone once.
  • Extracts now.weekday() and now.time() for accurate schedule evaluations.
  • Adds comprehensive unit tests using pytest-freezer and dt_util.set_default_time_zone() to pin the clock and verify day-of-week rollover and time-of-day include/exclude windows against non-UTC zones deterministically.

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 7, 2026
@firstof9
firstof9 requested a review from tykeal November 7, 2026 22:24
@codecov-commenter

codecov-commenter commented Nov 7, 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.60%. Comparing base (cdb4922) to head (d8fdf5f).
⚠️ Report is 414 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     #856       +/-   ##
===========================================
+ Coverage   84.14%   97.60%   +13.45%     
===========================================
  Files          10       43       +33     
  Lines         801     6047     +5246     
===========================================
+ Hits          674     5902     +5228     
- Misses        127      145       +18     
Flag Coverage Δ
python 97.60% <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

This comment was marked as outdated.

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

tests/test_coordinator.py:2913 and tests/test_coordinator.py:2982 don't reliably discriminate the fix — they only mock dt_util.now, so the pre-fix code just falls back to the real clock. Verified: with the clock frozen to Fri 2026-11-06 11:00 local, both pass unmodified against main's dt.now() logic (only test_slot_time_of_day_includes_window_uses_ha_timezone fails); pin the clock with freeze_time plus dt_util.set_default_time_zone() to a non-UTC zone so the assertions actually depend on the HA zone rather than on what day CI runs.

tests/test_coordinator.py:2880, :2898, :3016 derive the expected weekday from a live dt_util.now() while the code under test samples its own — flaky across a midnight boundary. Nit.

custom_components/keymaster/coordinator.py:2246-2250 is a semantic no-op: stored date-range values are always tz-aware (HA's datetime component coerces naive input to the default zone before async_set_value), and aware-vs-aware comparison is by absolute instant, so dt.now().astimezone() and dt_util.now() are interchangeable there. Fine as a consistency cleanup, but the PR body lists date ranges under "This caused" — they were never affected.

The weekday/time-of-day hunks are correct, and sampling now once removes a real midnight-boundary race between the four old dt.now() calls.

Not for this PR: custom_components/keymaster/migrate.py:232 stamps legacy naive date-range values with the process UTC offset instead of HA's configured zone — same bug class, in a path this change doesn't reach.

@firstof9

firstof9 commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed the review feedback in commit d8fdf5f:

  1. Deterministic Test Discrimination via freezer & Default Timezone:

    • Replaced dynamic patch("dt_util.now", ...) in the schedule tests with freezer.move_to(...) and dt_util.set_default_time_zone(pacific_tz).
    • This directly exercises dt_util.now() vs the UTC process clock datetime.now() so the tests strictly fail against the pre-fix logic and pass on the fix, regardless of wall-clock time or day in CI.
    • Pinned the clock in all DOW and TOD test cases, eliminating the potential midnight race condition where test expectations sampled live time separately from the method under test.
    • Adjusted the exclude-window test to a window that cleanly discriminates between the UTC clock and local Pacific time.
  2. PR Description Clarification:

    • Clarified in the PR summary that stored date-range values were already tz-aware, and using now = dt_util.now() there is consistency cleanup and avoids multiple clock samples across a midnight boundary.

@firstof9
firstof9 requested a review from tykeal November 9, 2026 18:47

@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
Core Impact: Fixes a critical timezone bug in KeymasterCoordinator._is_slot_active where slot schedule limits (day-of-week, time-of-day, date ranges) were evaluated against the process clock (UTC in Docker containers) instead of Home Assistant's configured timezone. The follow-up commit d8fdf5f addresses prior review feedback by hardening the test suite with pytest-freezer and dt_util.set_default_time_zone() to create deterministic, discriminating test scenarios.


🚦 CI & Pipeline Health Summary

Check / Workflow Name Status Impact on Review
Autolabel PR ✅ PASSED Standard labeling check
HACS Validation ✅ PASSED HACS compatibility verified
Hassfest Validation ✅ PASSED Home Assistant integration manifest valid
Prek ✅ PASSED Pre-commit hooks (ruff, mypy, codespell) clean
Pytest (3.14) ✅ PASSED All unit tests pass on Python 3.14
coverage ✅ PASSED Coverage thresholds met (97.60% per Codecov)

Note

CI Pipeline Clear: All GitHub Actions workflows completed successfully.


🔍 Architectural Walkthrough

custom_components/keymaster/coordinator.py
  • Lines 29-30: Import refactored to include dt_util from homeassistant.util alongside slugify. This is the correct HA pattern for timezone-aware datetime operations.
  • Line 2244: Single call to now = dt_util.now() captures the current datetime in HA's configured timezone once, avoiding repeated calls and ensuring consistency across all schedule evaluations.
  • Lines 2246-2249: Date range comparison now uses now (HA timezone) instead of dt.now().astimezone() (process timezone). This fixes the date range evaluation for users where HA timezone ≠ system timezone.
  • Line 2252: Weekday extraction uses now.weekday() (HA timezone) instead of dt.now().astimezone().weekday() (process timezone). This fixes the critical weekday rollover bug at UTC midnight vs local midnight.
  • Lines 2258-2259: Time-of-day extraction uses current_time = now.time() (HA timezone) instead of repeated dt.now().time() calls. This fixes the time window evaluation bug.
  • Lines 2260-2267: Include-mode time window comparison simplified to use current_time variable, improving readability and performance.
  • Lines 2274-2278: Exclude-mode time window comparison similarly simplified with chained comparison today.time_start <= current_time <= today.time_end.

Verdict: The fix correctly addresses all three bug vectors described in issue #855 (time-of-day, day-of-week, date ranges) by consistently using HA's timezone utility. The single now capture is a good practice for consistency.

tests/test_coordinator.py (Updated in commit d8fdf5f)
  • Lines 2877-2911: test_slot_day_of_week_disabled_day_returns_false and test_slot_day_of_week_enabled_day_returns_true — Now use freezer fixture to pin clock, eliminating live-time flakiness.
  • Lines 2913-2947: test_slot_day_of_week_uses_ha_timezone_weekday — Critical discriminating test: Freezes clock to 2026-11-07 05:00:00 UTC (Saturday in UTC) while setting HA default timezone to America/Los_Angeles (Friday 21:00). Verifies slot evaluates as active when Friday (4) enabled, inactive when only Saturday (5) enabled. This strictly fails against pre-fix logic (dt.now().astimezone().weekday() → Saturday) and passes on the fix (dt_util.now().weekday() → Friday).
  • Lines 2949-2984: test_slot_time_of_day_includes_window_uses_ha_timezone — Freezes to 2026-11-06 21:57:00 UTC (13:57 Pacific). Tests include-mode window 09:00-21:00 returns True, correctly returns False when window narrowed to 09:00-13:00.
  • Lines 2986-3018: test_slot_time_of_day_excludes_window — Improved discrimination: Exclude window changed from [09:00, 21:00] to [09:00, 15:00] so 13:57 Pacific is clearly inside excluded window (inactive), then window shifted to [14:00, 21:00] (active). This cleanly discriminates HA timezone vs UTC.
  • Lines 3020-3045: test_slot_time_of_day_invalid_time_types — Defensive test with frozen clock, ensuring None time_start/time_end with limit_by_time=True returns False for both include and exclude modes.

Verdict: Test suite now properly uses freezer.move_to() + dt_util.set_default_time_zone() to create deterministic scenarios where UTC process clock and HA configured timezone diverge. This directly addresses the prior review feedback from @tykeal. All tests are deterministic, non-flaky, and strictly discriminate the fix from the buggy implementation.


🔗 Related / Outside-Diff Context

  • Issue #855: This PR fixes the reported issue where slot schedules evaluated against UTC process clock instead of HA configured timezone.
  • Prior Review (tykeal): Identified that original tests didn't reliably discriminate the fix — only mocked dt_util.now(), so pre-fix code fell back to real clock. Also noted flaky live-time dependencies in some tests.
  • Author Response (commit d8fdf5f): Addressed all feedback by pinning clock with freezer and setting HA default timezone to non-UTC zone, eliminating flakiness and ensuring tests strictly depend on HA timezone logic.
  • Codecov Report: Project coverage increased from 84.14% to 97.60% (+13.45%), indicating the new tests significantly improve coverage.

✅ Diagnostic Lens Evaluation

Lens Assessment
HA Architectural Compliance ✅ PASS — Uses dt_util.now() per HA best practices; no blocking I/O in entity getters; coordinator pattern respected.
Python 3.14 Async Runtime ✅ PASS — No asyncio hazards; synchronous dt_util.now() is non-blocking; no task leaks.
Defensive Data Validation ✅ PASS — Existing isinstance guards retained; new tests cover invalid time types.
CI Diagnostics ✅ PASS — All 6 check runs passed; coverage improved significantly.
Prior Feedback Status ✅ RESOLVED — All issues from @tykeal's review addressed in commit d8fdf5f. Tests now properly discriminate with frozen clock + HA timezone configuration.

Approval Rationale: The fix is minimal, targeted, and correct. It resolves a genuine production bug affecting users in non-UTC timezones running HA in containers. The follow-up commit d8fdf5f addresses all prior review feedback by hardening the test suite with pytest-freezer and dt_util.set_default_time_zone() to create deterministic, discriminating test scenarios that strictly fail against the buggy implementation and pass on the fix. All CI checks pass. No architectural concerns or regressions identified.

@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 a623af0 into FutureTense:main Nov 9, 2026
7 checks passed
@firstof9
firstof9 deleted the fix/855-slot-active-ha-timezone branch November 9, 2026 20:38
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.

ISSUE: Day-of-week and time-of-day limits use the container clock instead of HA's configured time zone

4 participants