Skip to content

rs485_bridge: socket header is 7 bytes, not 8 - #14

Merged
aphelps-claude-bot merged 2 commits into
base-wled-16.0.1from
pack-socket-headers
Jul 30, 2026
Merged

aphelps-claude-bot merged 2 commits into
base-wled-16.0.1from
pack-socket-headers

Conversation

@aphelps-claude-bot

@aphelps-claude-bot aphelps-claude-bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Collaborator

Paired with aphelps/ArduinoLibs#9, which packs rs485_socket_hdr_t so AVR and 32-bit targets agree on the wire. Merge that one first.

Why the constant was wrong

Unpacked, sizeof(rs485_socket_hdr_t) was 7 on an ATMega328 (alignment 1) but 8 here — and that size positions the payload at both ends of the link. So this bridge emitted [7 header][1 pad][payload] while a legacy module read the payload from offset 7, and read the bridge's frames one byte late in the other direction. Not a single frame could cross between the bridge and a real HMTL module. RS485B_SOCKET_HDR_LEN read 8 for exactly as long as that bug existed.

Why the existing guard didn't catch it

usermod_rs485_bridge.cpp:19 already asserts RS485B_SOCKET_HDR_LEN == sizeof(rs485_socket_hdr_t), and it does fire loudly — but only in [env:ampworks], which no CI workflow builds:

  • build.yml:33 derives its matrix from [platformio] default_envs → nodemcuv2 and friends
  • usermods.yml builds usermods_esp32*, where this usermod compiles to nothing

So it is a local guard, not an automated one. Hence the second change: assert RS485B_SOCKET_HDR_LEN == 7 in the host test's wire-layout group. That suite runs plain and under -fpack-struct=1, which makes it the only place the constant is checked on both ABIs by something that needs no ESP32 toolchain — and therefore the only automated coverage this constant has.

A build trap worth knowing about

Documented in the usermod readme, because it made my own verification lie.

lib_deps lists the ArduinoLibs directories by path, so PlatformIO copies them into .pio/libdeps/<env>/ and builds the copy, without reliably re-syncing when the source changes. pio run -e ampworks reported SUCCESS against a deliberately wrong constant, because it was compiling a cached pre-fix RS485Utils.h — the static_assert meant to catch exactly that mismatch never saw the new struct. touching the .cpp was not enough; only deleting the libdeps copy was:

rm -rf .pio/libdeps/ampworks/RS485Utils
pio run -e ampworks

Anyone who edits ArduinoLibs and then flashes a board can otherwise end up testing a binary that disagrees with the source in front of them. That matters most for the hardware bring-up session this unblocks, so it is called out in the readme as a pre-flash step rather than buried here.

Verification

  • host test passes natively and under -fpack-struct=1 — 19 groups, 120 CHECK sites
  • pio run -e ampworks fails on the static_assert with the constant left at 8, and succeeds at 7 (after clearing libdeps) — run deliberately in that order, since it is the cheapest proof the guard works rather than being decorative
  • pio run -e usermods still builds

🤖 Generated with Claude Code

https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ

Follows aphelps/ArduinoLibs, which packs rs485_socket_hdr_t so AVR and 32-bit
targets agree on the wire. Unpacked, sizeof() was 7 on an ATMega328 (alignment 1)
but 8 here, and that size positions the payload at both ends -- so this bridge
emitted [7 header][1 pad][payload] while a legacy module read the payload from
offset 7, and read the bridge's frames one byte late in the other direction. Not a
single frame could cross between the bridge and a real HMTL module. RS485B_SOCKET_HDR_LEN
read 8 for exactly as long as that bug existed.

The existing static_assert against the real struct (usermod_rs485_bridge.cpp:19)
does catch the mismatch, and does so loudly -- but only in [env:ampworks], which no
CI workflow builds: build.yml takes its matrix from [platformio] default_envs
(nodemcuv2 and friends) and usermods.yml builds the usermods_esp32* envs, where this
usermod compiles to nothing. So it is a local guard, not an automated one.

