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.
+95 -4
View File
@@ -8,6 +8,14 @@
#include "SD.h"
#include <time.h>
// ────────────────────────────────────────────────────────────────────────────
// NTP sync safety thresholds — see README.md "NTP sync safety"
// ────────────────────────────────────────────────────────────────────────────
static constexpr time_t NTP_JUMP_THRESHOLD_SEC = 120; // >2 min drift requires consensus
static constexpr uint8_t NTP_AGREE_REQUIRED = 3; // consecutive agreeing syncs needed
static constexpr time_t NTP_AGREE_TOLERANCE_SEC = 5; // candidates must agree within this
static constexpr unsigned long NTP_MIN_RETRY_MS = 10000; // cooldown between attempts
void Timekeeper::begin() {
LOG_INFO(TAG, "Timekeeper initialized - clock outputs managed by ConfigManager");
@@ -160,6 +168,29 @@ void Timekeeper::syncTimeWithNTP() {
return;
}
// De-dup guard: never allow two sync attempts in flight at once. Without this,
// rapid WiFi reconnects on a flaky link could each start their own configTime()
// call, and a stale reply from an earlier abandoned attempt could be read back
// during a later attempt's getLocalTime() window (there is no request/response
// correlation in the underlying SNTP client — see README.md "NTP sync safety").
bool expected = false;
if (!ntpSyncInProgress.compare_exchange_strong(expected, true)) {
LOG_INFO(TAG, "⏰ NTP sync already in progress - skipping overlapping attempt");
return;
}
// Cooldown: refuse to retry too soon after the previous attempt. This throttles
// reconnect storms so each attempt gets a clean, uncontested window instead of
// stacking up behind each other.
unsigned long now = millis();
if (lastNtpAttemptMs != 0 && (now - lastNtpAttemptMs) < NTP_MIN_RETRY_MS) {
LOG_INFO(TAG, "⏰ NTP sync attempted too soon after last try (%lu ms ago) - skipping",
now - lastNtpAttemptMs);
ntpSyncInProgress.store(false);
return;
}
lastNtpAttemptMs = now;
LOG_INFO(TAG, "⏰ Starting NTP sync (UTC-only, offsets applied manually)...");
// Get stored offsets from config — these are the only source of truth
@@ -178,13 +209,10 @@ void Timekeeper::syncTimeWithNTP() {
time_t utcEpoch = mktime(&utcTimeInfo);
time_t localEpoch = utcEpoch + totalOffsetSec;
if (commitNtpResult(localEpoch)) {
struct tm localTimeInfo;
gmtime_r(&localEpoch, &localTimeInfo);
// Write local time into RTC
rtc.adjust(DateTime(localTimeInfo.tm_year + 1900, localTimeInfo.tm_mon + 1, localTimeInfo.tm_mday,
localTimeInfo.tm_hour, localTimeInfo.tm_min, localTimeInfo.tm_sec));
LOG_INFO(TAG, "✅ NTP sync successful: UTC %04d-%02d-%02d %02d:%02d:%02d → Local %04d-%02d-%02d %02d:%02d:%02d (offset %+ld s)",
utcTimeInfo.tm_year + 1900, utcTimeInfo.tm_mon + 1, utcTimeInfo.tm_mday,
utcTimeInfo.tm_hour, utcTimeInfo.tm_min, utcTimeInfo.tm_sec,
@@ -194,10 +222,73 @@ void Timekeeper::syncTimeWithNTP() {
// Reload today's events since the time might have changed significantly
loadTodaysEvents();
}
// commitNtpResult() logs its own rejection/pending-consensus messages
} else {
// No internet or NTP server unreachable — this is NORMAL for local networks
LOG_INFO(TAG, "⚠️ NTP sync skipped (no internet) - using RTC time. This is normal for local networks.");
}
ntpSyncInProgress.store(false);
}
bool Timekeeper::commitNtpResult(time_t candidateLocalEpoch) {
// No existing RTC time to compare against (not running) — trust NTP outright,
// this is the "RTC lost power / brand new board" case.
if (!rtc.isrunning()) {
rtc.adjust(DateTime((uint32_t)candidateLocalEpoch));
pendingNtpAgreeCount = 0;
LOG_INFO(TAG, "⏰ RTC was not running - accepting NTP result unconditionally");
return true;
}
time_t rtcEpoch = (time_t)rtc.now().unixtime();
time_t drift = candidateLocalEpoch - rtcEpoch;
time_t absDrift = drift < 0 ? -drift : drift;
if (absDrift <= NTP_JUMP_THRESHOLD_SEC) {
// Small correction — normal drift compensation, commit immediately.
rtc.adjust(DateTime((uint32_t)candidateLocalEpoch));
pendingNtpAgreeCount = 0;
LOG_DEBUG(TAG, "⏰ NTP drift %+ld s within threshold - committing directly", (long)drift);
return true;
}
// Large jump (>NTP_JUMP_THRESHOLD_SEC) — do not trust a single reading. Require
// NTP_AGREE_REQUIRED consecutive attempts to agree with each other (within
// NTP_AGREE_TOLERANCE_SEC) before writing the RTC. This is what actually stops
// a single bad/stale reply from corrupting the clock — see README.md.
time_t agreeDrift = pendingNtpAgreeCount == 0
? 0
: (candidateLocalEpoch - pendingNtpEpoch);
time_t absAgreeDrift = agreeDrift < 0 ? -agreeDrift : agreeDrift;
if (pendingNtpAgreeCount == 0 || absAgreeDrift > NTP_AGREE_TOLERANCE_SEC) {
// First candidate of a new sequence, or this one disagrees with the running
// sequence — restart the consensus count from this reading.
pendingNtpEpoch = candidateLocalEpoch;
pendingNtpAgreeCount = 1;
LOG_WARNING(TAG, "⚠️ NTP result differs from RTC by %+ld s (>%ld s threshold) - "
"holding, need %d consecutive agreeing syncs (1/%d so far)",
(long)drift, (long)NTP_JUMP_THRESHOLD_SEC, NTP_AGREE_REQUIRED, NTP_AGREE_REQUIRED);
return false;
}
// Agrees with the pending candidate.
pendingNtpAgreeCount++;
LOG_WARNING(TAG, "⚠️ NTP large jump (%+ld s) candidate confirmed (%d/%d agreeing syncs)",
(long)drift, pendingNtpAgreeCount, NTP_AGREE_REQUIRED);
if (pendingNtpAgreeCount < NTP_AGREE_REQUIRED) {
return false;
}
// Consensus reached — commit.
rtc.adjust(DateTime((uint32_t)candidateLocalEpoch));
LOG_INFO(TAG, "✅ NTP large jump confirmed by %d consecutive syncs - committing %+ld s correction",
NTP_AGREE_REQUIRED, (long)drift);
pendingNtpAgreeCount = 0;
return true;
}
// ════════════════════════════════════════════════════════════════════════════
+10
View File
@@ -67,6 +67,13 @@ private:
// Backlight management - new functionality
bool backlightState = false; // Track current backlight state
// NTP sync guard state — prevents overlapping attempts and validates large jumps
// before trusting them. See README.md "NTP sync safety" for the full rationale.
std::atomic<bool> ntpSyncInProgress{false};
unsigned long lastNtpAttemptMs = 0; // millis() of the last attempt start, for cooldown
time_t pendingNtpEpoch = 0; // first candidate local epoch of a large-jump sequence
uint8_t pendingNtpAgreeCount = 0; // consecutive attempts that agreed with pendingNtpEpoch
// Clean dependencies
OutputManager* _outputManager = nullptr;
ConfigManager* _configManager = nullptr;
@@ -147,6 +154,9 @@ private:
void advancePhysicalClockOneMinute();
void updatePhysicalClockTime();
// NTP sync safety helpers
bool commitNtpResult(time_t candidateLocalEpoch);
// ═══════════════════════════════════════════════════════════════════════════════
// HEALTH CHECK METHOD
// ═══════════════════════════════════════════════════════════════════════════════