Skip to content

fix(Async.catch+catchWith): Propagate :> OperationCanceledException - #21030

Open
bartelink wants to merge 1 commit into
dotnet:mainfrom
bartelink:async-stragglers
Open

bartelink wants to merge 1 commit into
dotnet:mainfrom
bartelink:async-stragglers

Conversation

@bartelink

@bartelink bartelink commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Adjusts two new FSharp.Core 11.0.1.0 APIs (Async.catch and Async.catchWith), covering two scenarios where they mishandle cancellation (trapping as Error/passing to handle rather than reraising) .

These deviate from the original intent, the sibling impls in Task, and the behavior as conveyed in their xmldoc.

(The inconsistencies got flagged during development of demystifyfp/FsToolkit.ErrorHandling#373)

@T-Gro

@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

✅ Release notes checked


✅ Found changes and release notes in following paths:

Change path Release notes path Description
`src/FSharp.Core` docs/release-notes/.FSharp.Core/11.0.200.md

@bartelink
bartelink marked this pull request as ready for review November 25, 2026 11:58
@bartelink
bartelink requested a review from a team as a code owner November 25, 2026 11:58
Copilot AI balanced review requested due to automatic review settings November 25, 2026 11:58

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Cancellation exceptions are rethrown with reset stack traces, and the Async.Catch documentation does not distinguish exception-continuation cancellation from cancellation that still propagates.

2 open issues
What changed in this PR

This PR updates FSharp.Core’s Async.catch and Async.catchWith to propagate cancellation exceptions instead of treating them as recoverable failures, aligning them with their documented behavior and Task equivalents.

Changes:

  • Propagate OperationCanceledException and derived exceptions without invoking recovery handlers.
  • Add regression tests for canceled awaited tasks and async cancellation.
  • Update API remarks and release notes.
File Description
tests/​FSharp.Core.UnitTests/​FSharp.Core/​Microsoft.FSharp.Control/​TaskModuleFunctions.fs Tests cancellation propagation through task wrappers.
tests/​FSharp.Core.UnitTests/​FSharp.Core/​Microsoft.FSharp.Control/​AsyncModuleFunctions.fs Adds cancellation coverage and contrasts legacy Async.Catch behavior.
src/​FSharp.Core/​async.fsi Documents cancellation behavior and the legacy API contrast.
src/​FSharp.Core/​async.fs Excludes cancellation exceptions from recovery handling.
docs/​release-notes/​.FSharp.Core/​11.0.200.md Records the cancellation propagation fix.

Review effort: Balanced

Comment thread src/FSharp.Core/async.fs
with e ->
return handler e
with
| :? OperationCanceledException as e -> return! raise e

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@T-Gro et al - I applied this advice. But would return! reraise () be equivalent but more legible?

(And, if so, should that also be applied in call sites where this is done in module Task and module Async ?)

Comment thread src/FSharp.Core/async.fsi Resolved
Comment thread src/FSharp.Core/async.fs
with e ->
return handler e
with
| :? OperationCanceledException as e -> return! raise e

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

But why special case OCE in a context of async CE? Async uses cancellation continuations, not exceptions, so the OCE here must originate from some non-async code. I'm not saying this is wrong, but a clarification would be helpful.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

see the resolved doc comment - that clarifies the scenario a bit more - all the normal Async-only scenarios are indeed fine, it's when Awaiting of Task that yield TaskCancelationException gets into the mix (perhaps they shouldn't; perhaps there's an improvement to Await that could render it impossible via that path?, but see the failing test cases). If you see the test cases I added for Task, the deviation in behavior in the shipped Async versions is clear.

Not sure what you mean by 'clarification' though - a comment here, more in the PR overview, xmldoc improvements?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Ah I get it now. We want same behavior as the equivalent Task functions.

I guess this makes me uneasy only because this is purely async, so special-casing task-related mechanisms feels wrong here. I mean a user of this function may reasonably expect it to catch all exceptions equally, glancing at it's signature.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

But they may equally not expect when they flip to and fro between Task and Async that stuff works the same - random internal signalling and residue resulting from cancellation should not cause devations in whether or not compensation behavior applies.

i.e. Async.Catch is a "do a full catch with no conditionality - I know you cant catch StackOverflow but gotta catch em all apart from that", whereas Async.catch is just Async.map Ok >> Async.catchWith Error - you are applying a compensation for an ordinary exception.

Remember that Catch, like async.Return is just borrowed internal machinery/wiring - the fact it doesnt trap cancellation is an impl coincidence more than a specified thing.

I agree its slightly mysterious, andf there may be a case to answer:

  • Tasks have Completed, Faulted and Cancelled states
  • BUT if I Async.Await a Task.FromCanceled, the Async emits the exception

So perhaps Async.Await should Cancel the Async when appliedTask.FromCanceled ?

Maybe....

Bottom line for me is that
a) the user would expect to Async and Task to align
b) most of the time Async does not show you a cancellation exception or let you do something in response to it, and the docs dont suggest you end up holding an OperationCanceledExcetion or TaskCanceledException when you operate on an Async
c) anything that makes the tests that used to fail pass and the documentation not need a "watch out for canceled tasks behaving differently if you go from Task.* to Async.*" proviso.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I mean a user of this function may reasonably expect it to catch all exceptions equally, glancing at it's signature.

