Repository navigation
fix(modbus): share one TCP session per endpoint and name eviction wars - #987
Conversation
FTW could open competing Modbus TCP connections to a device it was already polling: a second driver on the same gateway, the driver-test endpoint, and the fingerprint probe each dialed their own socket. Many inverters accept exactly one session and RST the previous one on every new connect, so each extra client evicted the production session mid-control. Dial now returns a handle on a process-wide shared connection per host:port. Handles carry their own unit id, program it per request, and serialize through the endpoint's one mutex and socket; the socket closes when the last handle is released, so a finished test or fingerprint probe no longer tears down the live driver's session. When something outside FTW keeps taking the device's only session, a rate-limited warning names the likely cause (calibrated against the 2026-08-29 incident: an abandoned experiment process redialed a Sungrow 20-30 times/min for months). The per-dial "modbus reconnected" INFO line is rate-limited to once a minute with a suppressed-repeat count — it wrote ~17k lines into the log ring in 14 h. Closes #986. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01C7xyXX1HYi2i1aax8EsCFx
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 10e46dd7e9
ℹ️ 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".
| if endpointConns[c.conn.addr] == c.conn { | ||
| delete(endpointConns, c.conn.addr) | ||
| } |
There was a problem hiding this comment.
Keep the endpoint registered until its socket is closed
When the last handle is closed concurrently with another Dial for the same endpoint, deleting this entry before acquiring conn.mu and closing the old socket allows the new dialer to register and open a second socket while the first remains live or has an in-flight request holding the mutex. On single-session devices, that new connection can reset the old request—the eviction this change is intended to prevent—so deregistration and final socket closure must be coordinated to prevent a replacement from opening early.
Useful? React with 👍 / 👎.
| registryMu.Lock() | ||
| if existing := endpointConns[addr]; existing != nil { |
There was a problem hiding this comment.
Canonicalize hosts before indexing shared sessions
When two configurations use equivalent spellings such as meter.local and METER.LOCAL., they resolve to the same endpoint but produce different addr keys here, so FTW still opens competing TCP sessions. This also affects probes whose host spelling differs from the live driver's configuration; normalize DNS names and IP literals before the registry lookup so equivalent endpoints share one entry.
Useful? React with 👍 / 👎.
Keep master's shared Modbus session (#987) and graft the LAN proxy onto it instead of a second pool. Resolve config/UI overlap with OCPP; drop the retired CalDAV comments. Signed-off-by: Cursor Agent <[email protected]> Co-authored-by: Fredrik Ahlgren <[email protected]>


Closes #986.
What
FTW could open competing Modbus TCP connections to a device it was already polling:
host:port(a gateway fronting several unit IDs) each got their own socket;Many inverters accept exactly one Modbus TCP session and RST the previous one ~2 ms after every new connect (verified with tcpdump on a live Sungrow hybrid on direct Ethernet). Each extra FTW-side client therefore evicted the production session mid-control.
Dialnow returns a handle on a process-wide shared connection perhost:port. Handles carry their own unit id, program it per request, and serialize through the endpoint's single mutex and socket. The socket closes when the last handle is released, so a finished test or fingerprint probe no longer tears down the live driver's session. The public surface (Dial,DialWithOptions,drivers.ModbusCap) is unchanged; the factory inmain.goand both API probes get the sharing for free.Two observability changes ride along, both from the same incident:
modbus reconnectedINFO line wrote ~17k lines into the log ring in 14 h. It is now rate-limited to once a minute per endpoint with asuppressed_repeatscount.Why now
Found while validating v2.3.0-beta.1 on a live site (2026-08-29): an abandoned experiment process on the same host had been stealing the inverter's only session since May. FTW recovered silently per request, so nothing surfaced until someone read raw logs. FTW cannot stop other processes from dialing the inverter, but it must never be the second client itself, and it should say out loud when someone else is.
Testing
TestDialSharesSingleConnectionPerEndpoint: two handles with different unit ids share exactly one device-side connection, unit ids are programmed per request, closing one handle leaves the other's session alive, closing the last deregisters the endpoint.TestNoteReconnectedRateLimitsAndDetectsEviction: warn threshold, warn re-arm after its interval, window pruning, INFO suppression counting.make verifygreen.🤖 Generated with Claude Code
https://claude.ai/code/session_01C7xyXX1HYi2i1aax8EsCFx
Note
Medium Risk
Changes the core Modbus connection lifecycle for all drivers (shared socket, ref counting, unit-id switching); mistakes could affect polling/control site-wide, though the public API is unchanged and new tests lock in the #986 contract.
Overview
FTW no longer opens multiple Modbus TCP sockets to the same
host:port.Dial/DialWithOptionsnow hand out lightweightCapabilityhandles on a process-widesharedConnper endpoint, with refcountedCloseso driver tests and fingerprint probes do not drop the live driver’s session when they finish. Each handle keeps its own unit id;applyUnitsets the wire id only when it changes, and all I/O still serializes on the shared mutex.Observability: frequent successful redials (≥10 in a minute) trigger a rate-limited WARN that another Modbus client may be competing for a single-session device;
modbus reconnectedINFO is capped to once per minute with asuppressed_repeatscount. Failed permanent dials no longer leave a dead registry entry for others to share.Tests add
TestDialSharesSingleConnectionPerEndpointand eviction/log rate-limit coverage; existing reconnect/backoff tests are updated for thesharedConnsplit.Reviewed by Cursor Bugbot for commit 10e46dd. Bugbot is set up for automated code reviews on this repo. Configure here.