Repository navigation
Conversation
✅ Release notes checked
|
c9278cb to
bf3aace
Compare
bf3aace to
9c91b90
Compare
There was a problem hiding this comment.
🟡 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
OperationCanceledExceptionand 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
| with e -> | ||
| return handler e | ||
| with | ||
| | :? OperationCanceledException as e -> return! raise e |
There was a problem hiding this comment.
@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 ?)
| with e -> | ||
| return handler e | ||
| with | ||
| | :? OperationCanceledException as e -> return! raise e |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
Is this async really cancelled? There is no cancellation token?
There was a problem hiding this comment.
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()))


Adjusts two new FSharp.Core 11.0.1.0 APIs (
Async.catchandAsync.catchWith), covering two scenarios where they mishandle cancellation (trapping asError/passing tohandlerather 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