Production-hardening pass: half-open detection, cascade throttle, OBSERVE refresh, lamp/door coupling

Four failure modes observed in-house since the polling-first refactor
(709fdf4):

1. Half-open DTLS sessions where the socket stays writable but the peer
   has gone silent. Ping sends succeed against a wedged peer because
   RT-OCF doesn't reliably emit a RST; only successful polls prove the
   session is live.

   - PollScheduler exposes last_success_ts (bumped on every 2.05).
   - KeepaliveTask takes liveness_fn(); ticks fail if no 2.05 in the
     last 60s, even when the ping send succeeded.
   - Bridge force-closes the session after 120s unreachable so
     run_forever() breaks out of sess.join() and reconnects.

2. RT-OCF cascade under load. One wedged path can eat 8s of timeout,
   the next tier tick fires immediately and stacks another attempt,
   and the device wedges harder.

   - PollTier.timeout_s per-tier override (hot=2s, warm=4s, sweep=15s).
   - On TimeoutError, the href goes into a 5-60s cooldown via the
     existing _defer_until mechanism.
   - take_window_stats() now reports successful-poll RTT separately
     from a timeout count, exposed as the "Poll Timeouts (window)"
     diagnostic entity in HA.
   - Active-window throttle: if the previous health window saw >=3
     timeouts and is_active=True, drop back to idle cadence -- stops
     stacking polls on a stalled responder.

3. OBSERVE table aging across cloud-auth blips. The device stays
   DTLS-reachable but the on-device stack clears its observer table
   during the blip, so push delivery stays dead even after upstream
   recovers.

   - New ObserveRefreshTask per bridge; every 6h derregs all current
     observer tokens and re-subscribes on the existing session.

4. Oven lamp/door coupling. Oven hardware auto-drives the lamp from
   door state but /mode/vs/0 is warm-tier (30s) so HA showed stale lamp
   during a cook.

   - Track door + lamp value-change timestamps in descriptor_state.
     When the door transition is newer, derive lamp from door_open.
     When an HA optimistic write is newer, the cache value wins.

Also: ANSI-coloured WARNING/ERROR lines (NO_COLOR=1 opt-out), jittered
reconnect backoff so dryer + oven don't sync up after a router blip.

In-house verification: running on dryer + oven since 2026-06-03.
This commit is contained in:
Jack Nagy committed 2026-06-30 19:27:59 +01:00
1 parent 0374f8cf68
commit 36acf3a209
9 files changed
+438 -62

No files matched your search

+41 -17
View File
@@ -2,7 +2,7 @@
Replaces the TLS-over-TCP transport used in the original dryer bridge.
Both the oven (UDP/49154) and the dryer (UDP/49155) speak CoAP-over-DTLS
with the ECDHE-ECDSA-AES128-GCM-SHA256 cipher and ab0b0ac4 client cert.
with the ECDHE-ECDSA-AES128-GCM-SHA256 cipher and a client cert.
Wire-level details that matter (from local-tools/oven-findings.md §17):
* DTLS ciphertext MTU must be 1200; otherwise OpenSSL fragments the
@@ -226,10 +226,8 @@ class DtlsCoapSession:
ConnectionError / TimeoutError on failure."""
ctx = SSL.Context(SSL.DTLS_METHOD)
ctx.set_verify(SSL.VERIFY_NONE, lambda *_: True)
# @SECLEVEL=0 needed because the AC14K_M-rooted ab0b0ac4 chain
# is SHA-1 signed, which OpenSSL 3.x's default security level
# rejects. The chain comes from Samsung's leaked CA so the
# signature algorithm isn't ours to change.
# @SECLEVEL=0 — the AC14K_M-rooted chain is SHA-1 signed, which
# OpenSSL 3.x's default security level rejects.
ctx.set_cipher_list(b'ECDHE-ECDSA-AES128-GCM-SHA256:@SECLEVEL=0')
ctx.use_certificate_chain_file(self.cert_path)
ctx.use_privatekey_file(self.key_path)
@@ -592,25 +590,51 @@ class DtlsCoapSession:
def ping(self):
"""RFC 7252 §4.4 CoAP Ping — empty CON, no token, no payload.
Peer MUST respond with an RST sharing the same Message ID.
We don't block waiting for the RST here; the reader thread
sees it, finds nothing in _pending/_observe_tokens for an
empty token, and drops it quietly — which is the documented
behaviour for unsolicited RST.
Fire-and-forget: we do not wait for the matching RST because
Samsung's RT-OCF doesn't reliably emit one (verified
2026-06-04: every sync ping timed out while polls succeeded
at 200+/window). The send itself is the keepalive — it
tickles Samsung's observer state so OBSERVE subscriptions
aren't aged out.
Sole purpose is keepalive: gives Samsung's RT-OCF stack a
visible "client still here" signal so it doesn't expire our
OBSERVE subscriptions (symptom of expiry: POSTs still get
2.04 but OBSERVE notifications stop arriving)."""
Real half-open-session detection lives in PollScheduler's
`last_success_ts`, surfaced through KeepaliveTask's
`liveness_fn`."""
if self.conn is None:
raise ConnectionError("DTLS session closed")
mid = self._next_mid()
# Empty message: ver=01, type=CON, tkl=0, code=0.00, mid, no
# token, no options, no payload. build_coap with empty token
# and no options yields exactly that.
self._send_dgram(build_coap(TYPE_CON, 0, mid, b'', []))
return mid
def refresh_observes(self, paths):
"""Drop all current OBSERVE registrations and re-subscribe to
the given paths. Used as a periodic safety net — CoAP OBSERVE
has no built-in TTL but Samsung's RT-OCF can age out its
observer table during cloud blips even while the DTLS session
stays healthy. Without this, internet recovery on a still-
reachable device leaves push permanently dead.
Best-effort: dereg failures are logged and we still bind fresh
tokens via subscribe. Brief race window where a notify on the
old token gets dropped as 'stale' — acceptable for a 6h-scale
safety net."""
if self.conn is None:
raise ConnectionError("DTLS session closed")
for tok, href in list(self._observe_tokens.items()):
segs = [s for s in href.split('/') if s]
try:
self._send_observe_dereg(tok, segs)
except Exception as e:
logger.warning("refresh dereg %s: %s", href, e)
self._observe_tokens.clear()
time.sleep(0.1)
for path in paths:
try:
self.subscribe(list(path))
time.sleep(0.05)
except Exception as e:
logger.warning("refresh subscribe %s: %s", path, e)
def subscribe(self, path_segs):
"""Register an OBSERVE on the given path. The initial 2.05
notification and all subsequent state-change notifications