Skip to content

TryFinallyAsync implementation ignores potential exceptions in TryFinally #16189

Open

Description

@En3Tho

Currently implementation of TryFinallyAsync is defined as:

member inline internal this.TryFinallyAsync
        (
            body: TaskCode<'TOverall, 'T>,
            compensation: unit -> ValueTask
        ) : TaskCode<'TOverall, 'T> =
        ResumableCode.TryFinallyAsync(
            body,
            ResumableCode<_, _>(fun sm ->
                if __useResumableCode then
                    let mutable __stack_condition_fin = true
                    let __stack_vtask = compensation ()

                    if not __stack_vtask.IsCompleted then
                        let mutable awaiter = __stack_vtask.GetAwaiter()
                        let __stack_yield_fin = ResumableCode.Yield().Invoke(&sm)
                        __stack_condition_fin <- __stack_yield_fin

                        if not __stack_condition_fin then
                            sm.Data.MethodBuilder.AwaitUnsafeOnCompleted(&awaiter, &sm)

                    __stack_condition_fin
                else
                    let vtask = compensation ()
                    let mutable awaiter = vtask.GetAwaiter()

                    let cont =
                        TaskResumptionFunc<'TOverall>(fun sm ->
                            awaiter.GetResult() |> ignore
                            true)

                    // shortcut to continue immediately
                    if awaiter.IsCompleted then
                        true
                    else
                        sm.ResumptionDynamicInfo.ResumptionData <- (awaiter :> ICriticalNotifyCompletion)
                        sm.ResumptionDynamicInfo.ResumptionFunc <- cont
                        false)
        )

Note that it never calls awaiter.GetResult() meaning that if ValueTask was compelted synchronously it will throw but if not then it will just ignore result of the async computation.

Proposed fix is (matches .Bind implementation for example):

member inline internal this.TryFinallyAsync
        (
            body: TaskCode<'TOverall, 'T>,
            compensation: unit -> ValueTask
        ) : TaskCode<'TOverall, 'T> =
        ResumableCode.TryFinallyAsync(
            body,
            ResumableCode<_, _>(fun sm ->
                if __useResumableCode then
                    let mutable __stack_condition_fin = true
                    let __stack_vtask = compensation ()
                    let mutable awaiter = __stack_vtask.GetAwaiter()
                    
                    if not awaiter.IsCompleted then                        
                        let __stack_yield_fin = ResumableCode.Yield().Invoke(&sm)
                        __stack_condition_fin <- __stack_yield_fin

                    if __stack_condition_fin then
                        awaiter.GetResult()
                    else
                        sm.Data.MethodBuilder.AwaitUnsafeOnCompleted(&awaiter, &sm)

                    __stack_condition_fin
                else
                    let vtask = compensation ()
                    let mutable awaiter = vtask.GetAwaiter()

                    let cont =
                        TaskResumptionFunc<'TOverall>(fun sm ->
                            awaiter.GetResult() |> ignore
                            true)

                    // shortcut to continue immediately
                    if awaiter.IsCompleted then
                        cont.Invoke(&sm)
                    else
                        sm.ResumptionDynamicInfo.ResumptionData <- (awaiter :> ICriticalNotifyCompletion)
                        sm.ResumptionDynamicInfo.ResumptionFunc <- cont
                        false)
        )

Test code is:

[<Fact>]
let``task should propagate exception if thrown in DisposeAsync``() = task {
    let disposable = { new IAsyncDisposable with
        member _.DisposeAsync() = ValueTask(task {
            do! Task.Delay(1)
            failwith "boom"
        })
    }

    let! _ = Assert.ThrowsAsync<Exception>(fun () -> task {
        use _ = disposable
        ()
    })
    ()
}

Current behavior:

Assert.Throws() Failure
Expected: typeof(System.Exception)
Actual:   (No exception was thrown)

Activity

  1. added this to the Backlog milestone on Oct 26, 2023
  2. added
    Impact-Medium
    Area-Compiler-StateMachines
    Breaking-change
    and removed on Oct 30, 2023
  3. abelbraaksma commented on Nov 8, 2023

    @abelbraaksma
    Contributor

    yeah, I think this is a bug. @abonie is right to mark this as a breaking change, unfortunately, because currently, finally will not throw in the scenario you give, meaning that there will be code in the wild that may rely on this behavior.

    Granted: it should throw, for sure, if your code executes. However, be aware that it is considered bad practice to throw from a Dispose method, esp since in many coding patterns, Dispose can be called from the finalizer. And if a finalizer throws, it causes the whole process to fail fast. More info on dispose patterns in the topic of the Dispose method.

  4. TheAngryByrd commented on Nov 17, 2026

    @TheAngryByrd
    Contributor

    This also happens when the ValueTask from DisposeAsync has already completed with a fault. The issue text says that the synchronous case throws. That is true only if DisposeAsync itself throws. A ValueTask that is already faulted is lost too:

    • The static path checks IsCompleted and never calls GetResult.
    • The dynamic path returns true from the "already completed" shortcut, so cont (which calls GetResult) does not run.

    Probe (FSharp.Core 10.1.201 and 11.0.101, Debug and Release). It prints observed=success getResult=0:

    open System
    open System.Threading.Tasks
    open System.Threading.Tasks.Sources
    
    type FaultingDisposal() =
        let mutable getResultCalls = 0
        let source =
            { new IValueTaskSource with
                member _.GetStatus _ = ValueTaskSourceStatus.Faulted
                member _.GetResult _ =
                    getResultCalls <- getResultCalls + 1
                    raise (InvalidOperationException "dispose")
                member _.OnCompleted(continuation, state, _, _) = continuation.Invoke state }
        member _.GetResultCalls = getResultCalls
        interface IAsyncDisposable with
            member _.DisposeAsync() = ValueTask(source, 0s)
    
    let body (resource: FaultingDisposal) : Task =
        task {
            use _ = resource
            return ()
        }
    
    let resource = FaultingDisposal()
    let observed =
        try
            (body resource).GetAwaiter().GetResult()
            "success"
        with e -> e.GetType().Name
    printfn "observed=%s getResult=%d" observed resource.GetResultCalls

    The fix proposed above handles both cases. The same fix is in IcedTasks (TheAngryByrd/IcedTasks@c72b1347a) and in a PR for FsToolkit.ErrorHandling (demystifyfp/FsToolkit.ErrorHandling#385). That PR has tests for use and for for over IAsyncEnumerable (which disposes the enumerator through the same member). The cases are: DisposeAsync succeeds, faults, or cancels; already completed or pending; the body completes, throws, or returns early.

    With the fix, the results are the same as C# await using in all 18 cases. A fault or cancellation from DisposeAsync replaces the body result, as an exception from finally does. GetResult runs exactly once.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-Compiler-StateMachinesBreaking-changeBugImpact-Medium

    Type

    Projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions