Skip to content

follow-up: harden RP2350W peer OTA flow from #3863 #3956

Description

@zackees

Source PR: #3863

Source comments:

Why this matters: current peer-OTA success accounting and HTTP framing can report success for a failed transfer, while a blocking download can exceed the RP2350W watchdog window and an out-of-range port can silently target the wrong endpoint.

CodeRabbit suggestions (verbatim):

Guard the servedRequests conversion.

int(served.get(servedRequests, 0)) raises ValueError or TypeError when the device returns a non-numeric value. Neither exception is in the handler tuple at Line 161, so the run aborts with a traceback instead of the failure message.

Feed the watchdog during the blocking OTA download.

pollOtaArtifactUpdate calls HTTPUpdate::update(client, ...) synchronously, but loop() only feeds FastLED.watchdog() at scope start/end via FL_WATCHDG_AUTO(AUTORESEARCH_WATCHDOG_TIMEOUT_MS). A full firmware download can exceed the configured 5000 ms timeout and reset the board mid-upgrade. Disable the watchdog for this update or register an HTTPUpdate progress callback that calls FastLED.watchdog().feed().

Count only served requests that deliver the artifact.

serveOtaArtifact increments served_requests before it opens the file. A 404 response then still counts. run_ota_peer_autoresearch treats servedRequests >= 1 as proof that the RP2350W downloaded the image, so a failed download can pass the check. Increment the counter after the transfer completes.

Don’t add Content-Length to a chunked OTA response.

httpd_resp_send_chunk sends HTTP responses as chunked transfer encoding. Setting Content-Length adds conflicting OTA framing, so use httpd_resp_send with the full buffer instead, or confirm this Arduino-Pico OTA client accepts chunked responses for the active core version.

Reject port values outside the uint16_t range.

static_cast<uint16_t>(port) truncates. A request with port: 70000 becomes port 4464 and the update targets the wrong endpoint. Validate the upper bound too.

Acceptance criteria:

  • RED: focused host tests show malformed/non-numeric servedRequests is reported as a controlled failure and a 404/partial artifact response cannot satisfy served-transfer proof.
  • GREEN: validate status types explicitly and increment served_requests only after a complete successful response.
  • RED: a focused request test shows ports <= 0 and > 65535 are rejected before narrowing.
  • GREEN: accept only the full uint16_t endpoint range without truncation.
  • RED: a focused OTA transport repro exercises an update lasting longer than the 5-second watchdog interval and the current conflicting Content-Length/chunked response framing.
  • GREEN: keep the watchdog fed (or safely disable/restore it) during the blocking update and emit one standards-compliant framing mode supported by the pinned Arduino-Pico HTTPUpdate client.
  • Preserve cleanup on read/send/update failure and add deterministic tests for success, 404, partial-send, malformed status, timeout/watchdog, and framing behavior.
  • Run focused tests, strict lint, RP2350W and ESP32-C6 builds, then prove OTA build-marker, reboot, CDC/network recovery, and serial RPC health on hardware.

