Repository navigation
fix(drivers): driver restart closes MQTT/Modbus caps + records health on Add - #95
Conversation
PR #93 was too aggressive: it treated every non-positive override as a config error, including intentional one-sided constraints. But `max_charge_w: 0` is a legitimate "forbid charging, allow discharge" directive that mpc.Optimize's action grid (`-MaxDischargeW…+MaxChargeW`) already supports. The fix was overriding operator intent. Only the both-zero case (charge and discharge both 0) stays treated as a config error — that leaves the planner with no action space and produces the empty plan that looked like "disabled" in the UI. One-sided zero passes through untouched; negative values still fall back to default 0.5C with a warning. Also fixes a second time-sensitive flake in TestSlotDirectiveAtDischarge that was anchored to a hardcoded wall-clock date (same root cause as the one fixed in #91). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two foundational stability fixes prompted by tonight's incident on
homelab-rpi where POST /api/drivers/ferroamp/restart left ferroamp in
a silent `not_running: true` state until a full systemctl restart.
Root cause 1: Registry.Remove tore down the runLoop + the Lua VM but
never closed the driver's MQTT capability. A subsequent Add dialled a
new paho client with the same clientID ("ftw-<driver>") while the old
client was still connected. The broker resolved the collision by
kicking the newer session on the next keepalive, and subscribe ACKs
to the new client raced with the old client's disconnect — net effect
was a driver whose subscriptions never activated, so extapi/data/eso
messages never arrived, bat_soc stayed missing, and every tick just
re-emitted the cached ehub reading.
Root cause 2: driver health records were created lazily — the first
RecordError (poll failure) or the first emit inserted a row in
tel.AllHealth(). A freshly-added driver that was polling fine but
hadn't received any MQTT data yet was therefore absent from AllHealth,
and /api/status rendered it as `not_running: true, status: offline`.
Same appearance as a crashed driver — operator couldn't tell them
apart.
Fix 1: add Close() error to the MQTTCap and ModbusCap interfaces;
runLoop now calls Close() on both caps during stop-path cleanup,
right after DefaultMode and Cleanup. mqtt/Capability.Close promoted
from () to () error to match.
Fix 2: Registry.Add eagerly calls tel.DriverHealthMut() so the record
exists before runLoop runs the first poll. runLoop also now calls
RecordSuccess() on every successful (non-error) poll — previously
only errors and emits bumped the tick count.
Tests (new registry_restart_test.go):
- TestRemoveClosesMQTTCap — Close call count = 1 after Remove.
- TestRemoveClosesModbusCap — same for Modbus.
- TestRestartClosesOldMQTTBeforeDialingNew — three restart cycles
each produce a fresh MQTT factory call; no cap leak.
- TestAddCreatesHealthRecordImmediately — health visible from the
instant Add returns, before runLoop has ticked.
- TestRunLoopRecordsSuccessEvenWithoutEmits — TickCount > 0 after
350ms of 50ms polls even though the driver emits nothing.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4df1e84147
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| // subscribe and the first inbound message). Without | ||
| // this, drivers that wait on slow telemetry topics | ||
| // are indistinguishable from ones that crashed. | ||
| r.tel.DriverHealthMut(rd.cfg.Name).RecordSuccess() |
There was a problem hiding this comment.
Stop treating poll success as telemetry success
Recording RecordSuccess() on every nil-error driver.Poll makes LastSuccess advance even when no telemetry was emitted, but WatchdogScan uses LastSuccess as its staleness signal. That means a driver can stop producing readings (for example, MQTT topic silent) yet remain permanently online as long as driver_poll keeps returning nil, so stale battery data can continue participating in dispatch instead of being watchdog-offlined.
Useful? React with 👍 / 👎.
| // arrived (which can be 30+ s for slow telemetry topics), and | ||
| // mis-presented an alive-but-waiting driver as a failed one. | ||
| if r.tel != nil { | ||
| r.tel.DriverHealthMut(cfg.Name) |
There was a problem hiding this comment.
Avoid creating "ok" health before first successful tick
Eagerly calling DriverHealthMut in Add creates a record with StatusOk but LastSuccess == nil; on the next WatchdogScan, that combination is immediately treated as stale and flipped offline, which triggers SendDefault before the first poll/emit has happened. On restarts (especially with longer poll intervals), this can spuriously drop a healthy starting driver into autonomous mode for one or more control cycles.
Useful? React with 👍 / 👎.
Two foundational stability fixes prompted by tonight's incident on homelab-rpi where
POST /api/drivers/ferroamp/restartleft ferroamp silently dead until a full systemctl restart.Root causes
1. MQTT session leak across restart.
Registry.Removetore down the Lua VM but never calledClose()on the driver's MQTT capability. The stale paho client stayed connected to the broker under clientIDftw-<driver>. A subsequentAdddialed a new client with the same ID — broker resolved the collision by kicking the newer one on the next keepalive, and subscribe ACKs to the new client raced with the old one's disconnect. Driver's subscriptions never activated,extapi/data/esomessages never arrived, andbat_socstayed missing while every tick just re-emitted the cachedehubreading.2. Health records created lazily.
tel.AllHealth()rows were only inserted on firstRecordErroror first emit. A freshly-added driver that was polling fine but waiting on slow MQTT telemetry was therefore absent from AllHealth, and/api/statusrendered it asnot_running: true, status: offline— indistinguishable from a crashed driver.Changes
drivers.MQTTCapanddrivers.ModbusCapgainClose() error.mqtt.Capability.Closepromoted from()to() error.Registry.runLoopstop-path now closes both caps afterDefaultMode+Cleanup.Registry.Addeagerly creates a health record viaDriverHealthMut.runLooprecordsRecordSuccess()on every non-error poll, so idle-but-healthy drivers bump their TickCount.Tests (new
registry_restart_test.go)TestRemoveClosesMQTTCap—Closecount = 1 afterRemove.TestRemoveClosesModbusCap— same for Modbus.TestRestartClosesOldMQTTBeforeDialingNew— three restart cycles, four factory calls, zero leaks.TestAddCreatesHealthRecordImmediately— health visible the instantAddreturns.TestRunLoopRecordsSuccessEvenWithoutEmits— TickCount > 0 for a driver that polls but never emits.Full
go test ./...green incl e2e (which uses real MQTT + Modbus caps, so the interface change is exercised end-to-end).🤖 Generated with Claude Code