Skip to content

fix(relay): probe a half-open control socket instead of waiting out the silence bound (STA-7672) - #21076

Merged
Jinwoo-H merged 4 commits into
mainfrom
sta-7672-relay-half-open
Sep 18, 2026
Merged

Jinwoo-H merged 4 commits into
mainfrom
sta-7672-relay-half-open

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​197 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​196
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​203 $\color{#cf222e}{\Huge{\mathbf{−}}}$​53 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​150

ELI5

Imagine a phone call where the other person's line goes dead, but your phone still shows "connected." You keep talking into silence. That's what happened to the desktop's connection to the relay server on Windows — and it took 75 seconds to notice, while each pairing attempt gave up after 10. So every attempt failed, and the user just kept retrying into the same dead line.

Now, when a request goes unanswered, the desktop sends a tiny "you still there?" ping. No answer means the line is genuinely dead, so it hangs up and redials immediately.

What Changed

A control request that times out with no inbound frame since its send now arms an RFC 6455 ping probe. If neither a pong nor the relay's own ping arrives before the probe deadline, the socket is terminated and the origin reconnects.

The timeout error also stops being a bare string — it now names the request kind, the cell, the socket age, the time since the last inbound frame, and whether a probe was armed.

The silence watchdog, the probe, and the socket age moved into one RelayControlLiveness owner instead of being scattered across RelayControlClient.

Why

A socket CLOSE rejects a pending request as relay_control_closed_<code> (relay-control-client.ts), so a relay_control_request_timeout is positive proof the socket stayed open and never replied. The only thing that reaps such a socket is RELAY_CONTROL_SILENCE_LIMIT_MS = 75_000, combed every 15s — against a 10s request deadline. On Windows behind NAT/VPN, or across sleep-resume, a half-open TCP socket accepts send() into a dead pipe and stays invisible for 75-90s. Every pairing attempt in that window times out; the reporter burned about seven.

Why not just terminate on the timeout. Relay control ops run DB transactions that can outlive the 10s deadline, and the existing comment in handleMessage records that self-closing on a late reply was strictly worse than ignoring it — it orphaned the relay session and answered the phone with HOST_OFFLINE for minutes. A late reply must not tear down a healthy control. The probe distinguishes the two cases instead of guessing.

Why a run of three probes, not one. STA-3320 established that a single unanswered probe is UNKNOWN, not death — a cellular/VPN blackhole or a stalled TCP retransmit routinely swallows one pong from a peer that is still there, which is why RemoteRuntimeServerHeartbeat uses MISSED_PROBE_LIMIT = 3. The networks this detection exists for are precisely the ones that drop a lone frame, so three consecutive misses are required. Any inbound frame retires the whole run.

Why the probe run outlasts 15s. It deliberately exceeds the relay's own 15s application-level ping cadence. Relay liveness never depended on RFC 6455 control frames surviving end to end, so a shorter window would let a middlebox that swallows pongs turn every request timeout into a reconnect loop. The run is 3 x 8s = 24s, which still outlasts that cadence, so a healthy cell clears it either way — with a pong, or with the ping it was going to send anyway. A teardown therefore means the pipe carried neither frame, three times over. Detection drops from 75-90s to ~34s.

Why the deadline is jittered. Cell slowness is shared, so every host on a struggling cell times out at roughly the same moment. Without jitter they would all probe and terminate on the same boundary — the synchronized cohort burst that RELAY_RENEWAL_JITTER_RATIO was introduced for. That constant is reused here. (The pre-existing 75s watchdog comb has the same defect; this path does not add to it.)

Why the teardown is logged with a reason. It reaches the origin as an ordinary 1006 close, so without a label a probe-driven reconnect is indistinguishable from any other drop — and a fleet-wide false positive would be invisible in exactly the incident where you would need to see it.

Why a pong does not reset the silence watchdog. It proves the pipe, not that the relay still indexes the session; the watchdog exists to mirror the relay's own 75s bound.

Not a regression — nothing in 1.4.198 -> 1.4.204 touches this path. Long-standing. A second candidate defect (a Windows firewall rule pinned to a port) was investigated and ruled out: the existing repair flow already recovers from port drift in one click, so it was not a standalone broken path. See #21077 for that analysis. This PR is the real defect.

Linked Issue

STA-7672 — https://linear.app/stably/issue/STA-7672

Visual Proof

N/A — no UI change. This is main-process socket lifecycle; the user-visible effect is that pairing succeeds where it previously timed out.

Testing

pnpm tc, oxlint, and pnpm run check:code-quality:changed clean. Full pnpm test green apart from two pre-existing environmental failures with no import path to this code (relay-region-correction.unit.test.ts — pg not installed in this worktree; claude-structured-real-cli.test.ts — spawns the locally installed Claude CLI).

New regression coverage in relay-control-client.test.ts:

  • tears down only after a run of unanswered probes, not the first one
  • retires the whole probe run on a single pong (a later run never inherits an earlier miss)
  • spreads probe deadlines so one slow cell cannot synchronize a cohort
  • clears an armed probe on the relay's next ping, with no pong involved (middlebox guard)
  • does not probe a control that kept talking while a request went unanswered (late-reply guard)
  • names the cell and the silence in the timeout error

Mutation-checked: a miss limit of 1 fails four tests, 2 fails one, and removing the jitter fails one.

Not reproduced on real hardware. The half-open socket state needs a NAT/VPN or sleep-resume event to occur naturally; the tests drive it deterministically with a scripted socket instead. The reasoning is established from the code, not from a live repro.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

…he silence bound (STA-7672)

A socket CLOSE rejects a pending request as relay_control_closed_<code>, so a
relay_control_request_timeout is positive proof the socket stayed open and
simply never replied. The only thing that reaps such a socket is
RELAY_CONTROL_SILENCE_LIMIT_MS = 75_000, combed every 15s, against a 10s
request deadline. On Windows behind NAT/VPN or across sleep-resume a half-open
TCP socket accepts send() into a dead pipe and stays invisible for 75-90s, so
every pairing attempt in that window times out. The reporter burned ~7.

A request that times out with no inbound frame since its send now arms an RFC
6455 ping probe. Terminating on the timeout alone was rejected: relay control
ops run DB transactions that can outlive the deadline, and the existing comment
in handleMessage records that self-closing on a late reply was strictly worse
than ignoring it -- it orphaned the relay session and answered the phone with
HOST_OFFLINE for minutes. The probe distinguishes the two cases instead of
guessing.

The probe deadline deliberately exceeds the relay's own 15s application-level
ping cadence. Relay liveness never depended on RFC 6455 control frames
surviving end to end, so a shorter window would let a middlebox that swallows
pongs turn every request timeout into a reconnect loop. At 20s a healthy cell
clears the probe either way -- with a pong, or with the ping it was going to
send anyway -- so a probe that fires means the pipe carried neither. Detection
drops from 75-90s to ~30s.

A pong clears a probe but deliberately does not feed the silence watchdog: it
proves the pipe, not that the relay still indexes the session.

The timeout error also stops being a bare string; it now names the request
kind, the cell, the socket age, the time since the last inbound frame, and
whether a probe was armed.

The silence watchdog, the probe and the socket age now live in one
RelayControlLiveness owner rather than scattered across RelayControlClient.
@coderabbitai

coderabbitai Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: b6b34e4a-e2cc-42a9-ad32-10b9533b6b4f

📥 Commits

Reviewing files that changed from the base of the PR and between 88155b9 and f6b67d7.

📒 Files selected for processing (6)
  • src/main/runtime/relay/relay-control-client-options.ts
  • src/main/runtime/relay/relay-control-client.test.ts
  • src/main/runtime/relay/relay-control-client.ts
  • src/main/runtime/relay/relay-control-liveness.ts
  • src/main/runtime/relay/relay-control-requests.ts
  • src/main/runtime/relay/relay-control-timeout-classification.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.


📝 Walkthrough

Walkthrough

The relay control records request send times and reports timeout diagnostics through a liveness component. RelayControlLiveness monitors silence, inbound messages, pong events, and repeated jittered ping probes. RelayControlClient wires liveness handling into socket and lifecycle events. Tests cover probe recovery, jittered deadlines, and timeout classification.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to f6b67

The liveness changes retain the intended timeout classification and isolate reconnecting controls, with no actionable merge-blocking risk identified.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 7 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the main change: probing half-open relay control sockets instead of waiting for the silence bound. It is concise and specific.
Description check ✅ Passed The description covers the main template sections, including ELI5, changes, rationale, linked issue, visual proof, and testing. It provides detailed behavior, trade-offs, regression coverage, and know…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The new timeout diagnostics are dropped at the pairing RPC boundary, and the previously-preserved relay_control_request_timeout code now degrades to relay_mint_failed — see the inline comment. The probe lifecycle itself traces clean.

Reviewed changes

This run reviewed the full PR at 88155b9, which adds a half-open control-socket probe.

  • New RelayControlLiveness owner — folds the silence watchdog, the 20s probe deadline, and openedAt into one class that arms an RFC 6455 ping when a request times out with no inbound since its send, terminating the socket if no pong or relay ping arrives.
  • Client rewire — RelayControlLiveness replaces RelayControlSilenceWatchdog; socket.on('pong') and message now feed notePong/noteInbound.
  • Rich timeout error — RelayControlRequestTimeout carries reqId/kind/sentAt; the timeout message gains reqKind, cell, socketAgeMs, sinceInboundMs, probe diagnostics.
  • Watchdog getter — lastInboundTime exposes the watchdog's lastInboundAt.
  • Tests — five scripted-socket tests cover probe+teardown, pong disarm, relay-ping disarm, the late-reply no-probe gate, and the diagnostic text.

The probe lifecycle is sound: each RelayControlClient is single-use and owns exactly one socket, so a probe cannot terminate a replaced/active socket after a rebind, and both closeNow and handleClose disarm it. The live && lastInboundAt <= timeout.sentAt gate correctly declines to probe when anything arrived after the send.

ℹ️ Nitpicks

  • sentAt is now stored on PendingRequest (relay-control-requests.ts:200) but never read — the timeout closure already captures its own sentAt. Drop the field or read it from the pending entry.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

…control

A single unanswered probe was treated as proof of a dead pipe. STA-3320 already
established that it is not: a cellular/VPN blackhole or a stalled TCP
retransmit routinely swallows one pong from a peer that is still there, which
is why RemoteRuntimeServerHeartbeat requires three consecutive misses. The
networks this detection exists for are exactly the ones that drop a lone frame,
so the first cut was more trigger-happy than the rest of the product.

Three changes, all aimed at the cost of a false positive rather than the
detection itself:

- Three consecutive unanswered probes are now required. The interval drops to
  8s so the full run (24s) still outlasts the relay's 15s application-level
  ping, preserving the property that a healthy cell clears the probe even where
  a middlebox swallows RFC 6455 control frames. Detection lands at ~34s rather
  than ~30s, against 75-90s before the fix. Any inbound frame retires the whole
  run, so a later probe never inherits an earlier miss.

- The deadline carries the fleet's existing +/-10% jitter
  (RELAY_RENEWAL_JITTER_RATIO). Without it every host timing out against one
  slow cell would probe and terminate on the same boundary -- the synchronized
  cohort burst that constant was introduced for. The pre-existing 75s watchdog
  comb has the same defect; this path does not add to it.

- A liveness teardown now names its cause in the log. It reaches the origin as
  an ordinary 1006 close, so without a label a probe-driven reconnect is
  indistinguishable from any other drop, and a fleet-wide false positive would
  be invisible in exactly the incident where it matters.

Mutation-checked: a miss limit of 1 fails four tests, 2 fails one, and removing
the jitter fails one.
The diagnostics added in the previous commit were appended to the rejection's
message, which silently destroyed the signal they were meant to add.
`mobileRelayMintFailureFromUnknown` classifies a relay failure by testing
`error.message` against an anchored `/^relay_[a-z0-9_]{1,74}$/`, so
`relay_control_request_timeout reqKind=invite cell=...` stopped matching and
every pairing timeout was reported as the generic `relay_mint_failed` instead --
in exactly the flow STA-7672 is about. The pairing path logs only the resolved
code and discards the rejection's text, so nothing ever surfaced the suffix:
the change was a net loss of diagnosis.

The message is bare again and the diagnostics are logged from
RelayControlLiveness, which is the only place they survive.

Added relay-control-timeout-classification.test.ts to pin the contract end to
end through the real classifier, since the coupling is invisible at both sites:
restoring the suffix turns the assertion into relay_mint_failed.

Found in adversarial review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new critical issues in the incremental delta — one minor test-comment nitpick inline. The previously flagged [!IMPORTANT] finding (timeout diagnostics dropped at the pairing RPC boundary) is unchanged at this head, so its thread stays open.

Reviewed changes

This run reviewed the delta from 88155b9 to 77018e1, which hardens the half-open control-socket probe from a single deadline into a run.

  • Replaced the single 20s probe deadline with a run of up to three RFC 6455 pings at ~8s intervals, tearing down only on the third consecutive unanswered probe (PROBE_MISS_LIMIT), and resetting the whole run on any inbound frame or pong.
  • Jittered each probe boundary by ±RELAY_RENEWAL_JITTER_RATIO so a cohort timing out against one slow cell does not terminate on the same edge.
  • Renamed probeDeadlineMs/RELAY_CONTROL_PROBE_DEADLINE_MS to probeIntervalMs/RELAY_CONTROL_PROBE_INTERVAL_MS, added a livenessRandom test seam, and routed teardowns through terminateForLiveness, which logs the cause (reason=probe-unanswered / silence-limit).
  • Updated the scripted-socket tests to assert the run-of-three behavior, the pong reset, the relay-ping clear, the jitter, and the teardown log.

The widened window (min ~21.6s, ~24s nominal) still outlasts the relay's 15s app-level ping cadence (RELAY_PROTOCOL_LIMITS.controlPingIntervalMs, emitted from host-session-registry.ts:1446), so a healthy cell clears the run before the third miss and a middlebox that swallows pongs cannot turn this into a reconnect loop. The armProbe guard order (timer check before zeroing missedProbes) is correct — reversing it would strand a run — and every timer handle is cleared on stop() and both client teardown paths.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

expect(socket.pings).toBe(2)
socket.pong()

// A later probe run must start from zero, not inherit the earlier miss.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This comment names a property the test never exercises: the test never starts a second probe run, so a clearProbe() that cleared the timer but left missedProbes intact would still pass. That mutation is harmless anyway because armProbe() zeroes missedProbes on every run entry (relay-control-liveness.ts:108), which is exactly why the clearProbe reset is unobservable — so either drop the comment or add a second request that re-arms and shows the count restarts at zero.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues in this delta — the previously flagged must-address finding is resolved. The earlier minor test-comment suggestion is still open on its thread, so this is not an approval.

Reviewed changes

This run reviewed the delta from 77018e1 to f6b67d7, which restores the bare relay_control_request_timeout reason while keeping the diagnostics observable.

  • Moved the timeout diagnostics off the rejection: RelayControlRequests rejects with the bare relay_control_request_timeout again, so mobileRelayMintFailureFromUnknown's anchored /^relay_[a-z0-9_]{1,74}$/ match preserves the specific code at the pairing boundary.
  • OnRelayControlRequestTimeout now returns void; RelayControlLiveness.describeTimeout became noteRequestTimeout, which emits the reqKind/cell/socketAgeMs/sinceInboundMs/probe diagnostics via console.warn instead of returning them for concatenation.
  • Added relay-control-timeout-classification.test.ts, which pins the contract end to end: a timed-out request's message still classifies as relay_control_request_timeout through mobileRelayMintFailureFromUnknown.
  • Tightened the existing probe assertions from toContain(...) to toBe('relay_control_request_timeout'), and retargeted the diagnostics test at the warning log.

The probe lifecycle is otherwise unchanged from 77018e1 and remains sound: noteRequestTimeout still runs before the reject, so the probe observes the socket as the deadline found it, and a liveness teardown still logs its cause before terminating.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Design review of the three commits on this branch. No behaviour change: the
184 relay tests pass unmodified, and reverting PROBE_MISS_LIMIT to 1 or 2, or
dropping the jitter, still fails them.

Dead plumbing. `probeIntervalMs` had zero callers across three layers
(client options -> conditional spread -> liveness default), and `silenceLimitMs`
the same -- the only production construction site, relay-control-origin.ts,
passes neither. Both are gone. `livenessRandom` stays; one test uses it. The
conditional-spread idiom went with them: `exactOptionalPropertyTypes` is off for
src/ (only cloud/apps/relay-ops sets it), so it bought nothing that
`?? Math.random` does not already do.

Teardown owns its own log. A two-member reason union crossed a module boundary
just to reach a console.warn, and the client re-derived `cell=` from
relayOrigin when liveness already held `cellUrl`. Liveness now tears itself
down and calls `terminate`; the client lost the import, the method, and the
exported type.

One probe object, one interval. `probeTimer` + `missedProbes` are now
`probe: { timer, misses } | null`, so "no timer implies no misses" is structural
instead of maintained by resetting in two places, and the
sendProbe/onProbeUnanswered mutual recursion is a plain setInterval. Jitter is
computed once per run rather than per tick -- one offset already desynchronizes
the cohort.

Honest probe label. If ping() throws, the old arm path returned false and the
caller logged `probe=in-flight/0` moments after terminating the socket -- a
false statement in the line that exists for incident forensics. The arm path
now returns the label it means, including `probe=send-failed`.

Absorbed RelayControlSilenceWatchdog. It had one consumer and no test file, and
this branch had to punch a `lastInboundTime` getter through it purely so
liveness could read state it holds. `lastInboundAt` now sits next to `openedAt`;
the file, the getter, the import, and the onDead('silence-limit') lambda are all
gone.

Also: dropped `RelayControlRequestTimeout.reqId` and `PendingRequest.sentAt`
(both written, never read -- the timeout closure captures the local `sentAt`);
dropped the two `'n/a'` branches, unreachable because a request timeout can only
fire after sendActive succeeded, which requires a state only handleProofMessage
reaches on the line before it calls liveness.start(); moved the classifier
invariant off a void-returning callback type and onto REQUEST_TIMEOUT_CODE,
where an edit to the string is next to the warning about editing the string;
and replaced the `live` parameter with an `isLive()` option so liveness asks
rather than being told, which also let `liveness` be constructed before
`requests` instead of a closure reading a field assigned on a later line.
@Jinwoo-H Jinwoo-H closed this Sep 17, 2026
@Jinwoo-H Jinwoo-H reopened this Sep 17, 2026

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues in this delta — e1c73b5 is a behavior-preserving refactor. Approval is held only by the still-open test-comment thread from the prior review.

Reviewed changes

This run reviewed the delta from f6b67d7 to e1c73b5, which collapses the half-open detection onto one RelayControlLiveness object.

  • Merged the 75s silence watchdog into RelayControlLiveness (its own silenceTimer, SILENCE_LIMIT_MS / SILENCE_CHECK_INTERVAL_MS) and deleted relay-control-silence-watchdog.ts, so the probe run and the silence bound share one owner.
  • Replaced the RelayControlSilenceWatchdog field and terminateForLiveness with isLive / terminate callbacks; tearDown(reason) stops both timers before terminating.
  • Switched the probe chain from a per-miss setTimeout re-arm to a single jittered setInterval per run, tracking misses on the probe object.
  • Dropped silenceLimitMs / probeIntervalMs from RelayControlClientOptions and reqId / the stored sentAt from RelayControlRequests; the timeout callback now carries { kind, sentAt }.
  • Added the producer-side classification test and a cross-reference comment in mobile-relay-mint-failure.test.ts.

An independent audit of the merged timer lifecycle found no leaked interval, no double terminate(), and no skipped teardown relative to the separate-watchdog design; the only differences are log text (probe=send-failed vs probe=in-flight/0, socketAgeMs no longer n/a) and the once-per-run jitter. The touched suites pass locally (23 tests across the three files). The previously flagged [!IMPORTANT] finding is resolved and its thread is now closed.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H merged commit 9c92136 into main Sep 18, 2026
52 of 56 checks passed
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…he silence bound (STA-7672) (stablyai#21076)

* fix(relay): probe a half-open control socket instead of waiting out the silence bound (STA-7672)

A socket CLOSE rejects a pending request as relay_control_closed_<code>, so a
relay_control_request_timeout is positive proof the socket stayed open and
simply never replied. The only thing that reaps such a socket is
RELAY_CONTROL_SILENCE_LIMIT_MS = 75_000, combed every 15s, against a 10s
request deadline. On Windows behind NAT/VPN or across sleep-resume a half-open
TCP socket accepts send() into a dead pipe and stays invisible for 75-90s, so
every pairing attempt in that window times out. The reporter burned ~7.

A request that times out with no inbound frame since its send now arms an RFC
6455 ping probe. Terminating on the timeout alone was rejected: relay control
ops run DB transactions that can outlive the deadline, and the existing comment
in handleMessage records that self-closing on a late reply was strictly worse
than ignoring it -- it orphaned the relay session and answered the phone with
HOST_OFFLINE for minutes. The probe distinguishes the two cases instead of
guessing.

The probe deadline deliberately exceeds the relay's own 15s application-level
ping cadence. Relay liveness never depended on RFC 6455 control frames
surviving end to end, so a shorter window would let a middlebox that swallows
pongs turn every request timeout into a reconnect loop. At 20s a healthy cell
clears the probe either way -- with a pong, or with the ping it was going to
send anyway -- so a probe that fires means the pipe carried neither. Detection
drops from 75-90s to ~30s.

A pong clears a probe but deliberately does not feed the silence watchdog: it
proves the pipe, not that the relay still indexes the session.

The timeout error also stops being a bare string; it now names the request
kind, the cell, the socket age, the time since the last inbound frame, and
whether a probe was armed.

The silence watchdog, the probe and the socket age now live in one
RelayControlLiveness owner rather than scattered across RelayControlClient.

* fix(relay): require a run of unanswered probes before tearing down a control

A single unanswered probe was treated as proof of a dead pipe. STA-3320 already
established that it is not: a cellular/VPN blackhole or a stalled TCP
retransmit routinely swallows one pong from a peer that is still there, which
is why RemoteRuntimeServerHeartbeat requires three consecutive misses. The
networks this detection exists for are exactly the ones that drop a lone frame,
so the first cut was more trigger-happy than the rest of the product.

Three changes, all aimed at the cost of a false positive rather than the
detection itself:

- Three consecutive unanswered probes are now required. The interval drops to
  8s so the full run (24s) still outlasts the relay's 15s application-level
  ping, preserving the property that a healthy cell clears the probe even where
  a middlebox swallows RFC 6455 control frames. Detection lands at ~34s rather
  than ~30s, against 75-90s before the fix. Any inbound frame retires the whole
  run, so a later probe never inherits an earlier miss.

- The deadline carries the fleet's existing +/-10% jitter
  (RELAY_RENEWAL_JITTER_RATIO). Without it every host timing out against one
  slow cell would probe and terminate on the same boundary -- the synchronized
  cohort burst that constant was introduced for. The pre-existing 75s watchdog
  comb has the same defect; this path does not add to it.

- A liveness teardown now names its cause in the log. It reaches the origin as
  an ordinary 1006 close, so without a label a probe-driven reconnect is
  indistinguishable from any other drop, and a fleet-wide false positive would
  be invisible in exactly the incident where it matters.

Mutation-checked: a miss limit of 1 fails four tests, 2 fails one, and removing
the jitter fails one.

* fix(relay): keep the request-timeout rejection classifiable

The diagnostics added in the previous commit were appended to the rejection's
message, which silently destroyed the signal they were meant to add.
`mobileRelayMintFailureFromUnknown` classifies a relay failure by testing
`error.message` against an anchored `/^relay_[a-z0-9_]{1,74}$/`, so
`relay_control_request_timeout reqKind=invite cell=...` stopped matching and
every pairing timeout was reported as the generic `relay_mint_failed` instead --
in exactly the flow STA-7672 is about. The pairing path logs only the resolved
code and discards the rejection's text, so nothing ever surfaced the suffix:
the change was a net loss of diagnosis.

The message is bare again and the diagnostics are logged from
RelayControlLiveness, which is the only place they survive.

Added relay-control-timeout-classification.test.ts to pin the contract end to
end through the real classifier, since the coupling is invisible at both sites:
restoring the suffix turns the assertion into relay_mint_failed.

Found in adversarial review.

* refactor(relay): collapse the half-open detection onto one object

Design review of the three commits on this branch. No behaviour change: the
184 relay tests pass unmodified, and reverting PROBE_MISS_LIMIT to 1 or 2, or
dropping the jitter, still fails them.

Dead plumbing. `probeIntervalMs` had zero callers across three layers
(client options -> conditional spread -> liveness default), and `silenceLimitMs`
the same -- the only production construction site, relay-control-origin.ts,
passes neither. Both are gone. `livenessRandom` stays; one test uses it. The
conditional-spread idiom went with them: `exactOptionalPropertyTypes` is off for
src/ (only cloud/apps/relay-ops sets it), so it bought nothing that
`?? Math.random` does not already do.

Teardown owns its own log. A two-member reason union crossed a module boundary
just to reach a console.warn, and the client re-derived `cell=` from
relayOrigin when liveness already held `cellUrl`. Liveness now tears itself
down and calls `terminate`; the client lost the import, the method, and the
exported type.

One probe object, one interval. `probeTimer` + `missedProbes` are now
`probe: { timer, misses } | null`, so "no timer implies no misses" is structural
instead of maintained by resetting in two places, and the
sendProbe/onProbeUnanswered mutual recursion is a plain setInterval. Jitter is
computed once per run rather than per tick -- one offset already desynchronizes
the cohort.

Honest probe label. If ping() throws, the old arm path returned false and the
caller logged `probe=in-flight/0` moments after terminating the socket -- a
false statement in the line that exists for incident forensics. The arm path
now returns the label it means, including `probe=send-failed`.

Absorbed RelayControlSilenceWatchdog. It had one consumer and no test file, and
this branch had to punch a `lastInboundTime` getter through it purely so
liveness could read state it holds. `lastInboundAt` now sits next to `openedAt`;
the file, the getter, the import, and the onDead('silence-limit') lambda are all
gone.

Also: dropped `RelayControlRequestTimeout.reqId` and `PendingRequest.sentAt`
(both written, never read -- the timeout closure captures the local `sentAt`);
dropped the two `'n/a'` branches, unreachable because a request timeout can only
fire after sendActive succeeded, which requires a state only handleProofMessage
reaches on the line before it calls liveness.start(); moved the classifier
invariant off a void-returning callback type and onto REQUEST_TIMEOUT_CODE,
where an edit to the string is next to the warning about editing the string;
and replaced the `live` parameter with an `isLive()` option so liveness asks
rather than being told, which also let `liveness` be constructed before
`requests` instead of a closure reading a field assigned on a later line.
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