Skip to content

fix(drivers): driver restart closes MQTT/Modbus caps + records health on Add - #95

Merged
frahlg merged 2 commits into
masterfrom
fix/driver-restart-cleans-mqtt-modbus
Apr 17, 2026
Merged

frahlg merged 2 commits into
masterfrom
fix/driver-restart-cleans-mqtt-modbus

Conversation

@frahlg

@frahlg frahlg commented Apr 17, 2026

Copy link
Copy Markdown
Member

Two foundational stability fixes prompted by tonight's incident on homelab-rpi where POST /api/drivers/ferroamp/restart left ferroamp silently dead until a full systemctl restart.

Root causes

1. MQTT session leak across restart. Registry.Remove tore down the Lua VM but never called Close() on the driver's MQTT capability. The stale paho client stayed connected to the broker under clientID ftw-<driver>. A subsequent Add dialed 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/eso messages never arrived, and bat_soc stayed missing while every tick just re-emitted the cached ehub reading.

2. Health records created lazily. tel.AllHealth() rows were only inserted on first RecordError or first emit. A freshly-added driver that was polling fine but waiting on slow MQTT telemetry was therefore absent from AllHealth, and /api/status rendered it as not_running: true, status: offline — indistinguishable from a crashed driver.

Changes

  • drivers.MQTTCap and drivers.ModbusCap gain Close() error.
  • mqtt.Capability.Close promoted from () to () error.
  • Registry.runLoop stop-path now closes both caps after DefaultMode + Cleanup.
  • Registry.Add eagerly creates a health record via DriverHealthMut.
  • runLoop records RecordSuccess() on every non-error poll, so idle-but-healthy drivers bump their TickCount.

Tests (new registry_restart_test.go)

  • TestRemoveClosesMQTTCap — Close count = 1 after Remove.
  • TestRemoveClosesModbusCap — same for Modbus.
  • TestRestartClosesOldMQTTBeforeDialingNew — three restart cycles, four factory calls, zero leaks.
  • TestAddCreatesHealthRecordImmediately — health visible the instant Add returns.
  • 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

frahlg and others added 2 commits April 17, 2026 19:41
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]>
@frahlg
frahlg merged commit d3a567e into master Apr 17, 2026
1 check passed
@frahlg
frahlg deleted the fix/driver-restart-cleans-mqtt-modbus branch April 17, 2026 18:06

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant