Repository navigation
handle failed handler copies in AsyncClient safely - #18653
Conversation
AsyncClient copies its boost::function handler members out from under socketMutex_ before invoking them. Those snapshots used LOCK_MUTEX / END_LOCK_MUTEX, whose unexpected-exception path logs and falls through -- so a copy that threw (allocation failure being the realistic trigger) left the locals empty, and every site read that as "no handler installed": - deliverChunks() appended the piece to response_, which nothing in streaming mode ever reads, and went on to tell the consumer the body was complete one piece short - closeAndRespond() handed a streamed response to the whole-body handler with an empty response_ body, or settled with no notification at all - handleWrite() dropped the connect notification, leaving a caller gated on it (FormProxy) buffering until it timed out The lock-acquisition path also left deliverChunks() and closeAndRespond() reading an indeterminate `disabled` flag. Snapshots now go through snapshotHandlers(), which reports ready, disabled or failed; failed takes the client's ordinary error path. closeAndRespond() takes its snapshot before the close so that path is still open to it, and handleWrite() sets requestWritten_ only after a successful copy, so a failure routes the pending connect notification to the downstream-closed handler rather than dropping it. Addresses #18625.
RStudio E2E - all platformsAll tests passed!
View / download the full reportView report online -- opens in the browser, no download needed. Available for 14 days. Download playwright-report.zip -- extract and open
All platforms - commit |
The sites that store handlers copied them under socketMutex_ interleaved with the assignments, so a copy that threw left the client half-configured -- and LOCK_MUTEX logged it and stepped over it: - execute() installed a response handler with no error handler behind it, then set the request in motion anyway, so the exchange could complete with nobody left to notify - setFixedBufferHandler() detached the installed handler before copying the replacement into its place, so a failure left no fixed buffer handler at all -- silently flipping a streaming consumer into accumulating into response_, a body nothing then reads - setConnectHandler() stored the connect notification while losing the downstream-closed handler that reports its loss, leaving a caller with no way to be told either way Every copy now happens before the lock, with only swaps under it, so an install either lands whole or changes nothing and the exception reaches the caller -- which, unlike these void setters, has a stack to handle it on. Addresses #18625.
| // branches below would read as absent and settle silently -- either | ||
| // handing a streamed response to the whole-body handler with an empty | ||
| // response_ body, or completing with no notification delivered at all. | ||
| handleUnexpectedError("Failed to copy response handlers", ERROR_LOCATION); |
There was a problem hiding this comment.
Severity: blocking.
A failed snapshot is still silently dropped once closed_ is set.
All three Failed paths route through handleUnexpectedError() -> handleError(), and handleError() returns immediately when closed_ is already true (AsyncClient.hpp:784-789) -- before the error handler and before disableHandlers(). Taking the snapshot before this call's close() doesn't help when an earlier call already closed.
The completionPending_ retry is a guaranteed-closed path:
- streaming response,
fixedBufferHandlerSupportsPause_set;closeAndRespond()snapshotsReady,keepConnectionAlive()is false soclose()runs ->closed_ = true; fixedBufferHandler(response_, "")returns false under backpressure ->completionPending_ = true, return;resumeChunkProcessing()re-enterscloseAndRespond(); this time the copy throwsbad_alloc;Failed->handleUnexpectedError()->handleError()seesclosed_and returns.
Net result: no completion signal, no error report, disableHandlers() never runs, so the fixedBufferHandler_ <-> FixedBufferProxy cycle stays intact and the client, the proxy and the browser connection leak with the request hung -- the exact outcome this PR set out to eliminate.
deliverChunks()'s Failed path has the same exposure whenever a chunk delivery is in flight after a bare close() (embedder teardown, ServerSessionProxy closing a streaming client to stop it), since a bare close() sets closed_ but not handlersDisabled_, so the snapshot is still admitted and can still fail.
Why blocking: this is a regression, not just an incomplete fix. Pre-PR, a thrown copy here was swallowed by END_LOCK_MUTEX and control fell through to the disableHandlers() at the end of closeAndRespond() -- the failure went unreported, but the cycle still got broken. Post-PR, Failed returns early and handleError() no-ops on closed_, so disableHandlers() never runs at all. On the completionPending_ retry, which is always post-close(), that turns a silent-but-cleaned-up settle into a permanent leak.
There was a problem hiding this comment.
Fixed in 65cefca. Handler snapshot failures now use a settlement path that still runs when the client is already closed, so the completionPending_ retry and bare-close cases cannot skip disableHandlers(). Added a regression test that backpressures the completion signal, fails the retry snapshot after close, and verifies both error delivery and cycle release.
| oldDownstreamClosedHandler.swap(downstreamClosedHandler_); | ||
| connectHandler_ = connectHandler; | ||
| downstreamClosedHandler_ = downstreamClosedHandler; | ||
| connectHandler_.swap(newConnectHandler); |
There was a problem hiding this comment.
Severity: non-blocking (follow-up / cleanup).
The deferConnectNotification branch never uses newConnectHandler/newDownstreamClosedHandler: the post below copy-captures the original parameters again --
// line 678
[self, connectHandler, downstreamClosedHandler]()So on that path the two pre-lock copies are pure waste, and the fallible copy still happens after the decision was taken under the lock -- the property this change exists to establish doesn't hold there. A bad_alloc in the capture (or in post itself) escapes setConnectHandler() with the notification neither stored nor deferred: no downstream-closed report, and -- per the FormProxy::initialize() comment above -- the throw unwinds into the io_context worker.
Reachable whenever the connect+write completes before the posted onClientCreated runs, which is a real race for a LocalStream connect to an already-listening session socket (it's why deliverLateConnectNotification() exists).
Fix: capture the copies already made before the lock -- [self, connectHandler = std::move(newConnectHandler), downstreamClosedHandler = std::move(newDownstreamClosedHandler)] -- which removes both the duplicate allocations and the fallible copy after the lock.
Why non-blocking: no behavior regression -- duplicate allocations on one branch, and an invariant that doesn't hold where it's claimed to. Cleanup.
There was a problem hiding this comment.
Included in 65cefca. The deferred branch now move-captures newConnectHandler and newDownstreamClosedHandler, and the already-settled branch invokes the pre-copied downstream handler as well, so neither branch re-copies the original parameters after the locked decision.
Intent
Addresses #18625, a follow-up from #18541.
AsyncClientmovesboost::functionhandlers acrosssocketMutex_in two directions, and both were unsafe if a copy threw. Copying aboost::functionallocates whenever the target is too large for its small-object buffer, so allocation failure -- the memory pressure streaming exists to relieve -- is the realistic trigger. Both directions usedLOCK_MUTEX/END_LOCK_MUTEX, whose unexpected-exception path logs and continues, so in every case execution ran on over half-finished state.Reading handlers out (snapshots), where the empty local reads as "no handler installed":
deliverChunks()-- the decoded piece is appended toresponse_, which nothing in streaming mode ever reads, and the consumer is then told the body is complete, one piece short.closeAndRespond()--responseHandler_is copied first, so a failure on thefixedBufferHandler_copy leaves the surviving response handler to be invoked: a "successful" empty-body response for a body that in fact streamed in full.handleWrite()-- the connect notification is dropped, and a caller gated on it (FormProxy) buffers the upload until it times out.Both
deliverChunks()andcloseAndRespond()additionally read an indeterminatedisabledflag if lock acquisition itself threw, since the flag was declared uninitialized and assigned inside the critical section.Writing handlers in (installs), where a failure leaves the client half-configured:
execute()-- a response handler installed with no error handler behind it, and the request set in motion anyway, so the exchange can complete with nobody left to notify.setFixedBufferHandler()-- the installed handler is detached before the replacement is copied into its place, so a failure leaves no fixed buffer handler at all, silently flipping a streaming consumer into accumulating intoresponse_.setConnectHandler()-- the connect notification stored while the downstream-closed handler that reports its loss is lost, leaving a caller with no way to be told either way.Approach
Snapshots go through a small
snapshotHandlers()helper taking an explicitboost::lock_guardand reportingReady,Disabled, orFailed. The lambda it runs keeps each site's ownhandlersDisabled_test in the same critical section as its own copies, which is the propertydisableHandlers()'s contract comment depends on;Failedtakes the client's ordinary error path (handleUnexpectedError()), which closes the client, reports through theErrorHandler, and detaches the handlers. Two details are load-bearing:closeAndRespond()takes its snapshot before the close.handleError()ignores anything raised after a deliberate close, so a failure discovered afterwards would be dropped without reporting or detaching anything.handleWrite()setsrequestWritten_only after a successful copy.close()anddisableHandlers()read that flag as "the connect notification was reported"; a failed copy can never report it, so leaving it false routes the still-pending notification to the downstream-closed handler -- the answer a caller gated on the connect needs to hear.Installs use copy-then-swap: every copy happens before the lock, and only
swap()runs under it. An install now either lands whole or changes nothing, and the exception reaches the caller -- which, unlike thesevoidsetters, has a stack to handle it on. This is a deliberate change from "swallow and continue half-configured" to "propagate with nothing changed"; the callers (FixedBufferProxy::proxy(),ServerSessionProxy,FormProxy::initialize()) all run inside the connection's existing exception guards.Automated Tests
Six fault-injection tests in
AsyncClientContentLengthTests.cpp, one per site, driven by aThrowOnCopy<F>callback target whose copy constructor throwsstd::bad_alloconce armed. Each was confirmed to fail against the unfixed code with exactly the symptom described above:FixedBufferHandlerSnapshotFailureMidBodyFailsRatherThanDroppingPiecesawFinalSignal == trueafter only the first of two pieces was deliveredResponseHandlerSnapshotFailureAtCompletionFailsRatherThanRespondingEmptyResponseHandlerinvoked with an empty body for a fully streamed responseConnectHandlerSnapshotFailureReportsDownstreamClosedRatherThanDroppingExecuteHandlerInstallFailureLeavesNothingInMotionFixedBufferHandlerInstallFailureKeepsTheInstalledHandlerConnectHandlerInstallFailureKeepsTheInstalledPairExecuteHandlerInstallFailureLeavesNothingInMotiondeliberately aims at a dead port rather than aLocalServer: what it asserts is that nothing is set in motion at all, andLocalServer's accept loop blocks until a connection arrives, so a regression there would hang the harness teardown instead of failing.Full
rstudio-core-testssuite passes (621 passed, 8 environment-dependent skips). The one unrelated failure seen in a whole-suite run,AsyncConnectionImpl.ContinueParsingResumesOnTheConnectionsStrand, is the known pre-existing flake tracked in #18634 and passes in isolation.QA Notes
No user-visible behavior change on any path that does not throw. The failures this addresses are not reachable by ordinary operation, so there is nothing to exercise manually; the coverage is the fault-injection tests above.
Documentation
None required.
Checklist
If this PR adds a new feature, or fixes a bug in a previously released version, it includes an entry in
NEWS.mdNot applicable: the streaming proxy this hardens (HTTP proxying of unchunked responses buffers entire response to memory #18546 / Stream localhost proxy responses #18541) is itself unreleased, so no official-release user has encountered this.
If this PR adds or changes UI, the updated UI meets accessibility standards
A reviewer is assigned to this PR (if unsure who to assign, check Area Owners list)
This PR passes all local unit tests