Repository navigation
fix(light): retire WebSocket forwarders with their subscriptions - #1639
Claudius-Maginificent wants to merge 14 commits into
Conversation
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
|
|
⛔ Final review complete — 1 blocking finding(s) (commit ec3066a) · triage: normal · Phase 2 only (queue backlog) |
thepastaclaw
left a comment
There was a problem hiding this comment.
Final validation — Phase 2 only (queue backlog)
Changes requested: 1 blocker
- Closing one Unix WebSocket can silence another session and leave its workers running —
light/rpc/client.go:686-696(new)
Impact: On a supported Unix-socket light proxy, an ordinary client disconnect can silently stop another session's event delivery and leave a forwarder and session waiter running for each lost subscription.
The patch adds a per-connection, per-query registry to retire light-proxy WebSocket workers on subscription replacement and unsubscribe, with regression tests for worker cleanup and rejected admission. GitHub CI passed the build, lint, vet, vulnerability scan, unit tests, and end-to-end tests on this head; the automated review check is still pending. This was a static review.
🔴 1 blocking | 🟡 3 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 change is confined to light RPC subscription lifetimes, but cancellation, replacement, and registry cleanup require careful reasoning about concurrent workers without changing 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 `light/rpc/client.go`:
- [BLOCKING] light/rpc/client.go:686-696: Closing one Unix WebSocket can silence another session and leave its workers running
Impact: On a supported Unix-socket light proxy, an ordinary client disconnect can silently stop another session's event delivery and leave a forwarder and session waiter running for each lost subscription.
A session can lose all its subscriptions while its socket stays open, even if the departing client never subscribed. Unnamed Unix peers share a remote address. `SubscribeWS` registers that address as the HTTP backend's subscriber but keys the new worker registry by connection. The joined disconnect callback (`light/proxy/proxy.go:110–119`) removes all subscriptions for the shared address, and `UnsubscribeAllWS` does the same while retiring only the caller's workers. The HTTP backend leaves the result channels open, so neither path wakes the other session's workers. The shared-address mock test verifies that a live forwarder is not canceled, but it does not exercise backend ownership. Use a stable subscriber ID per session for subscribe, both unsubscribe methods, rejected-admission cleanup, and disconnect cleanup. Add a test with the HTTP backend that checks that the surviving session still receives events.
- [SUGGESTION] light/rpc/client.go:757-759: Unsubscribe leaves removed subscriptions' workers running during upstream reconnect
Impact: If the provider is reconnecting, an unsubscribe can hold the downstream request handler and both workers per removed subscription through minutes of backoff.
The workers stay alive after the HTTP backend has already removed their subscriptions. Both HTTP unsubscribe methods remove local subscribers and close their private `gone` signals before `unsubscribeUpstream` waits for the change lock or WebSocket writer (`rpc/client/http/ws.go:174–255`). The proxy passes the session context without an operation deadline and retires workers only after that call returns. Requests on the same socket are serialized, so this delays retirement rather than accumulating workers across completed requests. Bound the unsubscribe call as disconnect cleanup already does, or let the proxy observe local removal separately from the upstream send so the workers can exit immediately.
- [SUGGESTION] light/rpc/client.go:743-746: Unsubscribing with different query spacing leaves Local-backed workers running
Impact: A Local-backed proxy can retain both workers until the session ends even though unsubscribe succeeded and the event bus no longer has the subscription.
The proxy misses worker retirement for a successful query-based unsubscribe, not just for subscription IDs. For example, Local parses `tm.event='NewBlock'` and `tm.event = 'NewBlock'` to the same canonical query, which pubsub uses to find and remove the subscription (`rpc/client/local/local.go:312–324`, `internal/pubsub/pubsub.go:247–260`). The new registry instead matches the raw request text, and Local's event routine returns without closing the result channel. Use the backend's subscription identity or termination signal to retire the correct workers, and cover equivalent query spellings in a Local-backed test. Do not normalize the proxy lookup indiscriminately: the HTTP backend keys its local subscriptions by exact query text.
- [SUGGESTION] light/rpc/client.go:743-746: Direct Go calls to unsubscribe panic without RPC metadata
Impact: A Go caller passing a plain context to either exported WebSocket unsubscribe method now panics after the backend call instead of receiving its result.
`GetCallInfo` returns nil for a plain context, and the base implementation's nil-safe `RemoteAddr()` call let both methods delegate to the backend and return its result. The new retirement code dereferences `callInfo.WSConn` in both methods after delegation. The production WebSocket dispatcher always attaches this metadata, so the regression is limited to direct callers. Skip registry retirement when there is no WebSocket call record, and extend the existing cancellation test to exercise a context with no `CallInfo`.
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.
- Proxy workers stay alive when the upstream WebSocket stops reconnecting — On reconnect exhaustion, the upstream WebSocket closes
ResponsesChand the HTTP event listener exits without notifying consumers of the per-subscriber result channels. Downstream sessions can remain open, retaining both workers until explicit retirement or session shutdown. This is a terminal transport failure, separate from the replacement and unsubscribe paths changed here. PR #1641 addresses orphaned subscriptions on the upstream node, not this termination path.- Follow-up: Add a follow-up PR to propagate terminal subscription shutdown from the HTTP backend to the proxy without closing the legacy result channels.
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
Changes requested: 1 blocker
- Retrying a timed-out unsubscribe reports success without freeing upstream subscription slots —
light/rpc/client.go:763-768(new)
Impact: After a brief upstream write stall, a light-proxy client can successfully retry an unsubscribe while stale subscriptions still count against the quota shared by every session on that proxy.
New on this head: This revision adds a one-second deadline to both light-proxy WebSocket unsubscribe handlers and lets direct Go callers use them without WebSocket metadata. The Linux build, all six test shards, both end-to-end jobs, vet, and lint passed; the PastaClaw review check is still pending.
🔴 1 blocking
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 change is contained to light-proxy RPC, but coordinating forwarder replacement, cancellation, and cleanup across unsubscribe and timeout paths warrants 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 (
aad9e65d): 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 `light/rpc/client.go`:
- [BLOCKING] light/rpc/client.go:763-768: Retrying a timed-out unsubscribe reports success without freeing upstream subscription slots
Impact: After a brief upstream write stall, a light-proxy client can successfully retry an unsubscribe while stale subscriptions still count against the quota shared by every session on that proxy.
A client switching event streams can get success from a retried `unsubscribe_all` yet receive no events for its new queries if the old ones still fill the provider's quota. The default proxy shares one upstream WebSocket. If network backpressure keeps its writer busy past the new one-second deadline but the write completes before the transport's ten-second deadline, the socket stays open (`rpc/jsonrpc/client/ws_client.go:203–218,407–420`). The HTTP backend has already removed the last local owners, so timing out before the unsubscribe reaches the writer discards the only list of queries to remove. A retry or downstream disconnect finds no local entries and sends nothing (`rpc/client/http/ws.go:174–255`). The provider still counts those queries and rejects new ones once its quota is full (`internal/rpc/core/events.go:29–36`). The same regression applies to `UnsubscribeWS`: on the previous head, an explicit unsubscribe could wait out the stall while the downstream session stayed open. Keep local retirement bounded, but retain pending upstream removals for that connection and recheck ownership before sending them when the writer resumes. Add a regression that recovers the writer without reconnecting and verifies that a new subscription receives events.
_Confirmed by an independent pass: A light-proxy WebSocket client switching event streams can call `unsubscribe_all` while it is the last local owner of queries that fill the provider's shared subscription quota. If transient backpressure stalls the upstream writer past the new one-second deadline but clears before the transport's ten-second write deadline, the proxy forgets those subscriptions without sending their removals, and the upstream socket stays open. Retrying reports success without freeing any slots, so the provider rejects new queries on that socket and clients receive no events for them._
7a28dcc to
96c282e
Compare
96c282e to
ee2221c
Compare
Squashed net change of this branch up to 9734246, restacked linearly on its parent layer. The original commits (including the merges) remain reachable from 9734246. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Unsubscribing scanned every connection's forwarders under the registry lock; a client sending unsubscribe frames for unknown queries could keep that lock busy. Look the forwarder up by connection and query, and drop a connection's map once empty. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…Info UnsubscribeWS and UnsubscribeAllWS bound the backend call to one second, still ending with the session, so a reconnecting upstream no longer keeps the retired subscription's forwarders running. Forwarders are retired only for a known WebSocket connection, so direct Go calls without CallInfo return the backend result instead of panicking. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
… client's lifetime SubscribeWS contacted the upstream before its forwarder was admitted. When shutdown rejected the forwarder, the rollback Unsubscribe ran outside any joined worker, so a caller-owned upstream could receive it after the light client's Wait returned. Admit the whole subscription transaction, including its rollback, as a worker before contacting the upstream. Co-Authored-By: Claude Opus 5.5 <[email protected]>
0e396cb to
55840e2
Compare
The HTTP backend forgets a subscription before sending its upstream removal. When UnsubscribeWS or UnsubscribeAllWS stopped waiting after one second, the removal was cancelled with it, so a retry found nothing to remove and the provider kept the subscription. Run the backend call as a client worker: the caller still waits at most one second and its forwarders are retired, while the removal completes once the upstream writer resumes, bounded by the light client's lifetime. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A backend that stays blocked (for example the Local event bus behind a slow observer) left one client worker per repeated unsubscribe. A connection now runs one backend unsubscribe at a time: a later request waits for it within the one-second bound and otherwise returns the timeout without calling the backend or retiring forwarders the backend still feeds. The client's lifetime is read only once it is running, and a pending removal is canceled and joined when the client stops. Co-Authored-By: Claude Opus 5.5 <[email protected]>
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
Changes requested: 1 blocker
- Retrying a timed-out unsubscribe reports success without freeing upstream subscription slots —
light/rpc/client.go:753-764(thread, carried)
Impact: A light-proxy WebSocket client retrying after transient upstream backpressure can get a successful unsubscribe response while the node still counts the abandoned subscription against the proxy's shared quota.
New on this head: This revision makes light-client shutdown wait for the entire WebSocket subscribe transaction, including rollback if worker admission fails. The build, tests, lint, vet, vulnerability scan, and protocol checks passed; PR Hygiene and PastaClaw review are still pending.
🔴 1 blocking
Still open from earlier rounds (1)
- 🔴 Blocking: Retrying a timed-out unsubscribe reports success without freeing upstream subscription slots —
light/rpc/client.go:753-764(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:
normalbygpt-6.2-sol(effort low) — This is a substantial but contained behavioral change to light RPC WebSocket subscription lifecycle and concurrent goroutine management, requiring careful validation of cancellation, races, and backend interaction but not altering a critical consensus, cryptographic, funds, or storage 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) - 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 `light/rpc/client.go`:
- [BLOCKING] light/rpc/client.go:753-764: Retrying a timed-out unsubscribe reports success without freeing upstream subscription slots
(carried; thread: https://github.com/dashpay/tenderdash/pull/1639#discussion_r4705184773)
The light client cancels a WebSocket forwarder's context when it retires the subscription, possibly while the removal still waits for the event bus. The events routine then resubscribed and could re-add the query after its removal ran, so the session could not subscribe to it again. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A running client now runs every unsubscribe as a client worker, so a caller without WebSocket metadata also gets its answer within one second. Once the client has stopped, unsubscribe fails instead of calling a backend that could outlive Wait. A caller whose deadline ends while it waits for the connection's running removal no longer starts another. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A resubscription waiting for the event bus could run after a removal of the same subscriber and add the subscription back, although its caller had already given up. SubscribeWithArgs now checks the context once it holds the lock. The light client also no longer starts a backend unsubscribe for a request already canceled, and its docs note that the one-second bound applies once the client has started. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-remote test Run the second connection's SubscribeWS in a goroutine with a timeout, so a regression that makes it wait for the first connection's call fails the test instead of blocking it until the package timeout. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Waiting for bot review — thepastaclaw reviewed an earlier commit, not yet this one. Wait for the missing reviews, or a writer can post |
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 2 only (queue backlog)
Changes requested: 1 blocker
- A slow index write during block catch-up can abort validator startup —
internal/pubsub/pubsub.go:203-211(new)
Impact: An operator restarting a validator with KV indexing enabled can seetenderdash startfail even though the index write eventually succeeds.
New on this head: This revision lets a pending upstream WebSocket removal finish after the downstream request times out, retires the affected forwarders within the request’s wait bound, and prevents canceled Local subscriptions from being re-added. At the reviewed head, the Linux build, test shards, end-to-end jobs, lint, and vet passed; PR Hygiene and PastaClaw review are pending.
🔴 1 blocking | 🟡 3 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); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
normalbygpt-6.2-sol(effort low) — This is a substantial, cross-cutting change to WebSocket subscription lifecycle, backend cancellation, goroutine management, and pubsub concurrency, but it does not alter consensus, cryptography, funds, signatures, peer-facing deserialization, or storage migrations. - Phase 1 reviewers: not run (skipped for throughput: 24 PRs queued, above the 10 limit)
- New since the last final review (
55840e29): 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 `internal/pubsub/pubsub.go`:
- [BLOCKING] internal/pubsub/pubsub.go:203-211: A slow index write during block catch-up can abort validator startup
Impact: An operator restarting a validator with KV indexing enabled can see `tenderdash start` fail even though the index write eventually succeeds.
A temporary indexing delay can now prevent a validator from starting. When an operator restarts a validator behind the chain, the node starts the indexer, P2P router, and block-sync workers before the validator connection executor (`node/node.go:543–553, 617–630`; service order at `399–406, 456–474`). Block sync can finalize a valid committed block during that startup window, and pubsub holds `subs.RLock` while the indexer processes the block and performs synchronous KV writes (`internal/state/execution.go:650–655`, `internal/pubsub/pubsub.go:401–414`, `internal/state/indexer/block/kv/kv.go:53–73`, `internal/state/indexer/tx/kv/kv.go:67–97`). If that work holds the lock through the executor’s one-second subscription deadline, the new check returns `DeadlineExceeded` after the lock is released; previously the subscription succeeded at that point. The executor does not retry (`dash/quorum/validator_conn_executor.go:162–164, 192–205`), so the node rolls back startup and the CLI reports failure. Keep the cancellation check for abandoned subscriptions, but pass the executor’s startup context to this required subscription instead of imposing the one-second setup deadline.
_Confirmed by an independent pass: When an operator restarts a validator that is behind the chain with KV indexing enabled, block sync can finalize a valid block before the validator connection executor finishes starting. If the indexer's synchronous write holds the pubsub read lock through the executor's one-second subscription deadline, `SubscribeWithArgs` returns `context.DeadlineExceeded` once it acquires the lock; the executor does not retry, so the node rolls back startup and `tenderdash start` returns an error._
In `light/rpc/client.go`:
- [SUGGESTION] light/rpc/client.go:823-827: A stalled upstream removal makes an unrelated local unsubscribe time out
Impact: A light-proxy WebSocket client can time out when leaving a shared query and keep receiving its events after recovery, even though leaving it requires no upstream request.
Leaving query B can fail simply because the same connection’s removal of query A is still waiting for the upstream writer. With two distinct backend subscribers on B, removing one would leave B in use, so the HTTP backend would finish without acquiring the upstream changes lock or sending anything (`rpc/client/http/ws.go:216–243`). The new connection-wide gate waits for all of A’s backend call before letting B reach the backend. If B’s request times out at that gate, neither its local subscription nor its forwarder is removed. Separate local removal from pending upstream sends so the proxy can retire B’s forwarder once local removal is confirmed, while the backend preserves pending sends and rechecks query ownership before sending.
- [SUGGESTION] light/rpc/client.go:834-846: A timed-out Local unsubscribe can stall light-client shutdown
Impact: An application wrapping a running node’s Local RPC client can receive an unsubscribe timeout and then remain blocked in the light client’s `Wait` until the node’s event bus becomes available.
The one-second bound releases the caller but does not release the new service-owned worker. Both Local unsubscribe methods delegate to pubsub methods that ignore their context and acquire `subs.Lock` unconditionally (`rpc/client/local/local.go:314–330`, `internal/pubsub/pubsub.go:235–272`). If the shared bus is still indexing under its read lock, stopping the light client cancels the worker’s context without interrupting that wait. `BaseService` joins the worker before `OnDrain` can skip cleanup of the caller-owned backend (`libs/service/service.go:186–198`, `light/rpc/client.go:149–154`). Make the Local removal’s wait for the bus cancellable by the light client’s lifetime so the wrapper can shut down independently of the node.
- [SUGGESTION] light/rpc/client.go:812-822: An already-canceled unsubscribe can remove subscriptions before the light client starts
Impact: A Go caller wrapping an already-running HTTP backend can pass a canceled context to either WebSocket unsubscribe method and still lose backend subscriptions.
An already-canceled request can still mutate the backend because the new pre-start branch delegates inline before the cancellation check. Both HTTP unsubscribe methods delete matching local subscribers before consulting the context for any upstream send (`rpc/client/http/ws.go:174–200`). The backend can therefore remove a subscription even when the wrapper returns a cancellation error, or return success if no upstream send is needed. Keep inline delegation for live pre-start calls, but check cancellation before delegating on that path as well.
| func (s *Server) SubscribeWithArgs(ctx context.Context, args SubscribeArgs) (*Subscription, error) { | ||
| s.subs.Lock() | ||
| defer s.subs.Unlock() | ||
|
|
||
| if s.subs.index == nil { | ||
| // Checked under the lock: a caller that gave up while waiting for it must | ||
| // not be subscribed after a removal that ran in the meantime. | ||
| if err := ctx.Err(); err != nil { | ||
| return nil, err | ||
| } else if s.subs.index == nil { |
There was a problem hiding this comment.
🔴 Blocking: A slow index write during block catch-up can abort validator startup
Impact: An operator restarting a validator with KV indexing enabled can see tenderdash start fail even though the index write eventually succeeds.
A temporary indexing delay can now prevent a validator from starting. When an operator restarts a validator behind the chain, the node starts the indexer, P2P router, and block-sync workers before the validator connection executor (node/node.go:543–553, 617–630; service order at 399–406, 456–474). Block sync can finalize a valid committed block during that startup window, and pubsub holds subs.RLock while the indexer processes the block and performs synchronous KV writes (internal/state/execution.go:650–655, internal/pubsub/pubsub.go:401–414, internal/state/indexer/block/kv/kv.go:53–73, internal/state/indexer/tx/kv/kv.go:67–97). If that work holds the lock through the executor’s one-second subscription deadline, the new check returns DeadlineExceeded after the lock is released; previously the subscription succeeded at that point. The executor does not retry (dash/quorum/validator_conn_executor.go:162–164, 192–205), so the node rolls back startup and the CLI reports failure. Keep the cancellation check for abandoned subscriptions, but pass the executor’s startup context to this required subscription instead of imposing the one-second setup deadline.
Confirmed by an independent pass: When an operator restarts a validator that is behind the chain with KV indexing enabled, block sync can finalize a valid block before the validator connection executor finishes starting. If the indexer's synchronous write holds the pubsub read lock through the executor's one-second subscription deadline, SubscribeWithArgs returns context.DeadlineExceeded once it acquires the lock; the executor does not retry, so the node rolls back startup and tenderdash start returns an error.
source: gpt-6.2-sol (phase2-reviewer: general, tenderdash-consensus-security)
| var done chan struct{} | ||
| if conn != nil { | ||
| if done, err = c.claimWSUnsubscribe(ctx, conn); err != nil { | ||
| return false, err | ||
| } |
There was a problem hiding this comment.
🟡 Suggestion: A stalled upstream removal makes an unrelated local unsubscribe time out
Impact: A light-proxy WebSocket client can time out when leaving a shared query and keep receiving its events after recovery, even though leaving it requires no upstream request.
Leaving query B can fail simply because the same connection’s removal of query A is still waiting for the upstream writer. With two distinct backend subscribers on B, removing one would leave B in use, so the HTTP backend would finish without acquiring the upstream changes lock or sending anything (rpc/client/http/ws.go:216–243). The new connection-wide gate waits for all of A’s backend call before letting B reach the backend. If B’s request times out at that gate, neither its local subscription nor its forwarder is removed. Separate local removal from pending upstream sends so the proxy can retire B’s forwarder once local removal is confirmed, while the backend preserves pending sends and rechecks query ownership before sending.
source: gpt-6.2-sol (phase2-reviewer: general, tenderdash-consensus-security)
| result := make(chan error, 1) | ||
| if !c.Go(c.serviceCtx, func(ctx context.Context) { | ||
| defer release() | ||
| result <- call(ctx) | ||
| }) { | ||
| release() | ||
| return false, errClientNotRunning | ||
| } | ||
| select { | ||
| case err := <-result: | ||
| return true, err | ||
| case <-ctx.Done(): | ||
| return true, ctx.Err() |
There was a problem hiding this comment.
🟡 Suggestion: A timed-out Local unsubscribe can stall light-client shutdown
Impact: An application wrapping a running node’s Local RPC client can receive an unsubscribe timeout and then remain blocked in the light client’s Wait until the node’s event bus becomes available.
The one-second bound releases the caller but does not release the new service-owned worker. Both Local unsubscribe methods delegate to pubsub methods that ignore their context and acquire subs.Lock unconditionally (rpc/client/local/local.go:314–330, internal/pubsub/pubsub.go:235–272). If the shared bus is still indexing under its read lock, stopping the light client cancels the worker’s context without interrupting that wait. BaseService joins the worker before OnDrain can skip cleanup of the caller-owned backend (libs/service/service.go:186–198, light/rpc/client.go:149–154). Make the Local removal’s wait for the bus cancellable by the light client’s lifetime so the wrapper can shut down independently of the node.
source: gpt-6.2-sol (phase2-reviewer: general, tenderdash-consensus-security)
| ctx, cancel := context.WithTimeout(ctx, wsUnsubscribeTimeout) | ||
| defer cancel() | ||
| if !c.IsRunning() { | ||
| if c.Stopping() != nil { | ||
| return false, errClientNotRunning | ||
| } | ||
| return true, call(ctx) | ||
| } | ||
| if err := ctx.Err(); err != nil { | ||
| return false, err | ||
| } |
There was a problem hiding this comment.
🟡 Suggestion: An already-canceled unsubscribe can remove subscriptions before the light client starts
Impact: A Go caller wrapping an already-running HTTP backend can pass a canceled context to either WebSocket unsubscribe method and still lose backend subscriptions.
An already-canceled request can still mutate the backend because the new pre-start branch delegates inline before the cancellation check. Both HTTP unsubscribe methods delete matching local subscribers before consulting the context for any upstream send (rpc/client/http/ws.go:174–200). The backend can therefore remove a subscription even when the wrapper returns a cancellation error, or return success if no upstream send is needed. Keep inline delegation for live pre-start calls, but check cancellation before delegating on that path as well.
source: gpt-6.2-sol (phase2-reviewer: general, tenderdash-consensus-security)
TL;DR: The light proxy no longer keeps two goroutines alive for every WebSocket subscription that was replaced or unsubscribed; they now exit together with their subscription.
User story
As a light-proxy operator, I want a client that keeps subscribing and unsubscribing over one WebSocket to use a bounded number of goroutines, so a misbehaving or hostile client cannot exhaust the proxy.
Scenario
Base flow
Actual behavior
Each round leaves one forwarding worker and one session worker running until the whole WebSocket session or the proxy stops.
Expected behavior
Both workers exit as soon as their subscription is replaced or removed, while the session's other subscriptions keep delivering events.
Detailed discussion
Stack: builds on #1600, #1627 and #1515, which are merged; base
dev. #1641 and #1642 are stacked on this PR (a manual stack, since native stacked PRs are not enabled for this repository). Each PR carries only its own changes.What was done
light/rpc.Clienttracks each forwarder's cancel function per WebSocket connection, then per query, so an unsubscribe looks up only the caller's forwarders. A connection retires only its own forwarders, and since its requests are handled one at a time, the forwarder it retires always reads a channel the backend has already dropped.UnsubscribeWS/UnsubscribeAllWS— also when the backend call fails, because the backend forgets the subscription in that case too.UnsubscribeWS/UnsubscribeAllWSwait at most one second for the backend (still ending with the session), so an upstream reconnect does not keep a retired subscription's forwarders running. The backend call itself runs as a light-client worker: the HTTP backend forgets a subscription before sending its upstream removal, so a removal that outlasts the wait is still sent once the upstream writer resumes (bounded by the light client's lifetime) instead of being dropped. A connection runs one such backend call at a time; a further request waits for it within the same bound and otherwise returns the timeout without calling the backend or retiring its forwarders. Called directly from Go without WebSocket call metadata, they are bounded the same way and retire nothing, and a request already canceled starts no backend call; before the client starts they call the backend inline, and once it has stopped they fail without calling it.SubscribeWSadmits the whole subscription transaction (the upstreamSubscribeand any rollbackUnsubscribe) as a client worker before contacting the upstream, so no upstream call from it can happen after the light client'sWaitreturns (review thread).internal/pubsub) no longer adds a subscription whose context ended while it waited for the bus, so a forwarder retired while its removal still waits cannot bring the removed subscription back.rpc/client/http.It fixes the leak reported in this review thread, which predates #1515 (on
devthese workers live for the whole process; #1515 bounds them to the session).Out of scope: proxy-wide limits on subscriptions or sessions; verifying forwarded events (existing
TODO: verify data); any change to therpc/client/httpbackend.Known limitations:
unix://listener) still share one backend subscriber per query, because the backend keys subscribers by remote address. One such connection can take over or remove another's backend subscription; the other connection's forwarder then gets no events until that connection resubscribes, unsubscribes, or disconnects. Forwarders are retired only by their own connection, so retiring one never leaves a live backend channel unread. Pre-existing; tracked in light proxy: connections sharing a remote address share subscriptions, and Local-backed unsubscribe misses equivalent queries #1644.UnsubscribeAllWS, the subscription stays on the bus with no reader until the session ends, and subscribing to the same query again in that session fails withErrAlreadySubscribed. Pre-existing ondevand independent of the one-second bound; tracked in light proxy: connections sharing a remote address share subscriptions, and Local-backed unsubscribe misses equivalent queries #1644.Testing
light/rpc/subscribe_test.go:TestSubscribeWSReplacementRetiresWorkers,TestUnsubscribeWSRetiresWorkers,TestUnsubscribeAllWSRetiresWorkers,TestUnsubscribeWSRetiresWorkersOnBackendError,TestSubscribeWSSharedRemoteKeepsLiveForwarder; inlight/rpc/unsubscribe_test.go:TestUnsubscribeWSTimeoutRetiresWorkers(a backend whose send stalls past the one-second wait: the caller gets the timeout, its forwarders retire, and the removal still completes when the writer resumes)TestUnsubscribeWSTimeoutRemovalEndsWithClient(stopping the client cancels and joins a pending removal),TestUnsubscribeWSWhileRemovalPending(one backend unsubscribe per connection at a time)TestUnsubscribeWSWithoutConnection(no call metadata, both methods),TestUnsubscribeWithoutConnectionBounded(no call metadata, backend ignoring its deadline),TestUnsubscribeCanceledBeforeCallandTestUnsubscribeAfterStopRejected. Inrpc/client/local/local_test.go:TestSubscriptionEndedByContextStaysRemoved; ininternal/pubsub/pubsub_test.go:TestSubscribeWithArgsCanceledWhileWaiting. Inlight/rpc/subscribe_admission_test.go:TestSubscribeWSWaitJoinsTransaction(Waitdoes not return while a subscription transaction, including its rollback after either admission is rejected, still uses the upstream). They assert that removed subscriptions' workers exit, that subscriptions which should stay alive still forward events, that the registry tracks exactly the live subscriptions, and that two connections sharing a remote address never retire each other's live forwarder. They fail on the base commit (and under mutations of the registry cleanup, identity check and error-path retirement) and pass with the fix.go test -race -count=1 ./light/rpc/ ./light/proxy/passes, also with-tags deadlock;-count=20on the new tests passes;go vetandgolangci-lint --new-from-revonlight/rpcare clean.Breaking changes
None.
Prior work
Attribution
🤖 Co-authored by Claudius the Magnificent AI Agent
🤖 Generated with Claude Code
PR Hygiene ·
ec3066ainternal/pubsub/pubsub.go,internal/pubsub/pubsub_test.go,light/rpc/client.goand 5 more) — lklimek or shumkovWhen every merge requirement is met, the
PR Hygienecheck passes. Reviewer limits do not block merging; other required GitHub checks and protections still apply.