Hence the second change: assert RS485B_SOCKET_HDR_LEN == 7 in the host test's wire
layout group. That suite runs plain and again under -fpack-struct=1, which makes it
the only place the constant is checked on both ABIs by something that needs no ESP32
toolchain -- and therefore the only automated coverage this constant has.

Also documents a build-workflow trap found while verifying this, because it made the
verification lie. lib_deps lists the ArduinoLibs directories by path, so PlatformIO
copies them into .pio/libdeps/<env>/ and builds the copy without reliably re-syncing
it. `pio run -e ampworks` reported SUCCESS against a deliberately wrong constant
because it was compiling a cached pre-fix RS485Utils.h; touching the .cpp was not
enough, only deleting the libdeps copy was. Anyone who edits ArduinoLibs and then
flashes a board can otherwise end up testing a binary that disagrees with the source
in front of them -- which matters most for the hardware bring-up session this
unblocks.

Verified: host test passes natively and under -fpack-struct=1 (19 groups, 115
assertions); `pio run -e ampworks` FAILS on the static_assert with the constant left
at 8 and succeeds at 7, once libdeps is cleared; `pio run -e usermods` still builds.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ
`CHECK(RS485B_SOCKET_HDR_LEN == 7)` is 7 == 7. RS485B_SOCKET_HDR_LEN is a literal
#define in a header that deliberately does not include RS485Utils.h, so nothing in
that translation unit ever sees rs485_socket_hdr_t: the check was byte-identical
under -fpack-struct=1 and plain, and it stayed green with the packing attribute
deleted. It detected exactly one failure mode -- a hand-edit of the #define -- which
is not the one this change exists to prevent. Three comments (and the previous commit
message) claimed cross-ABI coverage on that basis; the claim was false.

Replaced with a packed replica of the declaration plus sizeof and offsetof checks
against it. Precise about what that buys, because it is not everything:

  * it DOES prove this field list, packed, is 7 bytes at these offsets under BOTH the
    native and the -fpack-struct=1 (AVR-like) ABI -- the cross-ABI property the wire
    format depends on -- and it fails if the packing is dropped. Verified: removing
    __attribute__((__packed__)) from the replica turns the suite red on the host.
  * it does NOT observe the real struct. Add a field there and the replica goes stale
    and stays green. The only check tying the constant to the real declaration is
    still usermod_rs485_bridge.cpp:19, which compiles solely in [env:ampworks].

The comments now say that instead of overstating it.

Also documents a pre-existing sizing bug the review turned up, without fixing it
here. static_assert(RS485B_TX_SLOT_LEN <= RS485_RECV_BUFFER) was commented "a queue
slot must be able to hold the largest frame the socket can carry", which is what it
does not check: the slot length is a PAYLOAD budget while RS485_RECV_BUFFER is the
TOTAL frame budget a receiver mallocs. A full 64-byte slot reaches the wire as 71
bytes and any peer on the default buffer -- including this bridge's own receive path
-- silently drops it. Real ceiling is 57 bytes of payload. No v1 traffic gets near it
(largest emitted frame is a 35-byte PROGRAM), but a WiFi client can submit 64, watch
rs485Tx increment, and see the frame vanish uncounted. That is the same symptom the
bring-up runbook attributes to the header-size mismatch, so it would have sent the
next debugger after an already-fixed bug. The comment now states the real arithmetic;
the fix is a behaviour choice (shrink the slot vs raise the buffer at a cost in AVR
SRAM) and is tracked as its own task rather than smuggled into a layout change.

Re-verified after these edits: host suite passes natively and under -fpack-struct=1
(120 CHECK sites), `pio run -e ampworks` SUCCESS with libdeps cleared, and the
ArduinoLibs assertion sweep still passes on all three toolchains with its negative
controls firing.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ
@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator Author

Self-review found the new test assert was worthless — fixed in 40d4ecd

Posting this rather than quietly amending, because the thing I got wrong is the part of this PR I was most confident about.

