fix(TimeKeeper): guard NTP sync against reconnect storms and bad readings

Field units on unstable internet had RTC time drift wildly (10 min to
half a day), while units with stable internet stayed accurate. Root
cause: syncTimeWithNTP() wrote getLocalTime()'s result straight to the
RTC with no plausibility check, and fires on every WiFi reconnect
(not a fixed schedule) — so flaky links produced far more unguarded
sync attempts than healthy ones. The underlying configTime()/
getLocalTime() API has no request/response correlation, so a stale
reply from an abandoned attempt could be picked up by a later
attempt's window if reconnects outpaced a single attempt's ~5s resolve
time.

Three layers of defense, all in TimeKeeper:
- In-flight de-dup guard (ntpSyncInProgress) so only one sync attempt
  is ever listening at a time, closing the window a stale reply could
  land in.
- 10s cooldown between attempts to throttle reconnect storms.
- commitNtpResult(): corrections under 2 minutes commit immediately
  (normal drift); anything larger is held as a pending candidate and
  only written to the RTC once 3 consecutive syncs agree within 5s of
  each other, so a single bad reading can no longer move the clock by
  hours.

Documented in TimeKeeper/README.md under "NTP sync safety".
This commit is contained in:
2026-07-20 09:08:05 +03:00
parent f41332a771
commit e89a1b623f
3 changed files with 166 additions and 15 deletions
+51 -1
View File
@@ -18,7 +18,7 @@ TimeKeeper is the timekeeping and scheduling subsystem for Vesper. It owns the D
| `void setTime(unsigned long timestamp)` | Sets the RTC from a UTC Unix timestamp. Applies the timezone offset from ConfigManager before writing to the RTC. Reloads today's events afterward. |
| `void setTimeWithLocalTimestamp(unsigned long localTimestamp)` | Sets the RTC directly from a pre-offset (local) Unix timestamp. No additional timezone conversion is applied. Used by ClockHandler when the caller has already computed the local time. |
| `unsigned long getTime()` | Returns the current RTC time as a Unix timestamp. Returns 0 if the RTC is not running. |
| `void syncTimeWithNTP()` | Calls `configTime()` + `getLocalTime()` with a 5-second timeout. On success, writes the result to the RTC and reloads events. Silently skips if network is unavailable. |
| `void syncTimeWithNTP()` | Calls `configTime()` + `getLocalTime()` with a 5-second timeout. Guards against overlapping/rapid-fire attempts (see "NTP sync safety" below), then runs the result through `commitNtpResult()` before writing the RTC and reloading events. Silently skips if network is unavailable. |
| `void loadTodaysEvents()` | Reads `/events/events.json` from SD and populates the internal event list for the current date. Handles `single`, `weekly`, and `monthly` event types. |
| `void loadNextDayEvents()` | Stub — pre-loads tomorrow's events for smooth midnight transitions. Not yet implemented. |
| `void pauseClockUpdates()` | Pauses physical clock motor advancement (sets internal flag). |
@@ -68,6 +68,56 @@ NTP sync is not triggered by `begin()`. It is deferred to a one-shot FreeRTOS ti
---
## NTP sync safety (bugfix)
**Background.** Field units with unstable internet were observed to have RTC time off by
anywhere from ~10 minutes to half a day, while units with stable internet stayed accurate
indefinitely. Root cause: `syncTimeWithNTP()` wrote whatever `getLocalTime()` returned
straight to the RTC via `rtc.adjust()`, with no plausibility check and no protection
against overlapping sync attempts. On a flaky link, `ntpSyncTimerCallback` (`main.cpp`)
fires on **every** WiFi reconnect — not on a fixed schedule — so an unstable connection
produces far more sync attempts than a healthy one, and each attempt was an unguarded
write straight to the RTC. Because the Arduino `configTime()`/`getLocalTime()` API has no
request/response correlation (a reply is accepted as valid based only on "does the system
clock look set", not "is this the reply to the request I just sent"), a stale or delayed
reply from an earlier, already-abandoned attempt could be picked up by a later attempt's
listening window if reconnects happened faster than a single attempt's ~5s resolve time.
This matches the reported symptom: random-magnitude jumps rather than a fixed offset.
**Fix — three layers in `syncTimeWithNTP()` / `commitNtpResult()`:**
1. **In-flight de-dup guard.** `ntpSyncInProgress` (atomic) rejects a new sync attempt if
one is already running. This is the primary fix for the missing request/response
correlation: since the underlying SNTP client can't tell attempts apart, the safest
fix is to never have more than one attempt in flight, so there's nothing for a stale
reply to collide with.
2. **Cooldown between attempts.** `lastNtpAttemptMs` enforces a minimum gap
(`NTP_MIN_RETRY_MS`, 10s) between sync attempts, independent of the de-dup guard. This
throttles reconnect storms on a flapping link so attempts don't stack up back-to-back.
3. **Plausibility + consensus gate (`commitNtpResult()`).** A result within
`NTP_JUMP_THRESHOLD_SEC` (2 minutes) of the current RTC value is committed immediately
— this is normal drift correction. A result that would jump the clock by more than
that is **not** written to the RTC on the first sighting. It is held as a pending
candidate, and only committed once `NTP_AGREE_REQUIRED` (3) consecutive sync attempts
agree with each other within `NTP_AGREE_TOLERANCE_SEC` (5s). A single bad/stale reply
can no longer move the clock by hours — it would have to be reproduced by three
independent syncs in a row. If the RTC is not running at all (dead battery, brand new
board), the first NTP result is trusted unconditionally since there is nothing
meaningful to compare it against.
**Tuning.** All four constants are `static constexpr` at the top of `TimeKeeper.cpp`.
Raising `NTP_AGREE_REQUIRED` or `NTP_AGREE_TOLERANCE_SEC` trades slower recovery from a
genuinely large clock error (e.g. after extended power-off) for stronger rejection of bad
readings. Lowering `NTP_JUMP_THRESHOLD_SEC` below normal RTC drift-per-sync-interval will
cause routine corrections to go through the consensus path unnecessarily.
**Consensus state does not persist across reboots or resets.** `pendingNtpEpoch` /
`pendingNtpAgreeCount` are in-RAM only. A device that reboots mid-consensus starts the
count over from zero on the next large-jump candidate. This is intentional — a fresh boot
has no reason to trust a partially-built consensus from before the restart.
---
## Gotchas / Notes
**Single FreeRTOS task.** Everything — physical clock sync, alerts, backlight automation, event scheduling, RTC health — runs in one task: `mainTimekeeperTask`, pinned to Core 1, priority 2, 4096-byte stack. The stack is shared with `fireAlertBell()`, which calls `vTaskDelay()` in a loop. Account for this when increasing ring counts or pulse durations.