Skip to content

[BUG] Report one outcome when a curl session is cancelled after the response arrives - #4363

Merged
marcalff merged 4 commits into
open-telemetry:mainfrom
thc1006:bugfix/curl-single-terminal-callback
Aug 5, 2026
Merged

marcalff merged 4 commits into
open-telemetry:mainfrom
thc1006:bugfix/curl-single-terminal-callback

Conversation

@thc1006

@thc1006 thc1006 commented Aug 5, 2026 •

Copy link
Copy Markdown
Member

Part of #4360, which lists three problems in the shared curl client's callback contract.
This is only the one with a single obvious answer. The other two need a decision I would
rather hear first, and they are still open on the issue.

What happens

Session::SendRequest passes this completion callback to SendAsync:

if (operation.WasAborted())
{
  callback->OnEvent(SessionState::Cancelled, "");
}

if (operation.GetSessionState() == SessionState::Response)
{
  ...
  callback->OnResponse(*response);
}

Two independent ifs, and the two conditions are not exclusive. HttpOperation::Abort
raises is_aborted_ and schedules the abort; it does not touch the session state. So a
transfer that has already been answered, and then cancelled, satisfies both, and the handler
is told the request was cancelled and given its response.

The window is not narrow. PerformCurlMessage dispatches Response and then calls
Cleanup, which is where the completion callback runs, and nothing between them is
synchronised against Abort. HttpClient::CancelAllSessions is what Shutdown calls, so
shutting down while a response is arriving lands in it.

What it costs in tree

OtlpHttpClient::ResponseHandler already guards against being finished twice: both
OnResponse and the terminal OnEvent states take stopping_ with a compare and exchange,
and only the winner calls Unbind. Because the client delivers Cancelled first, the
winner is the failure. Unbind moves the result callback out, so the response that follows
finds nothing to report and the export is recorded as failed while the server has it.

That is the reason to fix it here rather than in the consumers. A first writer guard cannot
pick the right outcome when it is handed the wrong one first.

Why the response wins

The state only reaches Response when the transfer succeeded: on a non-CURLE_OK result
PerformCurlMessage dispatches ConnectFailed or SendFailed first, which moves the state
out of the Connecting/Connected/Sending chain the Response transition needs. A
Response state therefore means the server answered.

That also makes it the safer of the two to report. Telling a caller its request was
cancelled when the server had already accepted it invites a retry, and for an exporter that
means writing the same batch twice.

Cancelled is unchanged for a cancel that lands while the request is still in flight, which
is the case it was written for.

What this leaves

The Cancelled arm can still double up with what Cleanup sends. Cleanup dispatches
Cancelled itself whenever the state is still Created, Connecting, Connected or
Sending, and then runs this callback, so an operation aborted in flight and torn down
through Session::FinishOperation reports Cancelled twice. The second case below measures
exactly that, two notifications for one request, which is why it asserts at least one rather
than one. An aborted operation whose transfer failed is the same shape, the failure state and
then Cancelled.

Each of those says one thing twice rather than two different things, and the consumers
collapse them: OtlpHttpClient through stopping_, the Elasticsearch synchronous handler
through recordCompletion, and its asynchronous handler not at all, which is #4338.

Dropping this arm entirely would close those too, but that decides which layer owns the
event rather than correcting an outcome, and it is the third item on #4360. What this change
covers is the one pairing where the two notifications disagree and the wrong one wins.

Test

ACancelAfterTheResponseReportsOneOutcome cancels from inside the handler's Response
event. That is not a lucky interleaving: DispatchEvent notifies the handler and only then
stores the new state, and the completion callback runs after both, so by the time it is
reached the operation is aborted and its state is Response. Cancelling from the handler
also keeps CancelSession on the thread that owns the curl handle, which is where the
background loop already is.

The handler counts terminal notifications and the case asserts one.

terminal notifications
http_client_curl.cc reverted to main, test kept Expected equality of these values: 1 ... Which is: 2
this branch 1

ACancelBeforeTheResponseReportsCancelled covers the other arm, which nothing in the suite
reached, so the line that reports a cancelled request was never run and Codecov saw the patch
at 50 per cent. The server handler takes mtx_requests before it answers, so holding it keeps
a response from racing the cancel, and the abort is torn down through
Session::FinishOperation while the transfer is still in flight.