Activity

  1. zackees commented on Aug 21, 2026

    @zackees
    MemberAuthor

    Landed via #3961 (a03fa0b30b). All five CodeRabbit findings addressed.

    Done

    • Success accounting — serveOtaArtifact incremented served_requests before opening the artifact, so a 404 or a mid-transfer send failure still counted, and the host's servedRequests >= 1 proof passed on a transfer that never happened. The counter now bumps only after the final chunk is accepted.
    • Truncated bodies no longer look complete — the failure path returns ESP_FAIL without a terminating zero chunk. A zero-length chunk is precisely the "body ended normally" signal, so emitting one after a failed read presented a half-written firmware image as a well-formed response.
    • Watchdog — pollOtaArtifactUpdate now halts the counter with disable() across the blocking download and re-arms to the sketch timeout immediately after.
    • Port range — new fl::net::tryParsePort (src/fl/net/port.h) accepts exactly [1, 65535]. Both applyOtaArtifact and runNetClientTest route through it; the latter previously had no range check at all.
    • Status parsing — servedRequests parsing is now total. Anything that is not a plain non-negative int reads as zero and surfaces as the ordinary failure instead of a ValueError/TypeError traceback. bool is excluded explicitly, since it is an int subclass and True would otherwise have counted as one served request. The artifact-server port reply is range-checked too.

    One finding resolved differently than suggested — worth recording

    The suggestion to drop Content-Length from the chunked response carried the caveat "or confirm this Arduino-Pico OTA client accepts chunked responses for the active core version." Confirmed against the pinned core (rp2040-5.7.0): it does not. HTTPClient::_size is initialised to -1 and only ever assigned from a Content-Length header (HTTPClient.cpp:1111), and HTTPUpdate requires len > 0 or fails with HTTP_UE_SERVER_NOT_REPORT_SIZE (HTTPUpdate.cpp:232, :295). Removing the header would have made every applyOtaArtifact fail with "Server did not report size". The client decodes the chunked body but takes the image size from Content-Length, so both are required and the header stays, now documented in-place with that evidence.

    Related: re-arming the watchdog with a longer timeout is not viable on this silicon — Watchdog::begin() clamps to FL_WATCHDOG_MAX_TIMEOUT_MS, which is 16777 ms on RP2350 (watchdog_rp.impl.hpp:47, :111) because the counter is 24-bit microseconds. Hence disable()/re-arm rather than a widened window.

    Verification: 283/283 host unit tests (new tests/fl/net/port.cpp pinning the 65536/65537/70000/74001 truncation boundaries), 16 cases in ci/tests/test_ota_peer_hardening.py, 930 Python tests overall, bash lint clean, rp2350w and esp32c6 builds green, and the new port must be in [1, 65535] string confirmed present in the linked rp2350w firmware.

    Still open — why this issue is not closed

    The final bullet asks to prove OTA build-marker, reboot, CDC/network recovery and serial RPC health on hardware. No RP2350W is attached to this bench, so none of the above is validated on-device — only by host tests and target builds. Leaving open for that HIL pass.

  2. zackees commented on Sep 7, 2026

    @zackees
    MemberAuthor

    The hardware clause on this issue is now unblocked.

    The bench fixture is confirmed a Raspberry Pi Pico 2 W — live evidence, not the historical record:

    2e8a:f00f  'Pico 2W'                                  # rpipico2w application CDC (2E8A:F00F)
    status     -> platform: "Raspberry Pi Pico 2 W (RP2350)"
    wifiStatus -> {"status":"IDLE","success":true}        # UNSUPPORTED on the non-W build
    

    Until now the variant was unestablished, so the W-only acceptance criteria here could not be attempted at all. They can be run now:

    • bash autoresearch rp2350w --rpc-smoke — PASS (71 RPC methods, dual-core concurrency 200/200)
    • bash autoresearch rp2350w --net-peer — deploys both boards; six full cycles of wifiConnect → join the C6 SoftAP → startNetServer → bidirectional HTTP → stopNet → ping

    Deploying the W build onto a board running non-W firmware needs --upload-port — fbuild refuses to guess which board to BOOTSEL and fails clean without flashing.

    One known blocker for long soaks: #4173 — the RP2350W hangs in wifiConnect on the 7th consecutive peer cycle and watchdog-resets. It self-recovers, so it limits repetition rather than stranding the fixture.

    Generated with Claude Code

    https://claude.ai/code/session_01KkufoNxfnNRU9psT3R9F51

  3. zackees commented on Sep 7, 2026

    @zackees
    MemberAuthor

    Hardware criterion attempted — peer OTA never reaches the transfer

    The blocker on this issue's last criterion ("prove OTA build-marker, reboot, CDC/network recovery, and serial RPC health on hardware") was that the fixture's variant was unproven. That is resolved — it is a Pico 2 W (2E8A:F00F, status.platform "Raspberry Pi Pico 2 W (RP2350)"). So --net-peer --ota can now be run. It fails before any OTA work happens.

    Symptom

    Reproducible across two runs with a clean daemon state:

    deploy succeeded (full flash); FBUILD_DEPLOY_PORT=/dev/ttyACM1   [RP2350W, 21.7s]
    deploy succeeded (full flash); FBUILD_DEPLOY_PORT=/dev/ttyACM0   [ESP32-C6, 66.6s]
    ✅ Fetched schema: 71 methods
    OTA PEER AUTORESEARCH: RP2350W <- ESP32-C6
    OTA peer autoresearch failed: No response with ID 1 within 20.0s
    

    ID 1 is the first request on the primary client — the status call at ci/autoresearch/ota.py:110, before beginOtaArtifact. So none of the artifact staging, framing, or served-counter logic from #3961 is exercised; the run dies at the handshake.

    The device is healthy

    Queried immediately after the failure, over the same port:

    RP ping   -> {"message":"pong","success":true,"uptimeMs":130563,
                  "lastResetCause":"SOFTWARE","lastResetWasWatchdog":false}
    RP status -> {"ready":true,"platform":"Raspberry Pi Pico 2 W (RP2350)","rpcReady":true}
    

    Not a watchdog reset, not a crash, and status — the exact call that timed out — answers immediately. The schema fetch had also just succeeded against this board, so RPC was working seconds before.

    What is not the cause

    The delta is --ota specifically: different firmware on both boards, and a C6 deploy that takes ~67 s between the RP's flash and the first RPC.

    Suggested next step

    Someone with the fixture should instrument between primary.connect() and the first rpc_data(primary, "status") in run_ota_peer_autoresearch — the device is provably reachable on either side of that window, so the handshake itself is where it goes wrong. A longer boot_wait, or reconnecting rather than reusing the pre-attached serial_iface, are the obvious things to try.

    Environment: NixOS 6.18.48, fbuild 2.5.23, RP2350W 2E8A:F00F on /dev/ttyACM1, ESP32-C6 303A:1001 on /dev/ttyACM0.

    Generated with Claude Code

    https://claude.ai/code/session_01KkufoNxfnNRU9psT3R9F51

  4. zackees commented on Sep 7, 2026

    @zackees
    MemberAuthor

    Correction to my previous comment — wrong board, and wrong about the cause

    Two things I got wrong above, both now settled by instrumenting the handshake.

    1. It is the ESP32-C6 that fails, not the RP2350W. I said ID 1 was the status call on primary. Adding a per-link ping with a bounded retry shows the RP2350W settles silently on its first ping and the C6 fails all three:

      ESP32-C6 did not answer ping (attempt 1/3): No response with ID 1 within 10.0s
      ESP32-C6 did not answer ping (attempt 2/3): No response with ID 2 within 10.0s
      ESP32-C6 did not answer ping (attempt 3/3): No response with ID 3 within 10.0s
    

    The original error, No response with ID 1 within 20.0s, names neither the board nor the call, which is how I misattributed it.

    2. The fbuild fd leak IS implicated. I first blamed FastLED/fbuild#1426, then retracted that because a pre-flight check found no process holding either port. The retraction was wrong: the leak is created by the run's own C6 deploy, so checking beforehand cannot rule it out. Immediately after the failure:

    holder pid=544820 comm=fbuild-daemon   # holding /dev/ttyACM0
    

    Four distinct fbuild-daemon pids did this across today's runs (414394, 434691, 544820, 551628). Each leaves the port EBUSY for the next client on a board that stays enumerated and healthy.

    Why --net-peer works but --net-peer --ota does not

    It looks like a race with deploy duration:

    Mode C6 deploy Result
    --net-peer 96.5 s 6 full cycles, bidirectional HTTP
    --net-peer --ota 25.7 s C6 unreachable at the first RPC

    The shorter OTA-mode deploy means the leaked handle is still live when the RPC client connects. That also explains why this looked like an OTA-logic fault when it is a serial-lifetime one.

    Remaining unknown

    After killing the holder, the C6 answers ping with null rather than timing out — channel healthy, device returning nothing — while running the OTA-fixture firmware. The standard esp32c6 AutoResearch build passes RPC smoke on the same board immediately afterwards. That may be a second, separate issue in the OTA fixture; I have not characterised it and am not claiming it is the same bug.

    Status

    #3961's hardening still has not been exercised on silicon — the run dies at the handshake, before beginOtaArtifact. Unblocking it most likely depends on FastLED/fbuild#1426 rather than on anything in this issue's own scope.

    Both boards are healthy and back to known-good builds.

    Generated with Claude Code

    https://claude.ai/code/session_01KkufoNxfnNRU9psT3R9F51

  5. zackees commented on Sep 7, 2026

    @zackees
    MemberAuthor

    Status check on this issue's code items — most are already landed. I re-read the review comments against current master rather than assuming, and four of five are addressed:

    CodeRabbit item state
    Guard the servedRequests conversion done — ci/autoresearch/ota.py:33 documents the ValueError/TypeError fix
    Count only served requests that deliver the artifact done — ++served_requests now runs after httpd_resp_send_chunk(request, nullptr, 0) returns
    Feed the watchdog during the blocking OTA download done — pollOtaArtifactUpdate(uint32_t watchdog_restore_ms) feeds FastLED.watchdog(), with a note on the 24-bit hardware counter
    Reject port values outside uint16_t done — fl::net::tryParsePort(), comment cites this issue and the 70000 -> 4464 wrap
    Don't add Content-Length to a chunked response deliberately kept, with justification

    On the last one: Content-Length is retained alongside chunked framing, and the code comment cites HTTPClient.cpp:1111 and HTTPUpdate.cpp:232/:295 showing the pinned Arduino-Pico client requires the header to size the image, even though the body streams chunked. That is a reasoned resolution of the review comment rather than an oversight, and it matches this issue's own GREEN criterion ("emit one standards-compliant framing mode supported by the pinned Arduino-Pico HTTPUpdate client").

    The hardware-proof criterion is what remains, and my attempt at it wedged the peer. Recording it because it is a real hazard for anyone running this next.

    bash autoresearch rp2350w --net-peer --ota --peer-environment esp32c6 reflashes both boards, then failed at the first step:

    OTA PEER AUTORESEARCH: RP2350W <- ESP32-C6
      ESP32-C6 did not answer ping (attempt 1/3): No response with ID 1 within 10.0s
      ESP32-C6 did not answer ping (attempt 2/3): ...
      ESP32-C6 did not answer ping (attempt 3/3): ...
    OTA peer autoresearch failed: ESP32-C6 did not answer ping after 3 attempts
    

    The C6 was then unopenable:

    open_port(/dev/ttyACM2) exceeded 3s; serial driver may be wedged
    

    Diagnosis, in order — and two of my three initial reads were wrong:

    1. Not the board's USB. Device node and by-id link both present and fresh.
    2. The fbuild daemon had died — fbuild-daemon <defunct> plus Connection refused on its WebSocket. fbuild daemon restart fixed the transport.
    3. Then EBUSY with no holder. A /proc/*/fd scan found no process holding /dev/ttyACM2, so this was the kernel cdc_acm side, not userspace. fbuild daemon locks showed no port locks either.
    4. No recovery handle available — usbfs path not writable, authorized/unbind/remove all root-only, no passwordless sudo. I could not reset it.
    5. It cleared on its own after roughly two minutes, and a reflash through fbuild deploy brought it fully back: Chip type: ESP32-C6FH4 (QFN32), RESULT: RPC smoke PASS.

    Both boards are healthy now.

    Practical warning for this criterion: the peer-OTA flow reflashes the fixture as well as the DUT, and the C6 has no watchdog/bootloader escape armed the way the RP2350W does (#4167/#4172). If the C6's CDC wedges mid-run on an unattended bench, there is no software path back without root — a USB reset needs privileges this account does not have. Worth either arming an escape on the fixture, or gating this run behind the PPPS-capable hub tracked in #3713/#3714.

    The hardware-proof criterion is therefore still open. I am not going to retry it unattended without one of those mitigations in place.

  6. 11 remaining items

  7. zackees commented on Sep 10, 2026

    @zackees
    MemberAuthor

    Located: truncated requests are discarded without a reply

    Traced the device-side receive path. createSerialRequestSource() in src/fl/remote/transport/serial.h reads a line and then:

    // Only parse if input starts with '{'
    if (view.empty() || view[0] != '{') {
        return fl::nullopt;
    }
    
    fl::string input(view);
    return fl::json::parse(input);

    Returning fl::nullopt means "no request available" — indistinguishable to Server::pull() from an idle link. So a line that arrives damaged is dropped with no response, no error, and no log. That is precisely the observed symptom: the host transmits all 735 bytes, the device replies with nothing at all, and the next RPC answers in 0.07 s.

    Worth noting what is not the limit: readStringUntil() in src/fl/system/serial.cpp.hpp has no size cap. It accumulates until the delimiter or a 1 s idle timeout, resetting the timer on every byte. So nothing in the line reader truncates at 512.

    That leaves the RX buffer as the place bytes go missing. AutoResearch.ino already anticipates this and calls Serial.setRxBufferSize(4096) before serial_begin(), with the correct ordering and a comment naming this exact hazard — yet the measured cliff sits right where the default 256-byte HWCDC queue would put it once framing is added. Whether that call takes effect on the C6's HWCDC is the thing to check next; I have not verified it, and it is a one-line experiment for someone with the part in front of them.

    Why this cost so much to find

    The two defects compound. Bytes go missing silently, and then the damaged line is discarded silently. Neither layer says anything, so the failure presents as "the device stopped answering this one method" — which is what sent this investigation through port locks, CDC re-enumeration, partition tables, and firmware identity before arriving here.

    Suggested fix, independent of the buffer question: when a line arrives that does not parse, respond. Even a JSON-RPC parse error with a null id, or a single FL_WARN naming the length received, would have made this immediate. A receive path that can only succeed or vanish is very expensive to debug from the far end of a serial link.

    Summary for this issue

    Layer Finding
    Attach undersized app0, 20.6 KB overflow — fixed (#4276)
    Transport request delivered in full; 735 bytes out, 0 back
    Receive truncated/non-{ lines return nullopt — silently dropped
    Line reader no size cap; not the limiter
    RX buffer prime suspect; setRxBufferSize(4096) is called with correct ordering, effect on HWCDC unverified
    Cost ~318 ms per RPC, size-independent — chunk size is the only lever on transfer time
  8. moved this from Triage to Done in FastLED Trackeron Sep 10, 2026
  9. zackees commented on Sep 10, 2026

    @zackees
    MemberAuthor

    Reopening the substance: I closed this prematurely, and there were four more layers

    I closed this as completed at 15:00 today after root-causing the 512-byte chunk limit. That was wrong. Clearing that limit only revealed the next failure, and clearing that revealed the next. Peer OTA still does not complete. #4318 fixes what I could verify.

    The layers, in the order they surfaced

    # failure status
    1 512-byte chunks base64-expand past the device's measured 428-char request limit worked around locally; see below
    2 startOtaArtifactServer → Artifact HTTP server start failed fixed, verified
    3 Artifact write failed at byte 200448 on every run after the first fixed, verified
    4 servedRequests: 0 with no reason recorded anywhere fixed, verified
    5 Update error: ERROR[4]: Not Enough Space on the RP fixed; not verified end to end

    2 — control-socket collision. HTTPD_DEFAULT_CONFIG() hardcodes .ctrl_port = ESP_HTTPD_DEF_CTRL_PORT (32768, confirmed in the IDF header). startNetServer runs immediately before, and fl::asio::http::Server::start() takes the same default, so the second httpd_start binds a control socket the first owns. A distinct server_port does not help — which is why 8081-vs-80 looked sufficient.

    3 — the fixture filesystem cannot hold two artifacts. finishOtaArtifact drops the old /rp2350.bin only after the new one verifies. Partition 0x130000 = 1,245,184 B; image = 1,030,348 B; headroom = 214,836 B; observed failure at byte 200,448, the difference being LittleFS block overhead. That arithmetic is what reconciled two runs I nearly wrote off as contradictory — run 1 hit a blank filesystem and transferred all 1,030,348 bytes with a matching SHA-256, run 2 inherited run 1's artifact and died 200 KB in.

    4 — the reason was being written to a closed port. The RP does explain itself via FL_WARN("[OTA] RP2350W artifact update failed: ..."), but pollOtaArtifactUpdate runs from loop() after the harness deliberately closes the RPC link so the board can reboot. A failed fetch and a fetch that never ran produced byte-identical evidence. rpOtaUpdateStatus now carries the outcome back.

    5 — and it paid off immediately. First run with the probe:

    'attempted': True, 'succeeded': False, 'host': '192.168.4.1', 'port': 8081,
    'lastError': 'Update error: ERROR[4]: Not Enough Space'
    

    Arduino-Pico stages an incoming image into the filesystem region — Updater.cpp:101 rejects when &_FS_start + size > &_FS_end, :121 sets updateStartAddress = &_FS_start. board_build_filesystem_size was 0.5m = 524,288 B against a 1,030,348 B image. Raised to 2m.

    Worth flagging for anyone else touching this: only the sizes rpipico2w declares in boards.txt are selectable (0, 64K, 128K, 256K, 512K, 1M, 2M, 3M), because fbuild matches the string against menu.flash.<flash>_<fs>. An unmatched value does not error — it yields fs_start == fs_end, and the build dies much later inside PicoOTA.cpp as the comparison reduces to '(0 > 130048)'. I lost a cycle to 1.5m exactly that way. 2M over 1M because 1M is 1,048,576 B against a 1,030,348 B image — an 18 KB margin the next commit to this sketch would erase.

    On the chunk size

    The preflight still refuses 512, so the flow cannot run unedited. But the choice was never binary:

    raw base64 round trips ~time at 318 ms
    256 344 4,025 21.3 min
    318 424 3,241 17.2 min
    512 684 — refused (>428)

    318 encodes to 424 characters, inside the 428 the device is measured to answer. I have not landed this — the constant was set to 512 deliberately when both known candidates failed, and reversing that is a call to make on evidence rather than inside a bug fix. But "both values fail" is not the whole option space.

    What is not verified

    Layer 5 is argued from the device's own error message, the arduino-pico source, and the arithmetic — not from a green run. Every attempt after it was killed mid-run by this bench's memory monitor, five times. The 2m build compiles, deploys and passes --rpc-smoke; 1.5m reproducibly fails the assert. The fetch past that point remains unproven, and I would rather say so than imply a pass I do not have.

    Separately, No response with ID 1 within 20.0s cost me four wrong hypotheses before I found _connect_peer_with_retry's docstring already describing it as a race on the C6's CDC re-enumeration, captured four times previously. #4318 makes that error name the board, the port and the method.

  10. zackees commented on Sep 10, 2026

    @zackees
    MemberAuthor

    Reopening: the flow does not complete. I closed this after explaining one blocker; four more sat behind it. Two are fixed and verified, one is fixed but unverified end to end, and the chunk-size preflight still refuses the committed value. Detail in the comment above; fixes in #4318.

  11. moved this from Done to Triage in FastLED Trackeron Sep 10, 2026
  12. moved this from Triage to Done in FastLED Trackeron Sep 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions