> Current policy: USB/serial-only provisioning. Network publishing, the update
> crate/key, second slot and journal were removed on 2026-09-10. Earlier update
> repair plans below are historical and superseded. See esp-hal-webfs.md.

# WebFS connection-failure and reset investigation

## Plan

Distinguish ESP32 reboots, TCP resets, refused connections, stalled requests,
and Wi-Fi loss using correlated client, packet, and serial evidence.

### Preserve and capture the baseline

Record source revision, artifact hashes, tool versions, device MAC/IP, and test
options. Capture TCP port 80 and ARP on the jail-facing interface and physical
uplink, including capture-drop statistics. Use one passive serial collector;
do not run reset tools or esptool during trials. Reproduce the original benchmark
before changing firmware. Probe recovery for 150 seconds before manual recovery.
Timestamp any deliberate reset separately.

### Instrument without changing behavior

Add boot/reset reason, firmware identity, uptime, Wi-Fi and DHCP events.
Record worker/connection IDs, remote endpoints, socket states, accept, mutex
wait/acquisition, completion, flush, close and drop. Preserve specific errors
and timeout distinctions. Use bounded event storage and rate-limited output
with overflow counts; never log secrets or request bodies. Compare instrumented
results against baseline to detect measurement effects. Trace a short failing
wrk run with truss to identify failing syscalls and errno values.

### Controlled experiments

Run three isolated 15-second trials at concurrency 1, 2, 4, 8, 16, 32 with
min(2, concurrency) threads and explicit two-second client timeout. Allow
recovery between trials; stop escalation after 150 seconds without recovery.
Compare sequential fresh connections. Test one, then four incomplete requests
alongside normal requests to expose mutex blocking and listener exhaustion.
Use a detailed client trace at the first reliably failing concurrency.

Correlate TCP tuples and timestamps with device events. A reboot requires a
new boot sequence/reset reason; serial disappearance is insufficient. Identify
RST direction and preceding exchange, refusal handshake, stalled worker state,
Wi-Fi events, and differences between jail and uplink captures. Once a cause
is reproduced, change one factor at a time: close completion, then mutex scope
if indicated. Keep general performance tuning separate.

### Completion and constraints

Document reproducible commands, measurements, trace paths, recovery times, and
evidence-backed failure timelines here and in esp-hal-webfs.md. Correct earlier
unsupported reset/error claims. Mark unresolved mechanisms and missing evidence
explicitly. Preserve baseline artifacts and diagnostic builds. Use only read-only
WebFS traffic; preserve the Linux jail, ZFS images, secrets, and datasets.

## Starting hypotheses

Four workers hold a shared mutex across network I/O. Workers flush, call close,
then immediately drop sockets; Embassy 0.9.1 removes dropped sockets from its
stack. Errors are currently collapsed or ignored. These are suspects, not
confirmed explanations. Existing benchmark results do not establish a reboot
or prove that manual reset was necessary.

## Investigation log

Plan saved before execution. Known device: MAC 90:70:69:ad:77:f4,
last IP 192.168.3.225, USB serial /dev/cuaU1. Jail: esp32c3. Capture points:
e0a_esp32c3 and re0, bridged by vm-public. Rediscover identities before testing.

### 2026-09-10: baseline and observer interference

Confirmed MAC from the jail ARP table and esptool: 90:70:69:ad:77:f4.
Device is ESP32-C3 revision 0.4 with 4 MiB flash, /dev/cuaU1. wrk is 4.2.0
(kqueue). Baseline checkout: ef8946c9074f7811833ad0496f3319b004bd29cb.
Baseline merged firmware SHA-256:
`c6c36775216e84514c20ba5b394bd66c662093ad7d0591e0f4377102272edf10`.

The first trial was invalidated by opening pyserial with DTR/RTS false at
13:55:57 UTC. Serial reported `rst:0x15 (USB_UART_CHIP_RESET)` and
`waiting for download`. This was observer-induced, not evidence of a load reboot.
The short monitor's HardReset did not restore service in this case;
esptool chip-id with its stub and hard-reset did. Firmware was unchanged then.

A second packet-only sweep ran without serial access or deliberate resets:

| Connections | Requests | Requests/s | Write errors | Timeout counter |
|---:|---:|---:|---:|---:|
| 1 | 991 | 65.87 | 0 | 0 |
| 4 | 1068 | 71.04 | 492 | 0 |
| 8 | 467 | 30.97 | 3397 | 8 |
| 16 | 228 | 15.11 | 5029 | 2 |
| 32 | startup refused | — | — | — |

The c16 interval also contained one unsuccessful traced connection attempt;
use the later isolated matrix for controlled comparisons. The immediate final
health check was refused, but a later check returned HTTP 200 without a reset.
This establishes recovery, not its exact duration.

Packets show SYN → device RST/ACK refusal and a separate reset after a complete
response during teardown. Not every RST means a failed response. A short truss
run recorded `write(...GET...) ERR#32 'Broken pipe'` after nonblocking connects
returned EINPROGRESS. Thus write errors can represent connection-establishment
failures discovered at write time despite connect=0. Truss timing was distorted;
do not use its throughput figures.

Evidence: `/tmp/webfs-diag/` contains baseline2.txt, baseline2-uplink.pcap,
baseline2-jail.pcap, packet-summary.txt, serial.txt, truss2-wrk.txt. The syscall
trace is `/tmp/webfs-truss2.txt` inside the jail. The full-flash backup
pre-diagnostic.bin contains secrets and is mode 600.

### Diagnostic firmware

Native build and flash verification succeeded. Diagnostic-v1 merged image hash:
`ff0deec073c4bc2f3c9e800d1aed64930cf483ffa3a272f83c8213a45534dae9`.
Application: 518,352 bytes; merged image: 583,888 bytes. Baseline artifacts are
preserved inside the jail at `/build/baseline-diag/`. Only the merged firmware
region was written; WebFS slots and journal were preserved.

The module keeps four worker snapshots, error counters and a 128-entry error
ring drained once per second with an overflow counter. Stages: 1 listening,
2 accepted, 3 mutex wait, 4 handler holds mutex, 5 success, 6 flush, 7 close/drop.
Errors: 1 accept, 2 handler I/O, 3 storage, 4 format, 5 handler deadline,
6 flush error, 7 flush deadline. Socket states use the pinned smoltcp State enum
values. Snapshots include connection ID, client port and stage-entry uptime.
These are sampled snapshots, not a complete per-request event trace.

`diagnostics/serial-raw.py` uses os.open/read without DTR/RTS ioctls. Attachment
preserved increasing application uptime and HTTP service. Opening serial is
still not guaranteed passive on other hosts. Initial boot output may be truncated.

Run the isolated matrix from the host:

```sh
python3.12 diagnostics/concurrency.py --host 192.168.3.225
```

Requests originate in esp32c3 using jexec, request gzip, include five seconds
settling and health checks, limit wrk wall time to 25 seconds, and stop after
150 seconds without recovery. `diagnostics/analyze-pcap.py CAPTURE` summarizes
Ethernet IPv4 TCP resets; it does not support VLAN frames or replace a full decoder.

The two stopped baseline captures each contain 37,974 matching TCP packets
(plus one other captured packet), comparing endpoints, sequence/ACK fields,
flags and frame length. Both tcpdump collectors reported zero kernel drops.
No packet loss between the jail-facing and physical uplink capture points was
observed. This does not measure losses between the access point and ESP32.

The installed version's [wrk 4.2.0 source](https://github.com/wg/wrk/blob/4.2.0/src/wrk.c)
counts response latency beyond its histogram range as `timeout`; this counter
is not a count of independently abandoned requests. It also explicitly reconnects
on responses that do not permit keep-alive. Keep these counters separate from
packet-level outcomes and avoid computing a failure percentage by adding them.

### Isolated diagnostic-v1 matrix

All 18 trials completed. No manual resets occurred within the matrix.

| Connections | Requests/s, three trials | Read errors | Write errors | Timeout counters |
|---:|---|---|---|---|
| 1 | 64.18, 64.42, 66.35 | 0, 0, 0 | 0, 0, 0 | 0, 0, 0 |
| 2 | 88.3, 88.05, 89.61 | 0, 0, 0 | 0, 0, 0 | 0, 0, 0 |
| 4 | 42.26, 47.41, 57.08 | 0, 0, 0 | 313, 257, 396 | 7, 3, 0 |
| 8 | 18.28, 30.03, 23.55 | 0, 0, 0 | 4320, 2681, 3009 | 12, 4, 3 |
| 16 | 15.46, 16.97, 13.25 | 207, 0, 0 | 4946, 4952, 5358 | 4, 4, 4 |
| 32 | 9.48, 8.55, 10.76 | 0, 0, 302 | 5479, 5809, 5229 | 8, 1, 5 |

Captured 415 heartbeats: uptime 14053–439178 ms; 0 decreases; maximum gap 1089 ms. Link-down samples: 0; maximum error-ring overflow: 0.

Immediate recovery probes occasionally failed. After c32 trial 1, probes at
14:06:21.789 and 14:06:23.813 were refused; HTTP 200 returned at 14:06:25.837.
Thus recovery was observed within about 4.1 seconds of that trial ending,
with two-second probe resolution. Other observed refusals recovered at the
next probe. There is no evidence of a load-induced reboot in this capture.

### Targeted incomplete-request reproduction

Twenty sequential fresh connections all returned HTTP 200 with 227-byte bodies.
At 14:07:11, one client (source port 54993) sent incomplete headers and stayed
open. A normal GET then timed out after 2.006 seconds. Closing the held client
restored service: the next GET completed in 14.3 ms. The mutex scope permits
one client waiting for headers to block unrelated requests.

At 14:07:21, four incomplete requests occupied all four workers. A fifth GET
failed with FreeBSD errno 61, ECONNREFUSED, in 4.2 ms. After releasing the four
clients, the next GET returned 200 in 23.8 ms. Worker snapshots and packets
correlate these failures with handler/mutex occupancy, rather than a reboot.

Evidence: matrix.txt, serial-diag.txt, slow-client.txt, diag-uplink.pcap,
diag-jail.pcap under /tmp/webfs-diag. The one-second worker snapshots do not
pinpoint every transition. Source port correlation assumes the single jail
client used here; instrument remote IP as well before multi-host testing.

### Reproduce captures, build and flash

From `/home/wongk/esp32`, in separate terminals:

```sh
# Recheck these interface names if the jail/bridge configuration changes.
doas sh diagnostics/capture.sh /tmp/webfs-new-capture 192.168.3.225
# Ctrl-C ends capture and writes packet/drop statistics.
doas python3.12 diagnostics/serial-raw.py /dev/cuaU1 > /tmp/webfs-serial.log
python3.12 diagnostics/concurrency.py > /tmp/webfs-matrix.log 2>&1
# Run only after the matrix finishes:
doas jexec esp32c3 python3.12 - < diagnostics/slow-client.py
```

Stop the serial reader before any flashing. Build the default diagnostic image:

```sh
doas jexec esp32c3 sh /project/scripts/build-freebsd.sh
```

The generated artifacts are inside the jail at `/build/artifacts/`, visible
on the host under `/usr/local/bastille/jails/esp32c3/root/build/artifacts/`.
The merged image embeds the ESP32-C3 bootloader, partition table and application;
write it at offset 0. This diagnostic deployment preserves the WebFS slots and
journal; the general provisioning script also rewrites site/journal state.
Exact diagnostic-v1 commands used (after positive chip identification and backup):

```sh
doas esptool --chip esp32c3 -p /dev/cuaU1 -b 460800 write-flash 0 \
  /usr/local/bastille/jails/esp32c3/root/build/artifacts/firmware.bin
doas esptool --chip esp32c3 -p /dev/cuaU1 -b 460800 verify-flash 0 \
  /usr/local/bastille/jails/esp32c3/root/build/artifacts/firmware.bin
```

The close-wait experiment is a default-off Cargo feature. Inside the writable
firmware build directory created by the build script, run:

```sh
export PATH=/root/.cargo/bin:/usr/local/bin:/usr/bin:/bin:/sbin
export CARGO_TARGET_DIR=/build/target
cargo build --release --locked --features close-wait
mkdir -p /build/close-wait
chmod 700 /build/close-wait
cp /build/target/riscv32imc-unknown-none-elf/release/webfs-blog /build/close-wait/webfs-blog.elf
espflash save-image --chip esp32c3 --flash-size 4mb --flash-mode dio \
  --flash-freq 40mhz --partition-table partitions.csv --merge --skip-padding \
  /build/close-wait/webfs-blog.elf /build/close-wait/firmware.bin
chmod 600 /build/close-wait/*
```

The experiment calls close, then awaits flush with a five-second deadline;
Embassy's flush explicitly waits for pending FIN acknowledgment. On deadline
it aborts and allows up to one second for the RST to leave. Stage 8 denotes this
close-wait phase. Worker count, mutex scope and request timeouts remain unchanged.

### Limits of the current attribution

The baseline and diagnostic captures distinguish refused handshakes from
post-response teardown resets. They do not identify individual 802.11 retries,
RF interference, or every dropped packet inside the ESP32 network stack. Some
stalls show requests on the wired uplink that are answered only after a later
TCP retransmission. Separating radio delivery loss from device RX queue loss
would require AP/radio capture or additional driver counters.

The bounded snapshots do not preserve every accept/close transition. They do
prove prolonged mutex occupancy in the deliberate incomplete-header test.
The currently reproduced reboot was caused by serial control, while the
instrumented load run preserved uptime. Earlier historical reset requirements
cannot be reconstructed retrospectively from benchmark output alone.

The build script now also accepts the experiment switch directly:

```sh
doas jexec esp32c3 env WEBFS_CLOSE_WAIT=1 sh /project/scripts/build-freebsd.sh
```

Omit WEBFS_CLOSE_WAIT to build the default diagnostic behavior. Preserve each
variant's artifacts before rebuilding because /build/artifacts is the common
output directory. Both the default and experiment retain the same HTTP API.

### Close-wait A/B result

The experiment image SHA-256 was
`52104b687f6997df163d2cd710de1d17e853749ce9c0fc73e7ab59b63289db60`.
It was flashed and verified from `/build/close-wait/firmware.bin` at offset 0.
One 15-second trial per concurrency was run; this is a mechanism experiment,
not enough repetition to rank throughput precisely.

| Connections | Requests/s | Read errors | Write errors | Timeout counter |
|---:|---:|---:|---:|---:|
| 1 | 52.63 | 0 | 0 | 0 |
| 2 | 57.51 | 0 | 375 | 0 |
| 4 | 40.34 | 0 | 1798 | 0 |
| 8 | 14.27 | 0 | 4124 | 0 |
| 16 | 7.18 | 0 | 4561 | 4 |
| 32 | 8.10 | 172 | 4425 | 0 |

Most post-response resets disappeared: capture contained 15,472 SYN refusals
and three other device resets, compared with 896 post-response resets in the
longer default diagnostic capture. The remaining three followed repeated FIN
transmissions and the experiment's five-second close deadline. Client FIN ACKs
were visible on the uplink, but were not acted on by the device before timeout;
the capture cannot distinguish radio loss from device RX processing loss.

Graceful close completion addresses the immediate-drop teardown defect, but
waiting retains workers longer and does not supply a free listener under load.
It is therefore retained as a default-off experiment, not presented as a complete
reliability fix. The default diagnostic firmware was rebuilt and restored.
Final merged image SHA-256:
`2eef1ae6a5a58430a5fa7b1b34c172362818b4ecad662adc732f753b1647dcb5`.
All 21 host tests passed during both default builds; these tests do not substitute
for hardware concurrency validation. Both default and close-wait native builds
compiled successfully, and every firmware write received esptool verification.

### Exact syscall attribution and final status

On the restored default build, kernel tracing avoided the short truss runtime:

```sh
doas jexec esp32c3 ktrace -t c -f /tmp/webfs-ktrace.out \
  wrk -t2 -c32 -d15s --timeout 2s -H 'Accept-Encoding: gzip' http://192.168.3.225/
doas jexec esp32c3 kdump -T -f /tmp/webfs-ktrace.out
```

The first full 15-second trace reported 4,268 wrk write errors and exactly 4,268
`write` returns with errno 32 (EPIPE). A second reported 5,818 and exactly 5,818
EPIPE returns. Nonblocking connect returned errno 36 (EINPROGRESS), which itself
is expected. Both runs reported connect=0. This confirms where the reported
write failures occurred; it is not a count of successfully established sockets.

Neither kernel-traced run reproduced the nonzero read counter seen in the
untraced matrix. Its exact syscall/parser attribution remains unresolved; do not
claim every read error has the same mechanism as the confirmed write errors.

For a precise refusal example, the four held source ports were 47774, 38335,
18329 and 34821. At 14:07:22.564–.581 the snapshots show worker 0 holding the
handler mutex and workers 1–3 waiting. The fifth connection, port 12661, received
device RST/ACK at 14:07:22.176011, and its client reported ECONNREFUSED.

The experimental close-wait build is no longer running. The final default
image is at `/usr/local/bastille/jails/esp32c3/root/build/artifacts/firmware.bin`,
with ELF alongside it. The final health check returned HTTP 200. Collectors and
load generators were stopped; no ZFS dataset or update endpoint was exercised.

Next implementation work should separate header reception from the shared
flash/image mutex and reserve admission capacity independently of connections
waiting for close. Qualify those changes with this same matrix before claiming
concurrency safety. Radio/RX-loss attribution and the intermittent wrk read
counter still need targeted evidence.

A durable compressed evidence copy is in
`/home/wongk/esp32/webfs-perf-results/2026-09-10/` (directory 700, files 600).
It includes captures, logs, summaries and the baseline main.rs; it excludes all
firmware binaries and full-flash backups. Use `gzip -dc FILE.txt.gz` for logs,
or decompress a pcap into a private temporary directory before tcpdump analysis.
The original secret-bearing backup remains private in /tmp/webfs-diag.

## Internet-facing hardening plan

Status: **planned, not implemented or qualified**. This plan supersedes any
suggestion that the current firmware is ready for public exposure.

### Corrected unattended-operation status

After the previously reported HTTP 200, stopping the raw serial collector was
followed by HTTP timeouts. Reattaching the reader did not immediately restore
service or produce new application output. At 14:15 UTC, the device terminal
settings showed canonical input, echo, 9600 baud and HUPCL enabled. The earlier
reader avoided control-line ioctls but did not configure a genuinely raw terminal
or prevent hangup on close. This is an unresolved observer/lifecycle issue;
those terminal settings alone do not prove its electrical cause. A diagnostic
reader was left attached during this investigation. The final unattended health
claim above is therefore **not valid**. Resolve this before performance tuning.

### 1. Deployment boundary and threat model

The first supported Internet deployment will expose **public read-only blog
content through an HTTPS gateway on FreeBSD**, with the ESP32 on an isolated
network. Keep the native FreeBSD Rust build and existing jails. Do not forward
Internet ports directly to the current device.

Use HAProxy at the gateway for TLS termination, request normalization, bounded
origin concurrency and admission control. Only the gateway may reach the ESP32
HTTP port; enforce this on the router/firewall or isolated VLAN, including IPv6.
Do not rely on a source-IP check inside the application. The initial origin link
may use HTTP only within that explicitly trusted, isolated segment, carrying
public assets and no management credentials. A shared or untrusted origin
network requires authenticated TLS to the device before deployment.

Assume hostile clients can send arbitrary bytes, many connections, incomplete
requests, slow reads, repeated reconnects and malformed paths. Assume Wi-Fi can
drop and power can fail. Availability is bounded by device capacity and upstream
bandwidth; the ESP32 cannot defend itself against an Internet-scale flood.
Gateway admission and upstream filtering are part of the deployment contract.

Defaults: public GET/HEAD only, no login, no directory listing, no public update
API, no remote shell, no OTA firmware endpoint. Keep ZFS key-serving separate;
never include its raw key or TLS credentials in a WebFS production image.

A **standalone ESP32 HTTPS listener** is a later release profile, not an implied
property of the gateway deployment. It must pass the separate TLS gate below.

### 2. Fix lifecycle and concurrency before adding exposure

1. Establish unattended operation first. Capture reset reason and boot identity
   while testing collector open, close, process termination, USB re-enumeration,
   and boot without any reader. Configure termios raw mode explicitly, disable
   echo/software flow control and HUPCL for diagnostic sessions, and restore
   settings only through a tested detach procedure. Do not toggle DTR/RTS as a
   side effect of ordinary status checks. Inspect control-line behavior and
   USB events before attributing a reset to firmware.
2. Make logging bounded and independent of a connected USB reader. Production
   telemetry uses fixed counters and a bounded ring; serial output is optional,
   rate-limited and must never hold the network executor or interrupts while
   waiting indefinitely for host consumption. Include boot reason, uptime,
   Wi-Fi/IP transitions, queue occupancy and dropped-log counts. No public
   diagnostics endpoint and no request bodies, passwords or private keys in logs.
3. Split HTTP processing into header reception/validation, immutable asset
   selection, chunk reads and transmission. Receive headers before taking the
   flash/image lock. Hold the lock only for bounded synchronous metadata or
   flash access; release it before every network await. For public read-only
   operation, pin the active volume for the boot session. Never release a lock
   around an update while retaining a reference to flash that can be erased.
4. Separate connection admission, request processing and closing states. Start
   with eight statically allocated TCP slots, at most two concurrent response
   producers, and a target of two available listeners when capacity permits.
   Explicitly budget DHCP and all other sockets in StackResources; do not just
   increase its number without accounting for RX/TX buffers and task storage.
   No unbounded spawn, queue, allocation or per-source-IP map.
5. Complete close with bounded FIN/ACK handling, then bounded abort/RST cleanup.
   The experiment showed that waiting alone worsens admission pressure: closing
   connections must not retain a response-production permit or flash lock.
   Retain closing sockets within the same fixed pool. If the pool is exhausted,
   reject predictably; do not promise an HTTP 503 before TCP is accepted.
6. Initial deadlines: complete headers within two seconds of accept, with a
   one-second inactivity limit; response writes within ten seconds total and
   two seconds without progress; graceful close within one second followed by
   at most 250 ms for abort cleanup. Deadlines include queue waiting and are not
   extended indefinitely by a trickle of bytes. These are release defaults,
   adjustable only through measured qualification, not remote client input.
7. Count accept failures, admission rejections, header deadlines, write stalls,
   close deadlines and handler failures separately. Record full remote tuple,
   connection ID, stage and uptime in bounded diagnostic events. Track minimum
   free heap, task/stack margin and pool high-water marks using supported APIs.

Success is isolation: a slow client must not hold flash state or prevent an
already admitted independent request from progressing. Under full admission
exhaustion, deterministic rejection and prompt recovery are acceptable.

### 3. Restrict and validate the protocol surface

Keep one request per origin connection for the first hardened release. The
gateway may offer client keep-alive but must normalize origin requests and avoid
pipelining. Do not introduce origin keep-alive until lifecycle correctness is
qualified independently.

Retain the 2 KiB total header bound. Reject invalid request-line spacing,
unsupported protocol versions, malformed field names, obsolete line folding,
missing/duplicate Host, duplicate Content-Length, Transfer-Encoding, conflicting
framing and request bodies on GET/HEAD. Use strict CRLF framing. Unsupported
methods return 405 with Allow: GET, HEAD; oversized headers return 431; malformed
requests return 400. Each error response is bounded and closes the connection.
The gateway and origin must agree on framing, rather than accepting ambiguous
requests differently. These checks follow the framing and parsing requirements
in [RFC 9112](https://www.rfc-editor.org/rfc/rfc9112.html).

Use exact asset lookup with one documented path normalization policy: reject
NUL, control characters, backslashes, encoded separators and dot-segment
traversal; do not decode twice. Split a bounded query from the asset path, without
reflecting it into headers. No filesystem path concatenation or directory
fallback. HEAD emits the same representation headers as GET, without a body.
Honor gzip quality values, including gzip;q=0; return 406 if no stored
representation is acceptable. Add Vary: Accept-Encoding and fixed MIME types.
Disable unsupported ranges rather than introducing partial-response complexity.

Set nosniff and a restrictive content policy suitable for the packaged blog
(self-hosted scripts/styles, no inline code, no framing, no object embedding).
Treat uploaded HTML/JavaScript as executable same-origin content; trusted
publication remains mandatory even when transport authentication succeeds.
Test headers against every bundled asset, redirects, 304 and error responses.

### 4. TLS, gateway admission and publication

For the first deployment, the FreeBSD gateway owns the public certificate,
renewal and TLS policy. Allow TLS 1.2/1.3 only, validate hostname coverage, test
renewal before expiry, and add HSTS only once HTTPS operation is confirmed.
Restrict origin routing to the configured hostname and asset paths; never let
request headers select an arbitrary backend. Strip untrusted forwarding headers
and set trusted ones at the gateway; the ESP32 must not use them as authority.

Initial gateway limits: two active origin connections, at most eight queued
requests, one-second queue deadline, ten new origin requests per second with
burst twenty, and a five-second public header deadline. Global bounds are
mandatory; per-IP limits alone are bypassable and can penalize shared clients.
Return bounded 429/503 responses at the gateway when limits are reached. Tune
only after sustained tests; the observed ~88 requests/s at c2 is not a guaranteed
production capacity. Apply equivalent IPv4/IPv6 firewall policy and verify that
neither the device nor its update path is directly reachable from outside.

For standalone deployment, first prove that a maintained TLS server stack works
with the pinned esp-hal/embassy versions and native FreeBSD build. Do not write
custom cryptography. Require correct entropy initialization, current protocol
policy, per-device keys, certificate provisioning/rotation and bounded handshake
memory and time. Start with one concurrent handshake and a five-second deadline;
reserve memory before accepting it. TLS state must share the overall admission
budget. Test malformed handshakes, reconnect floods and simultaneous transfers.
If this cannot meet the release gates on the C3, the standalone profile stays
unsupported; retain the gateway profile instead of weakening TLS verification.
Espressif documents TLS and platform security capabilities in its
[ESP32-C3 security guide](https://docs.espressif.com/projects/esp-idf/en/stable/esp32c3/security/security.html),
but ESP-IDF configuration switches do not automatically apply to this Rust stack.

Compile POST /update out of the public-serving firmware and reject it at the
gateway as well. Initial publication is an offline, verified flashing procedure
with a private backup and rollback image. Do not present the existing plaintext
HMAC update endpoint as Internet-safe management.

A later remote-publication release requires a separate private management path,
authenticated TLS, signed manifests/images, bounded upload size and duration,
monotonic version checks, key rotation and revocation, and inactive-slot writes
that cannot invalidate readers. Require power-loss and rollback tests before
reenabling it. Authentication and payload validation must precede destructive
flash actions; unauthenticated uploads must not consume flash endurance.

### 5. Build, device trust and operational maintenance

Pin dependencies and native toolchains, retain Cargo.lock, record source revision
and build flags in firmware identity, and produce a manifest with binary hashes,
partition offsets and tool versions. Keep secrets and configured binaries out
of Fossil/Git. Run dependency/advisory review at each release and monthly in
service; document a security-update owner and rollback procedure.

For production provisioning, validate Secure Boot v2, flash encryption and debug
restrictions with the actual Rust bootloader/storage path on a spare board first.
In particular, verify that esp-storage and the WebFS partition format operate
correctly with encrypted flash; do not assume ESP-IDF behavior is inherited.
Keep signing keys offline and per-device secrets separate. Review the exact
recovery path and eFuse changes before any irreversible programming. No eFuses
or existing development-board recovery features are changed by this plan.
These mechanisms address firmware authenticity and physical secret extraction,
not connection exhaustion or hostile HTTP inputs.

Use gateway-side health checks, request/error counters and alerting for repeated
origin failure. A watchdog may recover a proven executor hang, but it must not
be used to hide reproducible request-triggered crashes or create reboot loops.
Log reset reasons and retain a bounded failure record for diagnosis.

### 6. Tests and release gates

Implement and qualify in this order: unattended/serial lifecycle; parser and
lock-scope changes; admission/close lifecycle; gateway/TLS policy; publication
isolation; production provisioning. Preserve a baseline artifact and change one
subsystem at a time. Do not open firewall exposure as part of development tests.

- Host tests and fuzzing: malformed framing, duplicate headers, integer overflow,
  truncated input at every boundary, path ambiguity, gzip negotiation, HEAD,
  response lengths and corrupted WebFS metadata. Run sanitizers where supported
  and bounded parser/format fuzz campaigns with retained regression inputs.
- Device isolation: one and four slow-header clients, slow readers, abort during
  each phase, retransmissions, and repeated malformed requests. A separately
  admitted valid request must complete within two seconds under the documented
  healthy-LAN test conditions; rejected requests must not leak socket permits.
- Repeat the c1/2/4/8/16/32 matrix three times with synchronized packets, full
  remote-tuple events and kernel tracing at the first failure. Require zero
  transport errors at c1/c2 for valid requests under controlled conditions.
  Above admitted capacity, require bounded rejection, no memory growth or reboot,
  and HTTP recovery within five seconds after attack traffic stops.
- Resolve or explicitly reproduce the intermittent wrk read counter before
  qualification; distinguish parser failure, EOF and errno. Measure driver RX
  drops or AP captures when wired ACKs are not reflected in device TCP state.
- Lifecycle: 24 minutes of mixed valid/hostile traffic without an unexpected reboot
  or resource leak; 100 serial attach/detach cycles; ten cold boots without a
  reader; Wi-Fi loss/recovery and DHCP renewal; normal operation after leaving
  the console closed. A failed unattended test blocks release.
- Internet boundary: external IPv4/IPv6 scan exposes only intended gateway
  services; no direct device, update or diagnostics access. Verify TLS policy,
  certificate renewal, admission limits and rejection behavior through the gateway.
- Publication/provisioning: restore a known-good image, verify hashes, confirm
  secrets are absent from repository history and public artifacts, and document
  rollback. Remote updates remain disabled until their separate fault-injection
  and authenticity tests pass.

Deliverables are reviewed source changes, reproducible FreeBSD build/flash and
verification scripts, a tested gateway/firewall configuration, private artifact
manifest, test report and operator runbook. Use “hardened for the gateway-backed
public read-only profile” only after all applicable gates pass. Do not describe
the current diagnostic firmware, or the unqualified standalone TLS profile, as
an Internet-ready server.


### Publishing-timeout recovery follow-up

The user's publish.py errno 60 coincided with failing read-only HTTP probes.
Recovery stopped the reader, applied `stty -f /dev/cuaU1.init raw -hupcl 115200`,
and ran esptool chip-id with hard-reset. No flash, WebFS journal, publication
sequence or upload was changed. HTTP 200 returned without a reader (25.8 ms)
and after raw-reader detach (20.1 ms). Read-back terminal flags confirmed HUPCL,
ICANON and ECHO disabled. This narrows the observer problem to console lifecycle
configuration, but the full lifecycle matrix in the hardening plan is still due.
The reader now explicitly configures raw mode and disables HUPCL. No collector
was intentionally left running after this recovery; the earlier note about an
attached diagnostic reader describes the state before this follow-up.

## Update availability: diagnosis and repair plan

### Diagnosis (source inspection after the publishing timeout)

The service currently answers GET (HTTP 200 in 21.6 ms at this check). No new
POST was sent and no flash or publication sequence was changed for this diagnosis.

**Confirmed design defect:** firmware/src/main.rs acquires the shared AppState
mutex before calling webfs_http::handle. That handler receives headers and the
signed manifest, erases the candidate slot, receives the entire upload, programs
flash, validates the image, commits the journal, and writes HTTP 204 before the
mutex is released. All GET/HEAD handlers require the same lock. The 1 ms yields
between erase/program operations do not release it. A stalled upload can block
all other handlers for the enclosing 120-second deadline; accepted waiting
connections can fill the four-worker pool and subsequent connections are refused.
The earlier slow-header test already demonstrated this lock-exclusion mechanism.

**Additional starvation risk, not yet a measured crash cause:** Transaction::finish
synchronously hashes the entire candidate image, mounts/validates it, optionally
hashes the factory image, then erases/programs/verifies journal records. It has
no scheduling points. esp-storage calls the chip flash routines synchronously.
An async timeout cannot interrupt a synchronous operation while it is running.
Measure individual operation and executor blackout durations; do not assume
that adding a yield after a long operation makes the operation nonblocking.

**Incident attribution remains limited:** the reported urllib timeout occurred
while ordinary GETs also failed, after the separate serial-detach problem. No
trace proves that that particular POST reached manifest verification or wrote
flash. Neither the timeout nor the older POST incident proves an ESP32 reboot.
The lock defect is real, but must not be used to invent a cause for an untraced
historical event.

### Required behavior

An update must not reboot the board or take the serving path offline. Existing
readers finish against their original immutable generation; requests admitted
after successful publication use the new generation. Failed or interrupted
uploads leave a valid committed generation available. HTTP success is sent only
after durable commit and in-memory publication. Losing the success response must
not force the operator to guess whether to increment the sequence.

This restores authenticated LAN publication. The Internet-hardening plan still
disables public updates; this repair does not make plaintext management safe for
Internet exposure.

### Implementation sequence

1. **Separate network I/O from flash ownership.** Receive and validate bounded
   headers/manifest outside AppState. Introduce one storage-owner task with fixed
   request queues and bounded chunk buffers. It alone owns FlashStorage. GET/HEAD
   requests obtain a generation lease and request bounded reads; upload handlers
   receive chunks before submitting erase/program work. Never await network I/O
   while holding a storage or metadata lock. Do not fabricate concurrent mutable
   FlashStorage handles.
2. **Keep old images readable.** Store immutable active metadata and per-slot
   reader counts. A GET pins its slot/generation until all its body bytes have
   been copied and sent, releasing the lease on success, disconnect or timeout.
   Publish the new active metadata only after durable journal commit. Existing
   readers keep their old slot. Before a later update reuses that slot, require
   its reader count to reach zero; return 409 if it is still pinned. Bound reader
   lifetimes so a disconnected/slow reader cannot pin a slot indefinitely.
3. **Serialize writers without blocking readers.** Allow one update transaction
   at a time with a dedicated update permit, separate from read admission. Reject
   a second update with 409. Reserve read-serving capacity so one authenticated
   uploader cannot consume every worker. Authenticate and validate the manifest
   before erasing anything. Check sequence and slot availability atomically when
   granting the permit; recheck at commit if state could have changed.
4. **Schedule bounded flash work fairly.** Erase one 4 KiB sector or program at
   most one 1 KiB chunk per storage step, then service pending read work before
   another update step. Keep memory and queue sizes fixed. Stream SHA-256 during
   reception and retain a separate incremental readback hash/format validation
   before publication. Convert mount/CRC verification and factory-image hashing
   into bounded steps too. Preserve format and journal compatibility. Measure
   the non-preemptible time of each physical flash operation; if an erase alone
   violates the service budget, reduce update rate/use supported driver scheduling
   or external storage rather than promising zero interruption from async yields.
5. **Make commit and cancellation explicit.** Model receiving, erasing,
   programming, validating, committing, committed and failed states. Before
   commit, timeout/disconnect cancels the candidate and releases permits without
   changing active state. Once journal commit begins, a client disconnect must
   not cancel the storage task halfway through publication. Finish or reconcile
   the journal, then update active state. If write succeeds but verification fails,
   re-read valid journal records and reconcile in-memory state; do not claim the
   update failed safely while the next boot might select the new generation.
   Preserve the previous valid record and factory fallback throughout.
6. **Make completion observable and retries safe.** Add an authenticated LAN
   publication-status operation returning active sequence and image SHA-256 plus
   any in-progress transaction identity. Use a fresh server challenge and HMAC
   proof bound to method/path/challenge, or mTLS on the private management path;
   do not trust a bare header or expose an unauthenticated admin endpoint. Define
   retry identity as sequence plus image digest: the same already committed image
   reports success without erasing/programming again; a different image using
   that sequence returns 409. Recheck after acquiring the update permit to avoid
   races. Keep the existing publication envelope format compatible.
7. **Improve the publisher.** Add an explicit preflight and clear timeout/error
   reporting. On an uncertain completion, query authenticated status before any
   retry. Never silently increment sequence or automatically repeat destructive
   work. Distinguish authentication failure, sequence conflict, busy/pinned slot,
   transport timeout and device storage failure. Keep private keys and signed
   credentials out of error output. Return 204 only for confirmed publication.

The status authentication wire format must be specified and tested before that
step is implemented; until then a timeout is reported as uncertain and checked
through the trusted local console. Do not improvise an insecure status endpoint
merely to improve the publisher's message.

### Evidence and verification gates

First add transaction IDs, stage timings, bytes received/programmed, active and
candidate sequence, flash-operation duration, queue occupancy, and boot/uptime
markers to bounded diagnostics. Capture client, packets and serial concurrently
using the corrected console configuration. Back up the current flash privately
and identify the active sequence before a controlled upload; do not assume it is
zero or repeat sequence 1 blindly.

Test the new storage/state machine on the host before hardware: inject disconnect,
queue cancellation and flash failures at every step, including durable-write /
failed-readback and lost-204 cases. Use fake flash barriers to prove that a paused
uploader permits unrelated reads and that a second update never erases a pinned
old generation. Extend existing power-loss tests rather than treating their
current success as proof of runtime availability.

Then upload a small image and a maximum-size valid image on hardware while
running paced GET/HEAD checks at five requests/second with at most two in flight.
Require every admitted read to return a complete, hash-consistent old or new
representation, no unexpected reset or Wi-Fi loss, and p99 latency under 500 ms
on the controlled healthy LAN. Record flash blackout timing as well as response
latency. This target is a release gate, not a claim about current performance.

Repeat with slow uploads, stalled readers, disconnects during erase/program/
validation/commit/response, invalid signatures, bad hashes, stale sequences,
simultaneous publishers, and an old reader spanning two proposed updates.
Invalid authentication must cause zero flash writes. A lost success response
must be resolved without duplicate flash work. Use a spare board or explicit
maintenance window for physical power interruption; verify the selected valid
image and journal after every reboot.

Finally rerun the concurrency matrix and 24-minute mixed read/update soak, including
no serial reader attached. Require bounded rejection above admission capacity,
no leaked slots or permits, no request-triggered reboot, and recovery within
five seconds after a stalled client is removed. Deploy only after native FreeBSD
builds, host fault-injection tests and hardware availability gates pass. Retain
the prior firmware and image for rollback; do not use a maintenance outage as the
solution to the requirement that reads remain available during updates.


## Implemented: USB-only read-only WebFS

The user chose to remove publishing instead of implementing transactional upload
repairs. webfs-update, scripts/publish.py, update-key embedding, HTTP upload
handling and firmware erase/program methods were removed. One immutable region
now spans 0x1e0000 through 0x400000: 0x220000 bytes (2176 KiB). It reclaims the
second slot, journal and tail. Image format v2 is unchanged; no sequence is used.

The request-wide mutex is also gone. A single-executor !Sync Store makes short
RefCell borrows for reads and never holds one across network I/O. Four workers
remain bounded. Handlers have a 15-second total timeout and 10-second socket
inactivity timeout. This does not claim complete overload/Internet hardening.

mkwebfs --check validates an image and enforces the new capacity before the
flashing script performs any write. The script takes an optional explicit site
image, backs up full flash privately, clears the WebFS region and verifies both
images after writing. Provisioning intentionally stops service and is not
power-loss atomic; recovery is another USB flash, not network publishing.

Native build: 19 passing host tests. They cover rejected write methods, parser
and format behavior, a paused client alongside a successful reader, and a
1.2 MB asset spanning the previous 1 MiB boundary. Hardware: flashed and verified
firmware plus the user's 623656-byte, 92-asset blog. All assets matched exactly
with two concurrent clients (3.45 s total; max individual request 381 ms).
POST/PUT/DELETE/PATCH to /update, /update/check and /ota returned 405; GETs to those
paths returned 404; HEAD returned 200 without a body. An independent GET during
a deliberately incomplete request succeeded in 56 ms. Publish key absent from
new binary. HTTP remained available after serial reader detach.

Firmware SHA-256: 34e4a18d5166301b962a069955d91e31d7f9ada90c57d4faca0cee4887999cf7
Blog SHA-256: 97749f365ac3e2e9d22a20f74903183ed968fbc5223a43f17a1d570222a0ce0b
Application size: 505168 bytes. Images: /build/artifacts inside esp32c3;
selected blog: /home/wongk/esp32c3-webfs/artifacts/blog.wfs.
Backup: /build/artifacts/pre-webfs-20260910T183957Z.bin (private, inside jail).
Logs: /tmp/webfs-repair/readonly-final-build.txt, readonly-flash.txt,
readonly-network.txt and readonly-serial.txt. Current workflows are in
esp-hal-webfs.md and the project README. No ZFS dataset or Linux jail was changed.
