Skip to content

fix(rpc): keep the event loop running during an error-triggered resubscribe - #1642

Draft
Claudius-Maginificent wants to merge 1 commit into
fix/ws-resubscribe-orphanfrom
fix/ws-error-resubscribe-hang
Draft

Claudius-Maginificent wants to merge 1 commit into
fix/ws-resubscribe-orphanfrom
fix/ws-error-resubscribe-hang

Conversation

@Claudius-Maginificent

@Claudius-Maginificent Claudius-Maginificent commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

TL;DR: The RPC client no longer freezes when the node rejects a request while the connection is dropping: it keeps delivering events and reconnects.

User story

As a developer using the Tenderdash RPC client's event subscriptions, I want the client to keep working through a node error that arrives during a connection drop, to keep receiving events after the client reconnects.

Scenario

Base flow

A client holds event subscriptions over WebSocket. The node answers one of its requests with an error (for example, the per-client subscription limit is reached, or the node is restarting), and the connection drops around the same time.

Actual behavior

The client reacts to the error by re-subscribing from the same loop that reads the node's replies. If the connection is down, that re-subscribe waits for the connection to come back. The connection cannot come back until that loop reads the next reply. The client stays stuck, delivering no events, until it is stopped.

Expected behavior

The client keeps reading replies while it re-subscribes after an error, reconnects, and resumes delivering events.

Detailed discussion

Stack (bottom → top; a manual stack, since native stacked PRs are not enabled for this repository): #1600 → #1627 → #1515 → #1639 → #1641 → #1642. This PR is 6 of 6, base fix/ws-resubscribe-orphan; depends on #1641, #1639, #1515, #1627, #1600; merge them first (bottom-up). Each PR carries only its own changes.

What was done

Scope: only this hang in rpc/client/http/ws.go, pre-existing on dev and found while reviewing #1641.

Before this change, eventListener ran redoSubscriptionsAfter inline after a retryable RPC error. That could close a cycle:

  1. Its ws.Subscribe waits for the WSClient writer to accept the request (ws_client.go:207).
  2. A writer that failed restarts only after reconnectRoutine's wg.Wait() (ws_client.go:363).
  3. That waits for readRoutine, blocked handing the next response to ResponsesCh (ws_client.go:493).
  4. Only eventListener drains ResponsesCh.

The client stalled until its lifetime ended.

  • eventListener starts one resubscriber goroutine on a child context and joins it when it exits, so Stop still joins everything and fix(rpc): release upstream subscriptions orphaned by a resubscribe #1641's orphan unsubscribes still start before Stop waits for them.
  • A retryable error only requests a resubscribe through a one-slot channel. Errors arriving while one is pending coalesce, and at most one further pass runs after the current one.
  • The delay before a pass is unchanged. Events now keep flowing during the delay and the pass, where before every subscriber was paused for that time.

Out of scope: other wsEvents changes.

Known limitations: None.

Testing

  • TestErrorResubscribeKeepsDeliveringEvents reproduces the hang from the real trigger: an error response arrives, and a dialer wrapper fails the resubscribe's write as if the connection dropped. Without the fix it failed with event for "q1" was not delivered, and a stack dump showed the cycle above.
  • TestRepeatedErrorsCoalesceResubscribes: three errors, each followed by an event, deliver every event and leave exactly one resubscribe running and one pending.
  • TestSubscriptionNotFoundDoesNotResubscribe keeps the resubscriber busy and checks that a "subscription not found" reply queues no further resubscribe (fails without ignoring that error).
  • go test -p 1 -race -count=1 ./rpc/client/http/ and -tags deadlock pass. The join/leave stress test and all resubscribe tests pass under -race -count=5. golangci-lint on the package with --new-from-rev=origin/fix/ws-resubscribe-orphan is clean.

Breaking changes

None.

Prior work

Attribution

🤖 Generated with Claude Code

🤖 Co-authored by Claudius the Magnificent AI Agent

@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@thepastaclaw

thepastaclaw commented Nov 25, 2026 •

Copy link
Copy Markdown

🕓 Review not started yet because this PR is a draft.

  • Request normal review — click when the PR is ready for review.
  • Request priority review — click to move this review to the front of the queue.

Commit deae797. Normal review starts when eligible; priority review starts as soon as a slot is available.

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Final validation — Phase 2 only (queue backlog)

This PR moves error-triggered WebSocket resubscriptions to a single worker with a one-slot queue, so the event loop can keep draining responses while the writer reconnects. The Linux amd64 build, all six unit-test shards, app and ABCI CLI tests, both end-to-end jobs, lint, go vet, and govulncheck passed; the automated review check was still pending.

🟡 2 suggestion(s)

Approved: nothing here blocks the merge. The non-blocking findings are optional: fix them forward, in this PR or a follow-up, without waiting for another review round.

Review provenance

Source: reviewer 1: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.2-sol (agent: phase2-reviewer, role: tenderdash-consensus-security); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: low by gpt-6.2-sol (effort low) — The production change is confined to one WebSocket client loop and moves resubscription into a single worker with a bounded queue and explicit shutdown.
  • Phase 1 reviewers: not run (skipped for throughput: 11 PRs queued, above the 10 limit)
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-sol — general (completed, effort medium); agent phase2-reviewer, gpt-6.2-sol — tenderdash-consensus-security (completed, effort medium); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `rpc/client/http/ws_error_resubscribe_test.go`:
- [SUGGESTION] rpc/client/http/ws_error_resubscribe_test.go:104: The regression test hangs if the RPC error no longer starts a retry
  Impact: If a regression prevents the retry from reaching the writer, CI waits for the suite-wide timeout instead of reporting that the retry never started.
  The test cannot report a missing retry because `<-held` waits without a deadline. Only a write on the armed connection signals `held`, and the test's deferred cancellation and cleanup cannot run while the receive is blocked. Bound the wait and fail with a message that identifies the missing resubscribe write.
