fix(persistence): back off a failed save and time both configs in 32 bits

After a failed save due() stayed true on every loop iteration, so a full or
failing filesystem was opened, truncated and removed at firmware-loop speed.
LazySave now has three named operations: clear() for a confirmed write,
retryLater() to stay dirty but wait out another full delay, and reset() to drop
pending work when a reload or a reset-to-defaults supersedes it. load() calls
reset() in both configs, so an edit cannot outlive the file it was meant for.

Timestamps are uint32_t with elapsed time computed in uint32_t. The host's
unsigned long is 64-bit, so writing these fields as unsigned long meant host
tests could not model the wrap the MCU actually has — the wrap tests below were
meaningless before this change.

Battery sampling no longer stores an absolute deadline with 0 as an
"unarmed" sentinel, which conflated a wrapped deadline with an unarmed timer.
It keeps last_sample_ms plus an explicit sample_pending, samples at most once per
loop (never twice to catch up missed intervals), arms on the first loop, re-arms
when thresholds are set or the gate is enabled, and disarms when it is turned
off. The two-consecutive-reading debounce and the immediate first sample are
unchanged; only resume still takes a single reading, as before.

The native shim gained the fault injection R16 anticipated: fail_open, fail_write
and a write-open attempt counter, so the retry cadence is asserted rather than
inferred from whether a file appeared.

Note: PlatformIO does not track the force-included NativeShim.h as a
dependency, so a change to a struct it defines can leave stale test objects.
Cleaning the two native envs before running is the reliable path.

341 cases green across all four envs, 287 clean under sanitizers, Xiao_S3_WIO and
RAK_4631 compile with RAM unchanged at 20.6%.
This commit is contained in:
Jason Huebert committed 2026-10-03 13:29:42 -05:00
1 parent faee91272c
commit e152803eea
7 files changed
+274 -18

No files matched your search

