Skip to content

fix(web): declare a socket dead even when its probe cannot be sent - #17838

Merged
nwparker merged 3 commits into
mainfrom
fix/shared-transport-liveness-policy
Sep 2, 2026
Merged

nwparker merged 3 commits into
mainfrom
fix/shared-transport-liveness-policy

Conversation

@nwparker

@nwparker nwparker commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​31 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​31
Prod 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​7 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​4

First step of #17823, and it carries a real latent bug fix.

The bug

web-runtime-connection-heartbeat.ts armed its dead-socket deadline only if the probe was successfully sent:

if (this.options.sendProbe()) {
  this.heartbeatProbeSentAt = now
}

The dead-socket branch above requires heartbeatProbeSentAt !== null. So a false return silently disarms the only thing that can declare the link dead, and a socket that cannot be written to is watched forever.

This is the same wedge fixed on the SSH transport in #17817, where a saturated writer suppressed the dead-link check without bound and the mux never disposed, never fired onRelayLost, and never reconnected.

It is currently unreachable only by luck. sendProbe is sendEncrypted, which returns false solely for !socket || readyState !== OPEN || !sharedKey — and the first two are already excluded by the guard immediately above. Browser WebSocket.send() buffers into bufferedAmount rather than refusing, so saturation returns true. Make that predicate backpressure-aware, which is the natural thing to do next, and the bug appears immediately.

Fix: arm the deadline before the send and regardless of its result. A probe that could not be written is the strongest evidence available that the link is gone — never a reason to stop watching.

BEFORE  × still declares the socket dead instead of watching it forever
AFTER   Tests  1 passed (1)

The shared policy

src/shared/transport-liveness-policy.ts is a pure decision function — probe / rebase-after-pause / declare-lost / wait — plus the two invariants each hand-written copy re-derived and got wrong at least once:

  1. The pause threshold must be derived, not chosen. A healthy peer answers the previous probe, so at any tick its last inbound is already up to one probe interval old. A gap larger than deadWindowMs - probeIntervalMs pushes silence past the dead window on its own; a threshold set at deadWindowMs — the intuitive choice — leaves a dead band where every healthy peer is declared lost after a host suspend, a VM migration, or the local event loop stalling. I reintroduced exactly this while writing the relay reaper in fix(ssh): declare a wedged relay link lost, and stop reading silence as a verdict #17817; it was caught in review only because someone compared the two files.
  2. Arm the probe deadline unconditionally, per the bug above.

Six tests cover both shapes in the codebase (probe-every-tick like the SSH mux, probe-after-idle like the WebSocket), the dead band, a backwards clock, and "any inbound traffic counts, not just a reply".

Scope, deliberately

The module is introduced with one adopter. I also tried aligning remote-runtime-socket-liveness.ts's pause threshold onto the derived form and reverted it: that path has no bug — it arms probeSentAt before calling tryPing(), and tryPing swallows throws, so it is structurally immune — and with custom configs pingIntervalMs * 1.5 is not equal to livenessTimeoutMs - pingIntervalMs, which broke two tests that encode the existing value on purpose. Taking regression risk on a path with no defect is not worth it. Aligning it, and the SSH mux and relay reaper once #17817 lands, is mechanical follow-up under #17823.

Verification

$ pnpm test src/shared/ src/renderer/src/web/
 Test Files  632 passed | 5 skipped (638)
      Tests  6694 passed | 71 skipped (6766)

$ pnpm tc:node    # clean

One file (remote-runtime-shared-control-connection.test.ts) failed in a combined run and passes in isolation; this diff does not touch it.

Refs #17823, #17817


ELI5

The web client checked whether its connection was alive by sending a ping — but only started the 'are you dead' timer if the ping was successfully sent. A connection too broken to send was therefore never declared dead.

User-facing regression risk

  • A socket that cannot send is now declared dead and reconnected, where before it hung silently. Same class of visible change as fix(ssh): declare a wedged relay link lost, and stop reading silence as a verdict #17817.
  • The shared policy module has one adopter and changes no other transport's behaviour. Aligning remote-runtime-socket-liveness.ts was attempted and reverted — it has no bug, and with custom configs the thresholds are not equivalent.

Scoped down after review: the shared policy module has been removed