- [SUGGESTION] rpc/client/http/ws_error_resubscribe_test.go:105-107: The error-and-drop test passes even if event delivery never resumes after reconnect
  Impact: A regression that delivers the last event from the old connection but leaves existing subscribers silent after reconnect would pass this test.
  The test can pass without a successful redial or a restored subscription. The only asserted event comes from the original connection's `boom` response and can already be buffered before `release()` lets the write fail. The plain-reconnect test does not cover a reconnect with an error-triggered retry in flight. Keep the old-connection assertion, then have the fake upstream emit a distinct event when an existing query is resubscribed on the replacement connection and assert that it reaches the original subscriber channel.
Out-of-scope follow-up suggestions (1)

These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.

  • Oversized WebSocket responses can exhaust client memory — The unchanged transport in rpc/jsonrpc/client/ws_client.go:462 reads the entire message before JSON decoding, and the client does not configure a read limit. An untrusted RPC endpoint can exhaust the client's memory with an oversized response.
    • Follow-up: Open a separate PR to set a client-side WebSocket message limit that accommodates legitimate event payloads and handles limit violations as transport errors.


// The resubscribe's first write fails once the reader holds the event, which
// stops the writer before the next resubscribe.
<-held

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Suggestion: The regression test hangs if the RPC error no longer starts a retry
Impact: If a regression prevents the retry from reaching the writer, CI waits for the suite-wide timeout instead of reporting that the retry never started.

The test cannot report a missing retry because <-held waits without a deadline. Only a write on the armed connection signals held, and the test's deferred cancellation and cleanup cannot run while the receive is blocked. Bound the wait and fail with a message that identifies the missing resubscribe write.

Suggested change
<-held
select {
case <-held:
case <-time.After(5 * time.Second):
t.Fatal("resubscribe did not start a write after the RPC error")
}

source: gpt-6.2-sol (phase2-reviewer: general, tenderdash-consensus-security)

Comment on lines +105 to +107
require.Eventually(t, func() bool { return len(q1) == 1 || readerDelivering() }, 5*time.Second, time.Millisecond)
release()
requireEvent(t, q1, "q1")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Suggestion: The error-and-drop test passes even if event delivery never resumes after reconnect
Impact: A regression that delivers the last event from the old connection but leaves existing subscribers silent after reconnect would pass this test.

The test can pass without a successful redial or a restored subscription. The only asserted event comes from the original connection's boom response and can already be buffered before release() lets the write fail. The plain-reconnect test does not cover a reconnect with an error-triggered retry in flight. Keep the old-connection assertion, then have the fake upstream emit a distinct event when an existing query is resubscribed on the replacement connection and assert that it reaches the original subscriber channel.

source: gpt-6.2-sol (phase2-reviewer: general, tenderdash-consensus-security)

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Re-review — Final validation — Phase 1 + Phase 2

New on this head: This head merges the parent branch’s WebSocket orphan-cleanup changes and clarifies the shutdown test comment; the error-triggered retry worker is unchanged. The Linux build, all six test shards, end-to-end tests, go vet, and lint passed; the PastaClaw review is pending.

🟡 2 suggestion(s)

Approved: nothing here blocks the merge. The non-blocking findings are optional: fix them forward, in this PR or a follow-up, without waiting for another review round.

Still open from earlier rounds (2)

  • 🟡 Suggestion: The error-and-drop test passes even if event delivery never resumes after reconnect — rpc/client/http/ws_error_resubscribe_test.go:105-107 (thread)
  • 🟡 Suggestion: The regression test hangs if the RPC error no longer starts a retry — rpc/client/http/ws_error_resubscribe_test.go:104 (thread)
Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 3: gpt-6.2-sol (agent: phase2-reviewer, role: tenderdash-consensus-security); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: low by gpt-6.2-sol (effort low) — The behavior change is confined to the WebSocket RPC client, where a single worker and a one-slot queue move retries off the event loop without changing a critical surface.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort high); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (zai below 15% reserve: 5h 100% left, weekly 0% left)
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-sol — general (completed, effort medium); agent phase2-reviewer, gpt-6.2-sol — tenderdash-consensus-security (completed, effort medium); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `rpc/client/http/ws_error_resubscribe_test.go`:
- [SUGGESTION] rpc/client/http/ws_error_resubscribe_test.go:105-107: The error-and-drop test passes even if event delivery never resumes after reconnect
  (carried; thread: https://github.com/dashpay/tenderdash/pull/1642#discussion_r4700157042)
- [SUGGESTION] rpc/client/http/ws_error_resubscribe_test.go:104: The regression test hangs if the RPC error no longer starts a retry
  (carried; thread: https://github.com/dashpay/tenderdash/pull/1642#discussion_r4700157006)

…scribe

Squashed net change of fix/ws-error-resubscribe-hang up to 384eced,
restacked linearly on fix/ws-resubscribe-orphan. The original commits
(including the merges) remain reachable from 384eced.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@lklimek
lklimek force-pushed the fix/ws-error-resubscribe-hang branch from 50023a3 to deae797 Compare December 3, 2026 00:07

This branch has not been deployed

No deployments
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.

3 participants