Same point goes for Task.catch* BUT

  • doc already mentions cancellation is treated diffently in most cases
  • it is to a large degree

Personally this came as a surprise to me too - I didnt have it in the original impl, but Tomas and/or LLMs have flagged it and after some thought I agree with them. Once I got on board, I had a pretty clear rule that neither sets of helpers should trap, and I had convinced myself this was the case - only the interop with Await breaks that rule

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

So perhaps Async.Await should Cancel the Async when appliedTask.FromCanceled ?

The usual scenario is that the task returning cancellable function takes a ct parameter and we pass the ambient async token. Cancelling it, should cause the async wrapper to take the cancellation continuation anyway, instead of hitting the special case.
This way the only path that would hit the OCE in Async.Catch is when the OCE comes from a foreign ct, not the ambient one. IMV this should be a genuine exception.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I know about the usual scenario (Async.StartTaskImmediate etc) - but ultimately a Task can end up Completed, Canceled or Faulted. And when its Faulted, it can be an OCE or TCE. Atm Async.AwaitTask(Task.FromCancelled ) is trapped by Async.catch*, but not by Task.catch*. What prompts the TCE is one aspect; whether or not a prompting CT is supplied varies (some TFMs dont facilitate even doing so). As it stands, AFIACR Async.AwaitTask and Async.Await don't map anything to a cancelled Async state. If they did, Async.catch* would trap less cases. I can't say I understand the area inside out, but I know that an easy to explain rule that's consistent with something else is easier to explain and test. The notion of a 'foreign ct' seems fuzzy to me at this point, but perhaps others have deeper insight?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Ah, by foreign I meant simply other than the one the enclosing async runs with. To be clearer: OCE did not originate from current Async.CancellationToken.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I know - I get the intuitive notion you're trying to convey - however whether it's even possible to include the CancellationToken in the TCE depends on the TFM. In other words, I don't think there's a concrete way to infer from any given TCE whether it was prompted by a given cancellation. Which brings me back to having a broad rule of a TCE not being possible to compensate for in a catchWith, which is the same semantics that Task.cancelWith seeks to employ?

[<Fact>]
let ``Async.Catch treats Canceled Async as OperationCanceledException (sync)`` () =
let a = cancelledAsync<int>
Assert.Throws<OperationCanceledException>(fun () -> Async.Catch a |> Async.RunSynchronouslyImmediate :> obj) |> ignore

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is this async really cancelled? There is no cancellation token?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes. The minute you run it, it cancels itself, independent of a controlling ambient CT and./or a sibling or Async.Parallel etc doing it:

let cancelledAsync<'T> : Async<'T> =
    Async.FromContinuations(fun (_, _, cancel) ->
        cancel (OperationCanceledException()))

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: New

Development

Successfully merging this pull request may close these issues.

3 participants