A reviewer pointed out that src/shared/transport-liveness-policy.ts had zero production importers — decideTransportLiveness was called only by its own test. That is a fair criticism: the PR delivered less than its description implied, and shipping a module nothing imports is not consolidation, it is documentation with a test suite attached.

I considered adopting it here, in the heartbeat this PR already fixes, and decided against it. Mapping the heartbeat onto the policy would move its pause-rebase threshold from 20s to 10s — a real behaviour change on a path with no bug motivating it. I made exactly that mistake earlier in this batch (aligning remote-runtime-socket-liveness.ts onto the derived threshold, which broke two tests because with custom configs ping × 1.5 ≠ timeout − ping) and reverted it for the same reason. Taking regression risk on a healthy path to justify a module is the wrong trade twice over.

So this PR is now exactly what it is: the 6-line fix plus its regression test, scoped to the web path.

The policy module will land under #17823 with its first real adopters — the SSH multiplexer and the relay reaper — once #17817 merges and they can actually import it. That is where it has teeth, because those are the two sites that have already had this bug.

What the module was documenting remains true and is worth restating for whoever picks up #17823:

  1. The pause threshold must be derived, not chosen. A healthy peer answers the previous probe, so at any tick its last inbound is already up to one interval old. A gap beyond deadWindowMs - probeIntervalMs pushes silence past the window on its own; a threshold set at deadWindowMs leaves a dead band. I reintroduced exactly this while writing the relay reaper.
  2. A check that can legitimately be disarmed must never be the sole authority. Not "always arm unconditionally" — that is wrong for an ack check, which correctly disarms when nothing is outstanding. The rule is that there must be exactly one unconditional inbound-silence deadline per transport that no branch can clear, plus any number of conditional refinements that report distinct reasons. All three bugs in this batch were the same failure: the only authority was a conditional one.

@greptile-apps

greptile-apps Bot commented Sep 1, 2026

Copy link
Copy Markdown

Greptile Summary

The PR fixes WebSocket heartbeat teardown when a probe cannot be sent and introduces a tested shared transport-liveness decision policy.

  • Arms the WebSocket probe deadline before attempting the send.
  • Adds regression coverage for unsendable probes.
  • Adds shared pause-rebasing, probing, waiting, and dead-link decisions with boundary tests.
  • The shared policy is not yet connected to its intended production adopter.

Confidence Score: 4/5

The PR appears safe to merge, with the non-blocking concern that its new shared policy is not actually adopted by production heartbeat code.

The heartbeat fix handles unsendable probes correctly, but the policy and production implementation can drift because they remain disconnected.

Files Needing Attention: src/shared/transport-liveness-policy.ts and src/renderer/src/web/web-runtime-connection-heartbeat.ts

Important Files Changed

Filename Overview
src/renderer/src/web/web-runtime-connection-heartbeat.ts Correctly arms the existing deadline before attempting a probe, while retaining the handwritten policy instead of adopting the new shared function.
src/renderer/src/web/web-runtime-connection-heartbeat-unsendable-probe.test.ts Covers the reported false-return regression and verifies eventual dead-socket handling.
src/shared/transport-liveness-policy.ts Adds a clear pure decision policy, but it currently has no production importer.
src/shared/transport-liveness-policy.test.ts Exercises probing, timeout, pause, backward-clock, idle, and inbound-traffic decisions, though only against the otherwise-unused policy.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    T[Heartbeat tick] --> P{Long local pause?}
    P -->|Yes| R[Rebaseline timestamps]
    P -->|No| D{Probe deadline expired?}
    D -->|Yes| L[Close socket and reconnect]
    D -->|No| I{Idle and no probe outstanding?}
    I -->|Yes| A[Arm deadline unconditionally]
    A --> S[Attempt probe send]
    I -->|No| W[Wait]
Loading

Reviews (1): Last reviewed commit: "fix(web): declare a socket dead even whe..." | Re-trigger Greptile

Comment thread src/shared/transport-liveness-policy.ts Outdated
Comment on lines +45 to +48
export function decideTransportLiveness(
config: TransportLivenessConfig,
input: TransportLivenessInput
): TransportLivenessDecision {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Shared policy has no adopter

The production WebSocket heartbeat still implements these decisions independently instead of calling decideTransportLiveness, so the new policy's tests can pass while production behavior drifts from the invariants it is intended to centralize.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@coderabbitai

coderabbitai Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: d4d84ff4-a45a-4b97-8c21-8f725b741f0d

📥 Commits

Reviewing files that changed from the base of the PR and between 2b27e1c and 3267d05.

📒 Files selected for processing (1)
  • src/renderer/src/web/web-runtime-connection-heartbeat.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/web/web-runtime-connection-heartbeat.ts

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


📝 Walkthrough

Walkthrough

runTick now arms the heartbeat probe deadline before calling sendProbe(). The heartbeat can therefore declare a socket dead when the probe cannot be sent. A new test advances five 10-second ticks with sendProbe returning false and verifies that handleDeadSocket receives the socket.

Merge Risk: 🔵 Low · up to 3267d

The change correctly reconnects sockets whose probes cannot be sent, but the heartbeat still uses a pause threshold that may close a healthy connection after a moderate event-loop stall; the PR is mergeable with explicit owner awareness and follow-up for that bounded reconnect risk.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description clearly explains the bug, fix, scope, regression test, issue references, and verification results. However, it omits several required template sections and checklist items, including t… Update the description to follow the repository template. Add the required linked issue using Fixes #..., provide visual proof or write exactly N/A with a reason, document testing steps and tested platforms, complete applicable AI Discl…
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main WebSocket liveness fix: declaring a socket dead when its heartbeat probe cannot be sent.
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.
Full details: Description check

Explanation

The description clearly explains the bug, fix, scope, regression test, issue references, and verification results. However, it omits several required template sections and checklist items, including the required Fixes # linked issue entry, visual proof or an exact N/A statement, testing checkboxes and platform coverage, review notes, agent-skill boundary confirmation, AI disclosure, and the final checklist.

Resolution

Update the description to follow the repository template. Add the required linked issue using Fixes #..., provide visual proof or write exactly N/A with a reason, document testing steps and tested platforms, complete applicable AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections, and mark the required checkboxes.

  • 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.

@coderabbitai coderabbitai 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.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 3457e3f7-9750-4d7a-8e8f-d2107594fbe1

📥 Commits

Reviewing files that changed from the base of the PR and between f088872 and 2b27e1c.

📒 Files selected for processing (4)
  • src/renderer/src/web/web-runtime-connection-heartbeat-unsendable-probe.test.ts
  • src/renderer/src/web/web-runtime-connection-heartbeat.ts
  • src/shared/transport-liveness-policy.test.ts
  • src/shared/transport-liveness-policy.ts

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

Comment on lines +72 to +78
// Why the deadline is armed before the send and regardless of its result: a probe that could
// not be written is the strongest evidence the link is gone, not a reason to stop watching.
// Gating this on a successful send disarms the only branch above that can declare the socket
// dead, so a saturated or half-open socket would never be judged at all -- the same wedge
// fixed on the SSH transport in #17817. See src/shared/transport-liveness-policy.ts (#17823).
this.heartbeatProbeSentAt = now
this.options.sendProbe()

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.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Use the shared pause decision in runTick.

This code still uses the local 20-second pause threshold at Line 52. With a 10-second interval and a 20-second probe grace, the shared policy rebases after a 10-second pause.

For example, a probe armed at 30 seconds, followed by a normal tick at 40 seconds and a 15-second pause, reaches Line 64 with a 25-second-old probe. The current code closes the socket before queued inbound traffic can update lastInboundFrameAt. Use decideTransportLiveness here so the WebSocket path applies the same pause rebasing policy.

Comment thread src/shared/transport-liveness-policy.ts Outdated
* migration, or the local event loop stalling.
*/
export function transportLivenessPauseGapMs(config: TransportLivenessConfig): number {
return config.deadWindowMs - config.probeIntervalMs

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect every policy configuration and policy call site.
rg -n -C 4 --type ts \
  'deadWindowMs\s*:|probeIntervalMs\s*:|decideTransportLiveness\s*\(|transportLivenessPauseGapMs\s*\(' \
  src

Repository: stablyai/orca

Length of output: 9770


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- applicable repository conventions ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -type f -name '*.md' -print

printf '%s\n' '--- policy source ---'
cat -n src/shared/transport-liveness-policy.ts

printf '%s\n' '--- all tracked references to the policy and configuration fields ---'
rg -n -C 3 \
  'transportLivenessPauseGapMs|decideTransportLiveness|probeIntervalMs|probeAfterIdleMs|deadWindowMs' \
  $(git ls-files)

Repository: stablyai/orca

Length of output: 18367


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- repository-wide review conventions ---'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/repo-wide.md

printf '%s\n' '--- source-scope review learnings ---'
cat /tmp/coderabbit-repo-knowledge/stablyai/orca-89dc44e4/learnings/src.md 2>/dev/null || true
cat /tmp/coderabbit-repo-knowledge/stablyai-*/learnings/src.md 2>/dev/null || true

printf '%s\n' '--- change for the reviewed file ---'
git diff -- src/shared/transport-liveness-policy.ts src/shared/transport-liveness-policy.test.ts

Repository: stablyai/orca

Length of output: 2275


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- repository-wide review conventions ---'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/repo-wide.md

printf '%s\n' '--- source-scope review learnings ---'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings/src.md 2>/dev/null || true

printf '%s\n' '--- change for the reviewed file ---'
git diff -- src/shared/transport-liveness-policy.ts src/shared/transport-liveness-policy.test.ts

Repository: stablyai/orca

Length of output: 2275


Reject configurations where deadWindowMs <= probeIntervalMs. TransportLivenessConfig accepts independent number values. For an invalid configuration, transportLivenessPauseGapMs is non-positive, so decideTransportLiveness returns 'rebase-after-pause' for every non-negative tick gap and never reaches the probe or dead-link decisions. Enforce this invariant and add a test.

@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 heartbeat fix itself is correct, but the shared liveness policy this PR introduces has no production adopter — the description's "one adopter" claim doesn't match the diff.

Reviewed changes

  • Arm the probe deadline before sending — web-runtime-connection-heartbeat.ts now records heartbeatProbeSentAt unconditionally, so a probe that cannot be written still starts the dead-socket clock.
  • Introduce a shared transport-liveness policy — a pure decision function plus a derived pause gap and a true constant, meant to be the single source of truth for liveness decisions.
  • Add tests — one regression test for the unsendable-probe case and six tests for the policy module.

⚠️ The shared liveness policy has no production adopter

decideTransportLiveness and transportLivenessPauseGapMs are imported only by their own test file. The heartbeat fix is inline and never calls the module, so the module, the exported TRANSPORT_LIVENESS_ARM_PROBE_UNCONDITIONALLY constant, and its 108-line test file all ship unreferenced. Combined with the SOCKET_LIKE fixture mismatch below, nothing yet validates that the shared logic faithfully expresses the code it is meant to unify.

Technical details
# Shared liveness policy is unreferenced

## Affected sites
- src/shared/transport-liveness-policy.ts — no production importers
- src/shared/transport-liveness-policy.test.ts — the only consumer of the module
- src/renderer/src/web/web-runtime-connection-heartbeat.ts:76 — comment references the module, but the class never imports it

## Required outcome
- Either make the heartbeat a real adopter (route its tick through `decideTransportLiveness` and reconcile the pause threshold, currently `HEARTBEAT_INTERVAL_MS * 2`), or defer the module and its test to the #17823 migration that actually adopts it.

## Open questions for the human
- Is the module meant to be adopted within this PR, or is it documentation-as-code to be wired up later?

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

Comment thread src/shared/transport-liveness-policy.ts Resolved

@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 critical issues — one minor nit inline.

Reviewed changes

  • Removed the shared liveness-policy module and its test — src/shared/transport-liveness-policy.ts and its 108-line test are deleted, resolving the prior review's "no production adopter" finding by deferring the policy to #17823.
  • Heartbeat fix and regression test unchanged — the unconditional probe-deadline arming in web-runtime-connection-heartbeat.ts and its regression test carry over from the prior review.

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

@nwparker
nwparker merged commit c91edaf into main Sep 2, 2026
28 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tablyai#17838)

* fix(web): declare a socket dead even when its probe cannot be sent

* chore: land the shared liveness policy with its first real adopter instead

* docs: drop the reference to a file this PR no longer adds
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