+16 -8
View File
@@ -31,7 +31,8 @@ void BatteryGate::resetToDefaults() {
resume_mV = 0;
low_count = 0;
drops = 0;
next_sample_at = 0; // sample immediately on the first loop()
last_sample_ms = millis();
sample_pending = true; // sample immediately on the first loop()
}
BatteryGate::BatteryGate() {
@@ -50,7 +51,9 @@ void BatteryGate::setEnabled(bool on) {
if (!on) {
suspended = false;
low_count = 0;
next_sample_at = 0;
sample_pending = false; // disarmed; re-armed for the next enable
} else {
sample_pending = true; // evaluate the restored thresholds promptly
}
}
@@ -60,7 +63,7 @@ bool BatteryGate::setThresholds(uint16_t suspend, uint16_t resume) {
suspend_mV = suspend;
resume_mV = resume;
low_count = 0;
next_sample_at = 0; // re-evaluate immediately on the next loop()
sample_pending = true; // re-evaluate immediately on the next loop()
enabled = true;
markDirty();
return true;
@@ -86,9 +89,11 @@ void BatteryGate::sample(mesh::MainBoard& board) {
void BatteryGate::loop(FILESYSTEM* fs, mesh::MainBoard& board) {
if (enabled) {
unsigned long now = millis();
if (next_sample_at == 0 || (long)(now - next_sample_at) >= 0) {
next_sample_at = now + BATT_SAMPLE_INTERVAL_MS;
const uint32_t now = millis();
// one sample per loop, never two to catch up missed intervals
if (sample_pending || (uint32_t)(now - last_sample_ms) >= BATT_SAMPLE_INTERVAL_MS) {
last_sample_ms = now;
sample_pending = false;
sample(board);
}
}
@@ -97,6 +102,7 @@ void BatteryGate::loop(FILESYSTEM* fs, mesh::MainBoard& board) {
void BatteryGate::load(FILESYSTEM* fs) {
resetToDefaults(); // the file decides everything below; nothing survives from before
save_flag.reset(); // a reload supersedes any edit still waiting to be written
if (!fs->exists(BATT_CFG_FILE)) return;
File file = fsOpenRead(fs, BATT_CFG_FILE);
@@ -128,7 +134,7 @@ void BatteryGate::load(FILESYSTEM* fs) {
void BatteryGate::save(FILESYSTEM* fs) {
File file = fsOpenWrite(fs, BATT_CFG_FILE);
if (!file) return; // keep the dirty flag: the write is retried by loop()
if (!file) { save_flag.retryLater(); return; } // wait out another delay before retrying
uint8_t rec[BATT_CFG_RECORD_BYTES];
rec[0] = BATT_CFG_VERSION;
rec[1] = enabled ? 1 : 0;
@@ -136,8 +142,10 @@ void BatteryGate::save(FILESYSTEM* fs) {
memcpy(&rec[4], &resume_mV, 2);
bool ok = (file.write(rec, BATT_CFG_RECORD_BYTES) == BATT_CFG_RECORD_BYTES);
file.close();
// only once the config is actually on disk: a failed write stays pending
// only once the config is actually on disk: a failed write stays pending, but
// backs off a full delay instead of retrying on every loop
if (ok) save_flag.clear();
else save_flag.retryLater();
}
// ---------------------------------------------------------------- CLI
+7 -1
View File
@@ -38,7 +38,13 @@ class BatteryGate {
uint16_t resume_mV; // resume when voltage rises to this (hysteresis)
uint8_t low_count; // consecutive low readings (debounce)
uint32_t drops; // packets gated while suspended (RAM-only)
unsigned long next_sample_at;
// Sampling schedule: an explicit "sample next loop" flag plus the time of the
// last sample. A deadline stored as an absolute millis() value cannot tell a
// wrapped deadline from an unarmed timer, and 0 as a sentinel conflates the
// two. uint32_t (not unsigned long) so host tests model the MCU's 32-bit
// millis() wrap.
uint32_t last_sample_ms;
bool sample_pending;
LazySave save_flag; // needs save, written back by loop()
public:
+6 -3
View File
@@ -679,6 +679,7 @@ static bool validChannel(const FilterChannel* c) {
void FilterRules::load(FILESYSTEM* fs) {
resetToDefaults(); // the file decides everything below; nothing survives from before
save_flag.reset(); // a reload supersedes any edit still waiting to be written
if (!fs->exists(FILTER_CFG_FILE)) return;
File file = fsOpenRead(fs, FILTER_CFG_FILE);
@@ -770,7 +771,7 @@ void FilterRules::load(FILESYSTEM* fs) {
void FilterRules::save(FILESYSTEM* fs) {
File file = fsOpenWrite(fs, FILTER_CFG_FILE);
if (!file) return; // keep the dirty flag: the write is retried by loop()
if (!file) { save_flag.retryLater(); return; } // wait out another delay before retrying
uint8_t hdr[5];
hdr[0] = FILTER_CFG_VERSION;
hdr[1] = enabled ? 1 : 0;
@@ -784,11 +785,13 @@ void FilterRules::save(FILESYSTEM* fs) {
ok = (file.write((uint8_t*)&rules[i], FILTER_RULE_PERSIST_BYTES) == FILTER_RULE_PERSIST_BYTES);
}
for (int i = 0; ok && i < num_channels; i++) {
ok = (file.write((uint8_t*)&channels[i], sizeof(FilterChannel)) == sizeof(FilterChannel));
ok = (file.write((uint8_t*)&channels[i], FILTER_CHAN_PERSIST_BYTES) == FILTER_CHAN_PERSIST_BYTES);
}
file.close();
// only once the config is actually on disk: a failed write stays pending
// only once the config is actually on disk: a failed write stays pending, but
// backs off a full delay instead of retrying on every loop
if (ok) save_flag.clear();
else save_flag.retryLater();
}
// ---------------------------------------------------------------- CLI
+19 -4
View File
@@ -16,16 +16,31 @@
// costs one flash write instead of one per edit.
#define LAZY_SAVE_DELAY_MS 3000
// Dirty flag plus write-back timer for one persisted config. Clear it only
// after the config has actually been written (see Config::save callers).
// Dirty flag plus write-back timer for one persisted config.
//
// Elapsed time is computed in uint32_t so that a millis() wrap is handled for a
// full cycle. The host's `unsigned long` is 64-bit, so writing these fields as
// unsigned long would silently make host tests unable to model the wrap the MCU
// actually has.
class LazySave {
bool dirty;
unsigned long dirty_since;
uint32_t dirty_since;
public:
LazySave() : dirty(false), dirty_since(0) {}
void markDirty() { dirty = true; dirty_since = millis(); }
bool due() const { return dirty && millis() - dirty_since >= LAZY_SAVE_DELAY_MS; }
bool due() const { return dirty && (uint32_t)(millis() - dirty_since) >= LAZY_SAVE_DELAY_MS; }
// The config reached the disk. Only call this after a confirmed write.
void clear() { dirty = false; }
// A save attempt failed: stay dirty, but wait out another full delay before
// trying again. Without this, due() stays true on every loop iteration and a
// full or failing filesystem is opened and truncated at firmware-loop speed.
void retryLater() { if (dirty) dirty_since = millis(); }
// Forget pending work entirely — a reload or a reset-to-defaults, which must
// not inherit an edit the file no longer reflects.
void reset() { dirty = false; dirty_since = 0; }
};
// Config integrity is length-checked, not checksummed: a truncated file is
@@ -308,6 +308,125 @@ TEST_F(BatteryGateTest, RejectsOutOfRange) {
EXPECT_FALSE(gate.isEnabled());
}
// The schedule must not depend on an absolute deadline that a 32-bit millis()
// wrap could collide with, and must take exactly one sample per loop.
TEST_F(BatteryGateTest, FirstSampleHappensOnceNotOncePerLoop) {
board.mV = 100; // very low: first sample is low #1
gate.setThresholds(3400, 3600);
gate.loop(&fs, board);
EXPECT_FALSE(gate.isSuspended()); // one reading is not enough
// looping again in the same instant must NOT immediately take low #2: the
// gate waits out the interval rather than sampling twice to catch up
gate.loop(&fs, board);
EXPECT_FALSE(gate.isSuspended());
EXPECT_EQ(gate.getDropCount(), 0u);
}
TEST_F(BatteryGateTest, SamplingSurvivesAMillisWrap) {
gate.setThresholds(3400, 3600);
g_mock_millis = 0xFFFFF000u; // ~4 s before UINT32_MAX
board.mV = 100;
gate.loop(&fs, board); // immediate sample: low #1
g_mock_millis = 0xFFFFFFFFu;
board.mV = 4000;
gate.loop(&fs, board); // no interval elapsed: no sample, so low #1 stands
g_mock_millis += 1; // wrapped to 0
gate.loop(&fs, board);
EXPECT_FALSE(gate.isSuspended());
// 30 s measured across the wrap: the good reading lands as low #2, which
// resets the debounce rather than suspending
g_mock_millis += SAMPLE_INTERVAL_MS;
board.mV = 4000;
gate.loop(&fs, board);
EXPECT_FALSE(gate.isSuspended());
// ... and two lows in a row across the wrap still suspend
g_mock_millis += SAMPLE_INTERVAL_MS;
board.mV = 100;
gate.loop(&fs, board);
g_mock_millis += SAMPLE_INTERVAL_MS;
gate.loop(&fs, board);
EXPECT_TRUE(gate.isSuspended());
}
TEST_F(BatteryGateTest, OffDisarmsSamplingAndEnableRearmsIt) {
gate.setThresholds(3400, 3600);
EXPECT_TRUE(gate.isEnabled());
gate.setEnabled(false);
board.mV = 100;
for (int i = 0; i < 5; i++) { g_mock_millis += SAMPLE_INTERVAL_MS; gate.loop(&fs, board); }
EXPECT_FALSE(gate.isSuspended()); // disarmed: no sampling while off
// re-enabling re-arms and evaluates promptly, without waiting out an interval
gate.setEnabled(true);
gate.loop(&fs, board); // low #1
EXPECT_FALSE(gate.isSuspended());
g_mock_millis += SAMPLE_INTERVAL_MS;
gate.loop(&fs, board); // low #2
EXPECT_TRUE(gate.isSuspended());
}
TEST_F(BatteryGateTest, ReArmingThresholdsClearsSuspensionAndDebounce) {
board.mV = 100;
gate.setThresholds(3400, 3600);
gate.loop(&fs, board);
g_mock_millis += SAMPLE_INTERVAL_MS;
gate.loop(&fs, board);
ASSERT_TRUE(gate.isSuspended());
// the battery recovers and the thresholds are re-armed around a healthy
// voltage: the gate must be re-evaluated on the next sample rather than left
// suspended until the next interval
board.mV = 4000;
EXPECT_EQ(cli(gate, board, "1000 2000").substr(0, 3), "OK ");
EXPECT_TRUE(gate.isSuspended()); // not cleared by the command alone...
gate.loop(&fs, board);
EXPECT_FALSE(gate.isSuspended()); // ...the next sample confirms recovery
// ... and a low reading now trips again, needing two consecutive readings as
// before, with the old debounce state cleared by re-arming
board.mV = 100;
g_mock_millis += SAMPLE_INTERVAL_MS;
gate.loop(&fs, board); // low #1
EXPECT_FALSE(gate.isSuspended());
g_mock_millis += SAMPLE_INTERVAL_MS;
gate.loop(&fs, board); // low #2
EXPECT_TRUE(gate.isSuspended());
}
TEST_F(BatteryGateTest, FailedSaveRetriesSlowlyNotEveryLoop) {
gate.setThresholds(3400, 3700);
NativeFS broken;
broken.fail_open = true; // every open for writing fails
g_mock_millis = CFG_SAVE_DELAY_MS;
for (int i = 0; i < 100; i++) gate.loop(&broken, board);
// 100 loops in the same instant must NOT mean 100 open attempts
EXPECT_LE(broken.write_open_attempts, 1u);
EXPECT_FALSE(broken.exists(BATT_CFG_FILE));
// the edit is still pending, so it lands once the filesystem recovers
g_mock_millis += CFG_SAVE_DELAY_MS;
gate.loop(&fs, board);
EXPECT_TRUE(fs.exists(BATT_CFG_FILE));
}
TEST_F(BatteryGateTest, ReloadCancelsPendingEdits) {
gate.setThresholds(3400, 3700);
gate.markDirty();
g_mock_millis = CFG_SAVE_DELAY_MS;
gate.load(&fs); // nothing on disk: defaults, and no resurrected pre-load edit
gate.loop(&fs, board);
EXPECT_FALSE(fs.exists(BATT_CFG_FILE));
}
// ============================================================
// PERSISTENCE
// ============================================================
+20 -2
View File
@@ -29,6 +29,7 @@ public:
std::vector<uint8_t>* backing = nullptr;
size_t pos = 0;
bool valid = false;
bool fs_fail_write = false; // set from the owning store's fail_write
operator bool() const { return valid; }
@@ -44,7 +45,7 @@ public:
}
size_t write(const uint8_t* buf, size_t len) {
if (backing == nullptr) return 0;
if (backing == nullptr || fs_fail_write) return 0;
backing->insert(backing->end(), buf, buf + len);
pos = backing->size(); // append-only shim: the handle ends up at EOF
return len;
@@ -63,21 +64,35 @@ public:
void remove(const char* path) { files.erase(path); }
void mkdir(const char*) {}
// Fault injection for the persistence tests: a real filesystem can fail to
// open or to write, and the retry/recovery paths must be exercised, not
// assumed. Off by default so every other test sees a working store.
bool fail_open = false; // open() for writing returns an invalid handle
bool fail_write = false; // write() accepts nothing
// how many times a write-open was attempted, so a test can see the retry
// cadence rather than infer it from whether a file appeared
size_t write_open_attempts = 0;
// truncate a file to `keep` bytes after a successful open+write, modelling a
// power loss partway through the record
size_t truncate_to = SIZE_MAX;
NativeFile open(const char* path) {
NativeFile f;
auto it = files.find(path);
if (it != files.end()) { f.backing = &it->second; f.valid = true; }
return f;
}
// Arduino (RP2040) flavour: "r" reads, "w" creates/truncates. Honouring the
// mode is what lets a test exercise the RP2040 open paths.
NativeFile open(const char* path, const char* mode) {
if (mode != nullptr && mode[0] == 'w') {
write_open_attempts++;
if (fail_open) return NativeFile();
files[path].clear();
NativeFile f;
f.backing = &files[path];
f.valid = true;
f.fs_fail_write = fail_write;
return f;
}
return open(path);
@@ -93,10 +108,13 @@ public:
// Arduino (ESP32) flavour: open(..., "w", true) truncates/creates.
NativeFile open(const char* path, const char* mode, bool truncate) {
write_open_attempts++;
if (fail_open) return NativeFile(); // nothing written: an invalid handle
files[path].clear();
NativeFile f;
f.backing = &files[path];
f.valid = true;
f.fs_fail_write = fail_write;
return f;
}
};
@@ -1811,6 +1811,93 @@ TEST_F(FilterTest, RuleReferencingAnAbsentChannelIsConfinedNotWidened) {
EXPECT_NE(r2.getRule(0)->chan_flags & FILTER_CHANFLG_MASK_SET, 0); // still set, matches nothing
}
// A failed save must stay pending but back off: due() staying true on every
// loop would reopen and truncate the file at firmware-loop speed.
TEST_F(FilterTest, FailedSaveRetriesSlowlyNotEveryLoop) {
filter.addRule();
filter.markDirty();
NativeFS broken;
broken.fail_open = true; // every open for writing fails
g_mock_millis = CFG_SAVE_DELAY_MS;
for (int i = 0; i < 100; i++) filter.loop(&broken); // high loop frequency
// 100 loops in the same instant must NOT mean 100 open attempts: a failing
// filesystem used to be opened and truncated at firmware-loop speed
EXPECT_LE(broken.write_open_attempts, 1u);
EXPECT_FALSE(broken.exists(CFG_FILE));
// once the delay has passed again it tries again, and succeeds when it can
g_mock_millis += CFG_SAVE_DELAY_MS;
filter.loop(&fs);
EXPECT_TRUE(fs.exists(CFG_FILE));
EXPECT_GT(fs.files[CFG_FILE].size(), 0u);
}
TEST_F(FilterTest, FailedWriteKeepsTheEditPending) {
filter.addRule();
filter.markDirty();
NativeFS broken;
broken.fail_write = true; // opens fine, accepts nothing
g_mock_millis = CFG_SAVE_DELAY_MS;
filter.loop(&broken);
// a partial write must not be mistaken for a committed config
EXPECT_TRUE(broken.files[CFG_FILE].empty());
broken.fail_write = false;
g_mock_millis += CFG_SAVE_DELAY_MS;
filter.loop(&broken);
EXPECT_GT(broken.files[CFG_FILE].size(), 0u);
}
TEST_F(FilterTest, RetryDelaySurvivesAMillisWrap) {
// stamp an edit just before the 32-bit wrap, then let the delay elapse across
// it: the retry must still become due exactly once the delay has passed, and
// not before — the elapsed time has to be computed in 32 bits
filter.addRule();
g_mock_millis = 0xFFFFFF00u; // ~256 ms before UINT32_MAX
filter.markDirty(); // the edit is stamped just before the wrap
g_mock_millis = 0xFFFFFFFFu;
filter.loop(&fs); // 255 ms elapsed: still inside the delay
EXPECT_FALSE(fs.exists(CFG_FILE));
g_mock_millis += 1; // wrapped to 0
filter.loop(&fs);
EXPECT_FALSE(fs.exists(CFG_FILE)); // 256 ms: still inside the delay
g_mock_millis += CFG_SAVE_DELAY_MS; // now past it, measured across the wrap
filter.loop(&fs);
EXPECT_TRUE(fs.exists(CFG_FILE));
}
TEST_F(FilterTest, ReloadCancelsPendingEdits) {
filter.addRule();
filter.markDirty();
g_mock_millis = CFG_SAVE_DELAY_MS;
filter.load(&fs); // the file decides everything; a pending edit must not survive it
filter.loop(&fs);
EXPECT_FALSE(fs.exists(CFG_FILE)); // nothing resurrected a pre-load edit
}
TEST_F(FilterTest, DebounceAndWrapBoundaries) {
filter.addRule();
filter.markDirty();
g_mock_millis = 0;
filter.loop(&fs);
EXPECT_FALSE(fs.exists(CFG_FILE)); // 0 ms: inside the debounce
g_mock_millis = CFG_SAVE_DELAY_MS - 1;
filter.loop(&fs);
EXPECT_FALSE(fs.exists(CFG_FILE)); // one millisecond short
g_mock_millis += 1;
filter.loop(&fs);
EXPECT_TRUE(fs.exists(CFG_FILE)); // exactly the delay
}
TEST_F(FilterTest, UnknownConfigVersionDiscarded) {
filter.addRule();
filter.setEnabled(false);