Skip to content

fix(modbus): share one TCP session per endpoint and name eviction wars - #987

Merged
frahlg merged 1 commit into
masterfrom
986-single-modbus-session
Aug 29, 2026
Merged

frahlg merged 1 commit into
masterfrom
986-single-modbus-session

Conversation

@frahlg

@frahlg frahlg commented Aug 29, 2026 •

Copy link
Copy Markdown
Member

Closes #986.

What

FTW could open competing Modbus TCP connections to a device it was already polling:

  • two configured drivers with the same host:port (a gateway fronting several unit IDs) each got their own socket;
  • the driver-test endpoint dials a throwaway registry with its own connection;
  • the fingerprint probe dials its own connection.

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.

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 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 in main.go and both API probes get the sharing for free.

Two observability changes ride along, both from the same incident:

  • Eviction-war warning. When the endpoint's session keeps being replaced (≥10 successful redials/min), a rate-limited WARN names the likely cause: another Modbus client fighting for the device's only session. The incident that motivated this ran 20–30 redials/min for months, invisibly; the same inverter alone peaks at 7–8/min from its own idle timeout, so 10 splits the two cleanly.
  • Log-flood stop. The per-dial modbus reconnected INFO line wrote ~17k lines into the log ring in 14 h. It is now rate-limited to once a minute per endpoint with a suppressed_repeats count.

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

  • New 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.
  • New TestNoteReconnectedRateLimitsAndDetectsEviction: warn threshold, warn re-arm after its interval, window pruning, INFO suppression counting.
  • Existing reconnect/backoff/mute-session suites updated to the shared-connection structure and passing unchanged in behavior.
  • make verify green.

🤖 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 / DialWithOptions now hand out lightweight Capability handles on a process-wide sharedConn per endpoint, with refcounted Close so driver tests and fingerprint probes do not drop the live driver’s session when they finish. Each handle keeps its own unit id; applyUnit sets 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 reconnected INFO is capped to once per minute with a suppressed_repeats count. Failed permanent dials no longer leave a dead registry entry for others to share.

Tests add TestDialSharesSingleConnectionPerEndpoint and eviction/log rate-limit coverage; existing reconnect/backoff tests are updated for the sharedConn split.

Reviewed by Cursor Bugbot for commit 10e46dd. Bugbot is set up for automated code reviews on this repo. Configure here.

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

chatgpt-codex-connector Bot commented Aug 29, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-08-29T06:21:17.708361Z 10e46dd PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: 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".

Comment on lines +243 to +245
if endpointConns[c.conn.addr] == c.conn {
delete(endpointConns, c.conn.addr)
}

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

Comment on lines +109 to +110
registryMu.Lock()
if existing := endpointConns[addr]; existing != nil {

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

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approved. Cursor Bugbot completed with no findings that need human review, and no approval policy requires extra review. No reviewers were assigned.

Open in Web View Automation 

Sent by Cursor Approval Agent: Pull Request Router and Approver

@frahlg
frahlg merged commit 0b85747 into master Aug 29, 2026
17 checks passed
cursor Bot pushed a commit that referenced this pull request Sep 11, 2026
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]>
@frahlg
frahlg deleted the 986-single-modbus-session branch November 11, 2026 09:11
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.

P0: guarantee at most one Modbus TCP connection per device endpoint, and detect session-eviction wars

1 participant