Two Cancelled arrive, one from Cleanup and one from this callback, so counting them all
would stay green whether or not the arm ran. GetCurlErrorMessage never yields an empty
string, so Cleanup's carries a reason and the callback's never does, and the case counts the
empty one. Deleting the arm turns it red at 0 against 1. The total is deliberately not
asserted, since the doubling is the separate question above.

This one characterises rather than reproduces: it passes on main too, where the same arm
runs from the first if. What it adds is that the line cannot go uncovered again unnoticed.

gcov on the changed lines, from the suite: the response test drives OnResponse 24 times, the
else if is evaluated 7 times, and its body runs once, where before it ran not at all.

21 of 21 in curl_http_test, clang-format clean, and clang-tidy under the CI header filters
reports the same set as main for both files.

Checklist

  • CHANGELOG.md updated for non-trivial changes
  • Unit tests have been added
  • Changes in public API reviewed: no signatures change. A handler that used to receive
    Cancelled followed by OnResponse for one request now receives only OnResponse. For the
    OTLP HTTP exporter that turns a shutdown racing a response from a reported failure into the
    result the server actually returned.

The async completion callback tested WasAborted() and a Response session
state with two independent ifs, and the two are not exclusive. Cancelling
only raises a flag, so a transfer that has already been answered still
runs both arms, and a handler treating either as terminal counts one
request twice.

Only the transfer failing moves the state away from Sending, so a
Response state means the server answered. That is the outcome worth
reporting, and it is also the safe one: telling a caller its request was
cancelled after the server accepted it invites a retry that writes the
same batch again.

Reachable through Shutdown, which calls CancelAllSessions while requests
are in flight.
The comment claimed a request finishes once, which is wider than this
change. A cancel arriving while the transfer fails still yields the
dispatched failure state and then Cancelled; only the response case is
made exclusive here.
@codecov

codecov Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 81.77%. Comparing base (3a228da) to head (ee7d59f).

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #4363      +/-   ##
==========================================
+ Coverage   81.63%   81.77%   +0.15%     
==========================================
  Files         493      493              
  Lines       19456    19456              
==========================================
+ Hits        15880    15909      +29     
+ Misses       3576     3547      -29     
Files with missing lines Coverage Δ
ext/src/http/client/curl/http_client_curl.cc 86.64% <100.00%> (+4.38%) ⬆️

... and 2 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Codecov put the patch at 50 per cent: nothing in the suite reached a
cancel that gets as far as the callback, so the line reporting it never
ran. The server handler takes mtx_requests before answering, so holding
it keeps a response from racing the cancel while the abort is torn down
through Session::FinishOperation.

gcov on the changed lines: the else if runs 7 times and its body once,
where the body was previously never reached.

The case asserts at least one Cancelled rather than exactly one. It
measures two, one dispatched by Cleanup while the state is still in
flight and one from this callback, and that doubling is not what this
change decides.

@lalitb lalitb left a comment

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.

Thanks.

The previous assertion counted any Cancelled, so it stayed green whether
or not the arm ran: Cleanup dispatches its own before the callback. It
therefore covered the line without guarding it.

GetCurlErrorMessage never yields an empty string, so Cleanup's Cancelled
always carries a reason and the callback's never does. Counting the empty
one names the arm exactly. Removing the arm turns the case red with 0
against 1, which the count alone did not do.

@marcalff marcalff left a comment

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.

LGTM, thanks for the fix and tests.

@marcalff
marcalff merged commit a7da83e into open-telemetry:main Aug 5, 2026
72 checks passed
@thc1006
thc1006 deleted the bugfix/curl-single-terminal-callback branch August 5, 2026 20:16
@dbarker

dbarker commented Aug 5, 2026

Copy link
Copy Markdown
Member

TSAN caught a race in one of the tests from PR. Please see #4369 for the logs. This may be an existing bug in the curl client. @thc1006 are you tracking this one?

@thc1006

thc1006 commented Aug 6, 2026 •

Copy link
Copy Markdown
Member Author

Yes, tracking it. I put the detail on #4369 so it sits with the logs.

Short of it: CancelSession writes to the easy handle through curl_easy_setopt while the IO thread is driving that same handle. Any cancel off the IO thread does that, Shutdown() included. The new case just makes the window land often enough to get caught.

Fix is built and green locally. I asked over there which of two routes you'd rather have before I send it.

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.

4 participants