Repository navigation
fix(rpc): release upstream subscriptions orphaned by a resubscribe - #1641
Claudius-Maginificent wants to merge 4 commits into
Conversation
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
|
|
🕓 Review not started yet because this PR is a draft.
Commit 9814460. Normal review starts when eligible; priority review starts as soon as a slot is available. |
thepastaclaw
left a comment
There was a problem hiding this comment.
Final validation — Phase 2 only (queue backlog)
Changes requested: 3 blockers
- Cleanup of a malformed query removes every subscription on the connection —
rpc/client/http/ws.go:314-318(new)
Impact: Clients sharing a light RPC proxy can miss events on unrelated streams when a malformed subscription is forgotten during upstream reconnect. - Reconnect cleanup silently cancels a live rejoin that uses different query spacing —
rpc/client/http/ws.go:311-316(new)
Impact: An application that rejoins the same event query with different spacing during reconnect can stop receiving events even though its replacement subscription was accepted. - A failed resubscribe write can restore a canceled query on the next connection —
rpc/client/http/ws.go:300-306(new)
Impact: An application whose unsubscribe times out during a second disconnect can lose a subscription slot even after the connection recovers.
This PR adds background cleanup for WebSocket subscriptions forgotten during resubscribe, waits for that cleanup at shutdown, and stops retrying on harmless unsubscribe errors. The Linux build, lint, and RPC HTTP client tests passed; test shard 04 failed separately because light.TestClientStatusRPC could not bind its listener (address already in use).
🔴 3 blocking | 🟡 1 suggestion(s)
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); reviewer 3: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.2-sol (agent: phase2-reviewer, role: tenderdash-consensus-security); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
normalbygpt-6.2-sol(effort low) — The fix is confined to the WebSocket RPC client, but verifying cleanup ordering across reconnects, concurrent joins, and shutdown requires careful reasoning without touching a critical surface. - Phase 1 reviewers: not run (skipped for throughput: 11 PRs queued, above the 10 limit)
- Second Phase-2 pass: on this first full review every Phase-2 reviewer also ran a second, independent time, and the verifier weighed both sets
- Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.2-sol— general (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— tenderdash-consensus-security (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— general (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— tenderdash-consensus-security (completed, effort high); agentphase2-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.go`:
- [BLOCKING] rpc/client/http/ws.go:314-318: Cleanup of a malformed query removes every subscription on the connection
Impact: Clients sharing a light RPC proxy can miss events on unrelated streams when a malformed subscription is forgotten during upstream reconnect.
A malformed query that never had an upstream subscription can still shut down all active streams on the shared connection. The light proxy forwards queries without parsing them, and `wsEvents.Subscribe` records them after writer handoff, before the node accepts or rejects them. If a downstream disconnect forgets a malformed query during its resend and the bounded disconnect cleanup expires while the writer is unavailable, the new orphan worker can send the malformed unsubscribe after valid streams have been restored. On parse failure, `internal/rpc/core/events.go:115–121` leaves `args.Query` nil and sets `args.ID`, but `internal/pubsub/pubsub.go:247–260` ignores the ID and removes every subscription for that connection. The server treats those removals as client-requested and sends no termination notice to the affected streams. Reject invalid queries before tracking them, or at minimum skip automatic cleanup for them; the server should also reject a malformed query or match the requested ID rather than widening the operation.
- [BLOCKING] rpc/client/http/ws.go:311-316: Reconnect cleanup silently cancels a live rejoin that uses different query spacing
Impact: An application that rejoins the same event query with different spacing during reconnect can stop receiving events even though its replacement subscription was accepted.
The orphan worker can remove the replacement subscriber's live stream without clearing its local registration or notifying it. If the replacement spelling reaches the node before the old spelling is resent, the node accepts the replacement and rejects the resend as a duplicate. The client only sees writer handoff, and its locked ownership check at `rpc/client/http/ws.go:250–257` looks up the old raw string. The node instead uses parsed `Query.String()` for both duplicate detection and removal (`internal/pubsub/pubsub.go:209,251`), so the compensating unsubscribe removes the replacement's stream. Use the node's canonical query identity for ownership checks and route incoming events using the same identity, since the node echoes the original request text. Add a regression with the replacement accepted first against the real RPC handlers or a test upstream that canonicalizes queries.
- [BLOCKING] rpc/client/http/ws.go:300-306: A failed resubscribe write can restore a canceled query on the next connection
Impact: An application whose unsubscribe times out during a second disconnect can lose a subscription slot even after the connection recovers.
The node can retain a subscription the client has forgotten, and another unsubscribe for that query sends nothing because the local entry is already gone. `WSClient.Send` returns at writer handoff, so the post-send check can see the query still present and schedule no cleanup. If the write fails, `writeRoutine` saves the subscribe in the backlog. A last leave during the next reconnect removes the local entry immediately, but its unsubscribe can time out while there is no writer. The next resubscribe pass then skips the query while `processBacklog` replays the saved subscribe before starting the new writer (`rpc/jsonrpc/client/ws_client.go:334–349,381–384,409–420`). Keep cleanup pending when a last leave cannot hand off its unsubscribe, and recheck ownership before sending it after replay. Add coverage for a write that fails after handoff; the current test only delays handoff.
In `rpc/client/http/ws_join_leave_test.go`:
- [SUGGESTION] rpc/client/http/ws_join_leave_test.go:163-168: Reconnect tests can read upstream state before orphan cleanup runs
Impact: The release test can fail on correct code, and the rejoin test can pass before a broken cleanup removes the live subscription.
The assertions can observe the session too early. Closing `resubscribed` means the resend returned after launching the cleanup worker, but a stack snapshot can still find zero frames in `unsubscribeOrphan` if the worker has not entered the function. The `sync` request can then be processed before the orphan unsubscribe rather than after it. Once the resend has finished scheduling cleanup, use a bounded wait for the tracked worker before sending `sync`.
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.
- Inline error recovery can stall WebSocket reconnect — The existing event loop can block resubscribing while the writer is down. Reconnect waits for the reader to exit, but the reader can be blocked delivering a response to that same event loop. Moving the new orphan worker off the event loop does not change this pre-existing cycle.
- Follow-up: Track a separate PR to run error-triggered resubscriptions outside the response loop with bounded, coalesced recovery work and a reconnect regression test.
|
Re thepastaclaw's review, out-of-scope follow-up "Inline error recovery can stall WebSocket reconnect": handled in #1642, which runs error-triggered resubscription outside the response loop and is stacked on this pull request. 🤖 Co-authored by Claudius the Magnificent AI Agent |
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
Changes requested: 1 blocker
- A replacement subscriber gets no events when the old query spelling is restored first —
rpc/client/http/ws.go:335-347(new)
Impact: An application that cancels and rejoins an equivalent query with different spacing during reconnect can get a successful Subscribe call but silently miss every matching event, even after retrying Subscribe on the same connection.
New on this head: This revision makes reconnect cleanup compare canonical query keys, skip malformed orphan queries, and wait for cleanup workers before checking upstream state in tests. On the reviewed head, the build, lint, vet, and test checks passed; the PastaClaw review check is still pending.
🔴 1 blocking | 🟡 2 suggestion(s)
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:
normalbygpt-6.2-sol(effort low) — The fix is confined to RPC client subscription lifecycle logic, but verifying lock ordering, reconnect behavior, and shutdown requires careful review without changing a critical surface. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity quota lookup failed),glm-5.3-flash(not used above high effort; tier asks max) - New since the last final review (
ea487c2b): 1 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 1 confirmed - Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.2-sol— general (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— tenderdash-consensus-security (completed, effort high); agentphase2-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.go`:
- [BLOCKING] rpc/client/http/ws.go:335-347: A replacement subscriber gets no events when the old query spelling is restored first
Impact: An application that cancels and rejoins an equivalent query with different spacing during reconnect can get a successful Subscribe call but silently miss every matching event, even after retrying Subscribe on the same connection.
The replacement channel stays silent even though the node is publishing matching events. A caller of the public HTTP client's subscription API can cancel a query while its reconnect resend is waiting for the writer: Unsubscribe removes the local entry immediately, even if its context expires before it can send. If the caller rejoins with different spacing and the old resend reaches the node first, the node accepts the old spelling and rejects the replacement as a canonical duplicate (`internal/pubsub/pubsub.go:203–211`). The replacement still registers locally because Subscribe waits only for writer handoff (`ws.go:148–168`), and the listener ignores the duplicate response. The new guard then treats that local entry as an owner, but the node echoes the accepted request's old spelling (`internal/rpc/core/events.go:86–91`) and dispatch looks it up verbatim (`ws.go:394–401`). The previous cleanup could clear that stale stream, letting a later Subscribe succeed; now a retry with the replacement spelling still hits the duplicate. Use one validated query key for local ownership and event dispatch, retain valid request text for sends, and test delivery with each spelling accepted first.
_Confirmed by an independent pass: During a WebSocket reconnect, a caller of HTTP.Unsubscribe can remove its last local subscription while the reconnect callback is handing the old query to the writer, and the unsubscribe context can expire before its own request is sent. If the caller then uses HTTP.Subscribe with a differently spaced version of the same query and the old resend reaches the node first, the call returns a channel even though the node rejects the replacement as a duplicate. The new cleanup guard leaves the old stream in place, but incoming events still carry the old query text and are dropped by the client's exact-text lookup, so the replacement channel misses matching events and another Subscribe with the same replacement text does not restore delivery._
- [SUGGESTION] rpc/client/http/ws.go:350-355: A rejected overlong query can keep a canceled subscription alive
Impact: Clients sharing a light RPC proxy can lose an upstream subscription slot when a canceled query is restored during reconnect and its only apparent owner is a request the node rejected.
Cleanup can leave a canceled subscription occupying a slot with no usable local owner. The light proxy forwards the query unchanged (`light/proxy/routes.go:127–129`, `light/rpc/client.go:663–671`), and Subscribe records it after writer handoff, not node acceptance. The node rejects query text over 512 bytes before parsing (`internal/rpc/core/events.go:22–39`), but the new ownership check only parses it. Because the parser skips whitespace, an overlong spelling can compare equal to the canceled short spelling and suppress cleanup where the previous raw-key check would not. Apply the server's query-length rule before registering a local subscription so rejected overlong requests cannot count as owners.
In `rpc/client/http/ws_join_leave_test.go`:
- [SUGGESTION] rpc/client/http/ws_join_leave_test.go:164-173: The replacement-first test can see the resend arrive first
Impact: The regression test can fail its request-order assertion under scheduler contention even when orphan cleanup behaves correctly.
The test can fail at lines 319–320 without an orphan-cleanup defect. `goroutinesIn` confirms that the replacement has a `WSClient.Send` stack frame, not that it has queued at the channel select (`rpc/jsonrpc/client/ws_client.go:206–218`). If the replacement pauses before queueing, the test can start the resend and let it queue first, reversing the order the assertions require. Use a barrier that fixes the send order, or exercise the cleanup guard directly after the fake upstream confirms it accepted the replacement.
| w.mtx.RLock() | ||
| used := false | ||
| for q := range w.subscriptions { | ||
| if owned, err := canonicalQuery(q); err == nil && owned == canonical { | ||
| used = true | ||
| break | ||
| } | ||
| } | ||
| w.mtx.RUnlock() | ||
| if used { | ||
| return nil | ||
| } | ||
| return w.ws.Unsubscribe(ctx, query) |
There was a problem hiding this comment.
🔴 Blocking: A replacement subscriber gets no events when the old query spelling is restored first
Impact: An application that cancels and rejoins an equivalent query with different spacing during reconnect can get a successful Subscribe call but silently miss every matching event, even after retrying Subscribe on the same connection.
The replacement channel stays silent even though the node is publishing matching events. A caller of the public HTTP client's subscription API can cancel a query while its reconnect resend is waiting for the writer: Unsubscribe removes the local entry immediately, even if its context expires before it can send. If the caller rejoins with different spacing and the old resend reaches the node first, the node accepts the old spelling and rejects the replacement as a canonical duplicate (internal/pubsub/pubsub.go:203–211). The replacement still registers locally because Subscribe waits only for writer handoff (ws.go:148–168), and the listener ignores the duplicate response. The new guard then treats that local entry as an owner, but the node echoes the accepted request's old spelling (internal/rpc/core/events.go:86–91) and dispatch looks it up verbatim (ws.go:394–401). The previous cleanup could clear that stale stream, letting a later Subscribe succeed; now a retry with the replacement spelling still hits the duplicate. Use one validated query key for local ownership and event dispatch, retain valid request text for sends, and test delivery with each spelling accepted first.
Confirmed by an independent pass: During a WebSocket reconnect, a caller of HTTP.Unsubscribe can remove its last local subscription while the reconnect callback is handing the old query to the writer, and the unsubscribe context can expire before its own request is sent. If the caller then uses HTTP.Subscribe with a differently spaced version of the same query and the old resend reaches the node first, the call returns a channel even though the node rejects the replacement as a duplicate. The new cleanup guard leaves the old stream in place, but incoming events still carry the old query text and are dropped by the client's exact-text lookup, so the replacement channel misses matching events and another Subscribe with the same replacement text does not restore delivery.
source: muse-spark-1.3-contributor (phase1-reviewer: general); gpt-6.2-sol (phase2-reviewer: general, tenderdash-consensus-security)
| func canonicalQuery(query string) (string, error) { | ||
| q, err := tmquery.New(query) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
| return q.String(), nil |
There was a problem hiding this comment.
🟡 Suggestion: A rejected overlong query can keep a canceled subscription alive
Impact: Clients sharing a light RPC proxy can lose an upstream subscription slot when a canceled query is restored during reconnect and its only apparent owner is a request the node rejected.
Cleanup can leave a canceled subscription occupying a slot with no usable local owner. The light proxy forwards the query unchanged (light/proxy/routes.go:127–129, light/rpc/client.go:663–671), and Subscribe records it after writer handoff, not node acceptance. The node rejects query text over 512 bytes before parsing (internal/rpc/core/events.go:22–39), but the new ownership check only parses it. Because the parser skips whitespace, an overlong spelling can compare equal to the canceled short spelling and suppress cleanup where the previous raw-key check would not. Apply the server's query-length rule before registering a local subscription so rejected overlong requests cannot count as owners.
source: gpt-6.2-sol (phase2-reviewer: general, tenderdash-consensus-security)
| if replacement != "" { | ||
| // Queue the live stream first so the upstream accepts it before the resend. | ||
| sending := goroutinesIn("(*WSClient).Send") | ||
| joined := make(chan error, 1) | ||
| go func() { | ||
| _, err := w.Subscribe(ctx, "B", replacement) | ||
| joined <- err | ||
| }() | ||
| require.Eventually(t, func() bool { return goroutinesIn("(*WSClient).Send") == sending+1 }, | ||
| 5*time.Second, time.Millisecond) |
There was a problem hiding this comment.
🟡 Suggestion: The replacement-first test can see the resend arrive first
Impact: The regression test can fail its request-order assertion under scheduler contention even when orphan cleanup behaves correctly.
The test can fail at lines 319–320 without an orphan-cleanup defect. goroutinesIn confirms that the replacement has a WSClient.Send stack frame, not that it has queued at the channel select (rpc/jsonrpc/client/ws_client.go:206–218). If the replacement pauses before queueing, the test can start the resend and let it queue first, reversing the order the assertions require. Use a barrier that fixes the send order, or exercise the cleanup guard directly after the fake upstream confirms it accepted the replacement.
source: gpt-6.2-sol (phase2-reviewer: general, tenderdash-consensus-security)
30d6182 to
e5ad03c
Compare
e5ad03c to
db48a28
Compare
Squashed net change of this branch up to a54153c, restacked linearly on its parent layer. The original commits (including the merges) remain reachable from a54153c. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…or log Stop is now tested to wait for a blocked unsubscribeOrphan; ignored harmless subscription errors log a message distinct from errors that trigger a resubscribe; a test comment describes the asynchronous orphan unsubscribe. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ptions The node removes subscriptions by canonical query, and treats a query it cannot parse as a subscription ID, which removes every subscription of the client. Orphan cleanup now skips queries that do not parse and keeps the upstream subscription while a canonically equal query still has a local owner. Tests wait for tracked orphan cleanup before synchronizing with the upstream, so they no longer assert before the cleanup has started. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A recorded query always has a subscriber: the last leave deletes it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
d79ec0b to
9814460
Compare
TL;DR: An RPC client that drops an event subscription while it is reconnecting no longer leaves that subscription behind on the node, where it used up one of the client's limited subscription slots.
User story
As a developer using the Tenderdash RPC client's event subscriptions, I want subscriptions I cancel during a reconnect to be released on the node, so that my client keeps its full subscription quota and new subscriptions keep working.
Scenario
Base flow
A client subscribes to events over WebSocket. The connection drops and the client reconnects, re-creating its subscriptions on the node. While that is happening, the application cancels one of those subscriptions.
Actual behavior
The cancellation can reach the node before the re-created subscription does. The node then keeps a subscription the client has forgotten. It counts against the client's per-connection subscription limit until the next reconnect, and the client never cancels it. Once the limit is full, new subscriptions fail and the client keeps retrying.
Expected behavior
A subscription cancelled during a reconnect is also released on the node.
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 5 of 6, base
fix/light-proxy-ws-worker-lifetime; depends on #1639, #1515, #1627, #1600; merge them first (bottom-up). Each PR carries only its own changes. The dependency on #1639 is ordering only.What was done
Scope: only the orphaned upstream subscription from the #1515 review thread on
rpc/client/http/ws.go(#1515 (comment)).redoSubscriptionsAfter: after a successful resubscribe ofq, ifqwas forgotten during the send, a goroutine runsunsubscribeOrphan. It takes thechangeslock and sendsunsubscribe(q)only if no locally owned query is canonically equal toq(the node keys and removes subscriptions by canonical query):qholdschangesacross its own subscribe and recordsqbefore releasing it, so it is never cancelled.changesthere can deadlock. A holder's send can wait for the writer restart, which waits for the reader, which waits for the event loop to take its response.qthat does not parse is skipped: the node would treat it as a subscription ID and remove every subscription of the connection.Stopjoins these goroutines.resubscribeDelayand resubscribed all queries, and the cleanup above can provoke it routinely, when a leave and the cleanup both unsubscribeq.Out of scope: other
wsEventslocking changes.Known limitations:
dev; fixed in fix(rpc): keep the event loop running during an error-triggered resubscribe #1642, stacked on this PR).Unsubscribe/UnsubscribeAllstill send the caller's query text as is: a malformed one, or a different spelling of a query another subscriber still uses, can remove more upstream subscriptions than intended (pre-existing; tracked in light proxy: connections sharing a remote address share subscriptions, and Local-backed unsubscribe misses equivalent queries #1644).Testing
TestResubscribeOfForgottenQueryIsUnsubscribed: a cleanup that times out forgetsqwhile its resubscribe waits for the writer. Without the fix the upstream keepsq(failed with "the forgotten query stayed subscribed upstream").TestResubscribeOfForgottenQueryKeepsRejoin: another subscriber re-joinsqduring the resubscribe;qstays subscribed upstream. A variant that unsubscribes without the lock fails it.TestSubscriptionNotFoundDoesNotResubscribe: withresubscribeDelayof an hour, an event queued after a "subscription not found" reply is still delivered (failed without the fix:event for "q" was not delivered).Stopis tested to wait for a blocked orphan cleanup (fails without theorphanswait).TestOrphanCleanupPreservesLiveQuery: a forgotten query that is a different spelling of a live one (canonical_rejoin), or that does not parse (malformed_query), is not unsubscribed upstream and the live stream keeps its events (both failed before the fix).go test -p 1 -race -count=1 ./rpc/client/http/and-tags deadlock: pass. The join/leave stress test passes under-race -count=5. golangci-lint on the package with--new-from-rev=origin/fix/base-service-stopis clean.Breaking changes
None.
Prior work
wsEventssubscription bookkeeping and documents this orphan as a known limitation.Attribution
🤖 Generated with Claude Code
🤖 Co-authored by Claudius the Magnificent AI Agent