CHECK(RS485B_SOCKET_HDR_LEN == 7) is 7 == 7. RS485B_SOCKET_HDR_LEN is a literal #define in a header that deliberately does not include RS485Utils.h, so nothing in that translation unit ever sees rs485_socket_hdr_t. The check was byte-identical under -fpack-struct=1 and plain, and it stayed green with the packing attribute deleted. It detected exactly one failure mode — someone hand-editing the #define — which is not the one this PR exists to prevent. Three comments and the first commit message claimed cross-ABI coverage on that basis, and the claim was false.

Now a packed replica of the declaration plus sizeof/offsetof checks against it. Being precise about what that buys, since it isn't everything:

  • it does prove this field list, packed, is 7 bytes at these offsets under both the native and the -fpack-struct=1 ABI — the cross-ABI property the wire format depends on — and it fails if the packing is dropped. Verified by removing the attribute from the replica: suite goes red on the host.
  • it does not observe the real struct. Add a field there and the replica goes stale and stays green. The only check tying the constant to the real declaration is still usermod_rs485_bridge.cpp:19, which compiles solely in [env:ampworks].

The comments now say that instead of overstating it.

A pre-existing sizing bug the review turned up — documented, not fixed here

static_assert(RS485B_TX_SLOT_LEN <= RS485_RECV_BUFFER) was commented "a queue slot must be able to hold the largest frame the socket can carry", which is precisely what it does not check. RS485B_TX_SLOT_LEN is a payload budget; RS485_RECV_BUFFER is the total frame budget a receiver mallocs (recvLimit → the channel's bufferSize_). So a full 64-byte slot reaches the wire as 71 bytes and any peer on the default buffer — including this bridge's own receive path — silently drops it (RS485_non_blocking.cpp:199-205 calls reset() and bumps only an internal errorCount_ nobody reads). The real ceiling is 57 bytes of payload.

No v1 traffic gets near it — the largest frame the bridge emits is a 35-byte PROGRAM — but a WiFi client can submit 64, watch rs485Tx increment, and see the frame vanish uncounted. That is the same symptom the bring-up runbook attributes to the header-size mismatch this PR fixes, so left alone it would have sent the next debugger after an already-fixed bug. Pre-existing: 72-vs-64 before this PR, 71-vs-64 after.

Not fixed here because the remedy is a behaviour choice — shrink the slot to 57, or raise RS485_RECV_BUFFER at a cost in SRAM on every AVR module — and this PR is a pure layout change. Tracked as its own task; the comment now states the real arithmetic, and the runbook's step 6 lists it as a distinct cause.

Also from the review, addressed

  • ArduinoLibs/README.md claimed the packed-and-asserted guarantee for "all three header structs" in a way that reads repo-wide. TCPSocket's tcp_socket_msg_t is unpacked and carries no assertions — no hazard today (ESP32-only, so it never meets an AVR peer) but the README now says so rather than implying coverage. Fixed in ArduinoLibs f4afaab.
  • The first commit message's "115 assertions" was a miscount (the grep matched the #define CHECK too). It is 120 CHECK sites after this change. Corrected in the PR body; the commit message stands, since rewriting it would mean a force-push.

Re-verified after all of the above: host suite passes natively and under -fpack-struct=1; pio run -e ampworks SUCCESS with libdeps cleared; the ArduinoLibs assertion sweep still passes on all three toolchains with every negative control firing.

@aphelps-claude-bot
aphelps-claude-bot merged commit 3c11ec1 into base-wled-16.0.1 Jul 30, 2026
52 checks passed
@aphelps-claude-bot
aphelps-claude-bot deleted the pack-socket-headers branch July 30, 2026 02:09
aphelps-claude-bot added a commit to aphelps/WLED_dev that referenced this pull request Jul 30, 2026
…rget) (#24)

* bump ArduinoLibs + WLED: pack the RS485 socket header (7B on every target)

Both pointers move in ONE commit deliberately. rs485_socket_hdr_t goes from an
unpacked struct (7 bytes on AVR, 8 on ESP32) to a packed 7 everywhere, and
RS485B_SOCKET_HDR_LEN follows it from 8 to 7. Any intermediate state with one side
advanced fails `pio run -e ampworks` at the static_assert in
usermod_rs485_bridge.cpp:19 -- which is the build the hardware bring-up depends on.

What this unblocks: until now the rs485_bridge usermod could not exchange a single
frame with a real HMTL module. sizeof(rs485_socket_hdr_t) positions the payload at
both ends, so the ESP32 emitted [7 header][1 pad][payload] while an ATMega328 read
the payload from offset 7, and vice versa -- every frame misparsed by one byte, in
both directions. The bench session for the bridge was blocked on this and nothing
else.

  aphelps/ArduinoLibs#9 -- pack rs485/xbee/rfm69 socket headers + static_assert sweep
  aphelps/WLED#14       -- RS485B_SOCKET_HDR_LEN 8 -> 7, host-test coverage, readme

Submodule PRs merge first; this pointer pair is re-pointed at the merged shas before
this PR lands.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ

* bump submodules: self-review fixes on the socket-header stack

ArduinoLibs f4afaab -- README scopes the packing guarantee and names TCPSocket as
not covered.
WLED 40d4ecdf -- the new host-test assert was tautological (7 == 7, green even with
the packing attribute removed); replaced with a packed replica plus offsetof checks
that actually fail, and the three comments that overclaimed cross-ABI coverage now
say what the check can and cannot see. Also documents a pre-existing sizing bug the
review surfaced: a full 64-byte TX slot goes on the wire as 71 bytes and overflows a
default 64-byte receive buffer, so the real payload ceiling is 57. Filed separately
rather than fixed here.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ

* re-point submodules at the merged socket-header packing commits

ArduinoLibs d047ce2 (#9) -- pack rs485/xbee/rfm69 socket headers + assertion sweep
WLED 3c11ec16 (#14)     -- RS485B_SOCKET_HDR_LEN 8 -> 7, host-test coverage, readme

Both squash-merged, so this replaces the branch-tip pointers this PR opened with.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ

---------

Co-authored-by: aphelps-claude-bot <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
aphelps-claude-bot added a commit that referenced this pull request Jul 30, 2026
…f writing it down (#16)

* rs485_bridge: the payload ceiling is 57, not 64 — derive it instead of writing it down

RS485_RECV_BUFFER (64) is the budget for the whole FRAME, socket header included.
RS485B_TX_SLOT_LEN was hardcoded to the same number but means a PAYLOAD, so a full slot
reached the wire as 64 + 7 = 71 bytes and overflowed every peer on the default buffer --
including this bridge's own receive path. RS485_non_blocking discards the frame and
bumps only an internal counter nobody read, so a WiFi client could submit 64 bytes,
watch rs485Tx increment, and see it vanish with nothing recorded anywhere.

The real ceiling is 57. Nothing in the v1 command set came close -- the largest frame
the bridge emits is a 23-byte poll response -- but the UDP ingress path accepted up to
the slot length, so it was reachable from a client, and the symptom ("tx increments,
module saw nothing") is identical to the socket-header bug fixed in #14. Left alone it
would have sent the next person at the bench after settled code.

Rather than change 64 to 57, the slot is now DERIVED:

  RS485B_TX_SLOT_LEN = RS485B_RECV_BUFFER_LEN - RS485B_SOCKET_HDR_LEN

which makes this class of error structurally impossible rather than fixed once. That
matters here specifically: this is the third defect in this subsystem whose root cause
was a constant describing one thing compared against a constant describing another
(payload vs total frame here, AVR vs 32-bit struct size in the header, poll-request vs
poll-response in the ACK handling).

The old guard was `RS485B_TX_SLOT_LEN <= RS485_RECV_BUFFER`, which passed at 64 <= 64
while the property it claimed was false. It now includes the header. It is true by
construction and therefore cannot fail -- kept only to stop the slot being hardcoded
again, and the comment says so instead of pretending it is coverage. The ceiling is
pinned where it CAN fail: an absolute 57/58 pair in the ingress test here (every other
check in that group uses the constant symbolically, which follows the number wherever
it goes and pins nothing), and a 57-delivered / 58-dropped boundary group in
ArduinoLibs' receive-path suite.

UDP_BUF_LEN is now RS485B_RECV_BUFFER_LEN, deliberately one header LARGER than a slot.
Sized to the slot, a 58..64-byte payload would be truncated by udp.read() and miscounted
as RS485B_ERR_SHORT; read whole, it is refused as RS485B_ERR_OVERSIZE, which is the
countable rejection worth having. Costs 7 bytes of stack.

Also surfaces the framing counter from the paired ArduinoLibs change in the info row
(with buf3 grown 80 -> 128, since five counters plus the literal already ran close
enough that snprintf_P would have truncated silently), corrects the rate-limit
arithmetic in three places (a max frame is 64 B total -> ~132 wire bytes -> ~47 ms, not
"a 64-byte payload -> 135 -> 48 ms"), and fixes the readme's ingress-cap bullet, which
stated the cap as the buffer size.

Verified: host suite passes natively and under -fpack-struct=1; `pio run -e ampworks`
and `-e usermods` both SUCCESS with libdeps cleared; and hardcoding the slot back to 64
FAILS the build on the new assert -- confirmed, because a guard that cannot fail is not
a guard.

Needs the paired aphelps/ArduinoLibs change for getFramingErrorCount().

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ

* address self-review: I claimed a guard that does not exist yet

Five findings, and the first is a false statement I put in a comment.

The assert tying RS485B_RECV_BUFFER_LEN to the real RS485_RECV_BUFFER said that
tools/rs485_bridge_probe.py --self-test cross-checks it too. It does not -- the probe
pins the HMTL header and struct sizes and has never looked at either buffer constant.
That check is queued for the parent pointer bump, so the claim was true of the plan and
false of the code.

The consequence is the same shape as the bug being fixed. That assert compiles only
under [env:ampworks], which no CI workflow builds, so the mirror has NO automated guard
at all right now: raise RS485_RECV_BUFFER in ArduinoLibs and the slot stays at 57 with
CI green and the bus quietly under-used; lower it and the 71-vs-64 silent drop comes
straight back. The comment now says that plainly instead of pointing at a check that
isn't there.

Added the guard that CAN fail, in-class because UDP_BUF_LEN is private:

  static_assert(UDP_BUF_LEN >= RS485B_TX_SLOT_LEN + RS485B_SOCKET_HDR_LEN)

Reverting UDP_BUF_LEN to the slot length is an obvious-looking simplification that
would silently make RS485B_ERR_OVERSIZE unreachable -- a 58..64-byte payload would be
truncated by udp.read() and miscounted as short, which is precisely the behaviour this
change exists to remove. Verified it fails the build when reverted.

Two comments were left contradicting the change: the one directly above
buf[UDP_BUF_LEN] still said truncation was intentional "because nothing bigger than a
transmit slot can be forwarded", and the maxPayload doc said initBuffer() "handed back"
the size. initBuffer() returns an offset POINTER and enforces no size -- its data_size
argument only feeds a debug print -- so the bound actually lives in rawTxBuf's own
dimension. A reader following that comment would have gone looking in the wrong place.

Also: the poll response advertises recv_buffer_size 64, which is the whole-frame budget
and not the sendable payload, so a master that treats it as a payload size and sends 64
gets ERR_OVERSIZE from the node that advertised it. That conflation is in the HMTL wire
format, so the value stays -- but it is now labelled in both the code and the readme's
message table rather than left as a trap. The readme's info-page section also still
described a four-bucket dropped row; it has six, and the two new ones needed the
caveats spelled out.

Two host tests added, both in CI's reach where the ampworks assert is not: the
slot/header/budget relationship checked against a real packed struct rather than the
mirrored literal, and a 64-byte datagram carrying a valid 40-byte frame plus trailing
junk -- confirming "read more than a slot" is not mistaken for "forward more than a
slot", which is a path that only exists now that UDP_BUF_LEN is 64.

Reconciled the frame-size figures while here: 23 bytes is the largest frame the bridge
emits, 43 the largest it can relay (MSG_MAX_SZ), and the "35-byte PROGRAM" in earlier
notes was sizeof(msg_program_t) without its header.

Verified: host suite green on both ABIs, ampworks and usermods both build, and both new
asserts fail the build when their invariant is broken.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ

---------

Co-authored-by: aphelps-claude-bot <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
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