Skip to content

handle failed handler copies in AsyncClient safely - #18653

Merged
kevinushey merged 4 commits into
mainfrom
bugfix/18625-asyncclient-handler-snapshot
Aug 27, 2026
Merged

kevinushey merged 4 commits into
mainfrom
bugfix/18625-asyncclient-handler-snapshot

Conversation

@kevinushey

@kevinushey kevinushey commented Aug 26, 2026 •

Copy link
Copy Markdown
Collaborator

Intent

Addresses #18625, a follow-up from #18541.

AsyncClient moves boost::function handlers across socketMutex_ in two directions, and both were unsafe if a copy threw. Copying a boost::function allocates 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 used LOCK_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 to response_, 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 the fixedBufferHandler_ 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() and closeAndRespond() additionally read an indeterminate disabled flag 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 into response_.
  • 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 explicit boost::lock_guard and reporting Ready, Disabled, or Failed. The lambda it runs keeps each site's own handlersDisabled_ test in the same critical section as its own copies, which is the property disableHandlers()'s contract comment depends on; Failed takes the client's ordinary error path (handleUnexpectedError()), which closes the client, reports through the ErrorHandler, 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() sets requestWritten_ only after a successful copy. close() and disableHandlers() 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 these void setters, 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 a ThrowOnCopy<F> callback target whose copy constructor throws std::bad_alloc once armed. Each was confirmed to fail against the unfixed code with exactly the symptom described above:

Test Symptom without the fix
FixedBufferHandlerSnapshotFailureMidBodyFailsRatherThanDroppingPiece sawFinalSignal == true after only the first of two pieces was delivered
ResponseHandlerSnapshotFailureAtCompletionFailsRatherThanRespondingEmpty ResponseHandler invoked with an empty body for a fully streamed response
ConnectHandlerSnapshotFailureReportsDownstreamClosedRatherThanDropping neither notification delivered; the request read to completion behind the caller's back
ExecuteHandlerInstallFailureLeavesNothingInMotion the connection ran to failure anyway, and left the client closed so a retry reported nothing
FixedBufferHandlerInstallFailureKeepsTheInstalledHandler the installed streaming consumer was lost; the body silently fell back to being buffered
ConnectHandlerInstallFailureKeepsTheInstalledPair the previously registered pair was destroyed, so the settle had nowhere to report

ExecuteHandlerInstallFailureLeavesNothingInMotion deliberately aims at a dead port rather than a LocalServer: what it asserts is that nothing is set in motion at all, and LocalServer's accept loop blocks until a connection arrives, so a regression there would hang the harness teardown instead of failing.

Full rstudio-core-tests suite 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

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.
@github-actions

github-actions Bot commented Aug 26, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

#################### 100% pass rate

Passed Failed Skipped Flaky
2428 0 161 1
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 2 0 10 0
✅ desktop-linux 606 0 31 0
✅ desktop-macos 603 0 35 0
✅ desktop-windows 611 0 31 1
✅ server-linux 580 0 44 0
✅ setup 26 0 10 0
View / download the full report

View report online -- opens in the browser, no download needed. Available for 14 days.

Download playwright-report.zip -- extract and open index.html

Includes screenshots, traces, and step-by-step details for every test. Expires in 15 days.


All platforms - commit 721e02a31ad75170f33f6e632f506de04b8cdd45 - Run #717

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.
@kevinushey kevinushey changed the title handle failed handler snapshots in AsyncClient as errors handle failed handler copies in AsyncClient safely Aug 26, 2026
// 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);

@gtritchie gtritchie Aug 26, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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:

  1. streaming response, fixedBufferHandlerSupportsPause_ set; closeAndRespond() snapshots Ready, keepConnectionAlive() is false so close() runs -> closed_ = true;
  2. fixedBufferHandler(response_, "") returns false under backpressure -> completionPending_ = true, return;
  3. resumeChunkProcessing() re-enters closeAndRespond(); this time the copy throws bad_alloc;
  4. Failed -> handleUnexpectedError() -> handleError() sees closed_ 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.

@kevinushey kevinushey Aug 27, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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);

@gtritchie gtritchie Aug 26, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@kevinushey kevinushey Aug 27, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@kevinushey
kevinushey merged commit a9238e1 into main Aug 27, 2026
7 of 12 checks passed
@kevinushey
kevinushey deleted the bugfix/18625-asyncclient-handler-snapshot branch August 27, 2026 18:25
@gtritchie gtritchie mentioned this pull request Aug 31, 2026
3 of 4 tasks

This branch was previously deployed

1 inactive deployment
e2e-playwright — 721e02a3 Deployed Aug 27, 2026 by kevinushey via windows / e2e-desktop-windows (6) #717
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.

2 participants