Skip to content

Null reference exception when nesting loops in Release mode (TaskSeq) #18848

@mrakgr

Description

@mrakgr

Link: fsprojects/FSharp.Control.TaskSeq#269

Posted that issue in TaskSeq, but since the project is inactive, I decided to repost it here for visibility.

Repro steps

Repo: https://github.com/mrakgr/taskseq_bug_report

module ICF_Main.Main

open System
open System.Threading.Channels
open FSharp.Control

module Db =
    let service () = 
        let ch_in = Channel.CreateUnbounded()
        let loop_add_db = task {
            for events in ch_in.Reader.ReadAllAsync() do 
                for stream_name, events_grouped_by_stream_name in Array.zip events events do
                    printfn "%A" events_grouped_by_stream_name
                    ()
        }
        loop_add_db

[<EntryPoint>]
let main args =
    let t = Db.service()
    t.Wait()
    0

Expected behavior

That the program should wait forever.

Actual behavior

When I run this in Release with dotnet run -c Release taskseq_bug_report.fsproj here is what happens:

mrakgr@Marko:~/taskseq_bug_report$ dotnet run -c Release taskseq_bug_report.fsproj 
/home/mrakgr/taskseq_bug_report/Program.fs(10,27): warning FS3511: This state machine is not statically compilable. A resumable code invocation at '(12,16--12,19)' could not be reduced. An alternative dynamic implementation will be used, which may be slower. Consider adjusting your code to ensure this state machine is statically compilable, or else suppress this warning.
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AwaitUnsafeOnCompleted[TAwaiter](TAwaiter& awaiter, IAsyncStateMachineBox box)
--- End of stack trace from previous location ---
   at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__128_1(Object state)
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()

Note that it has to be run in Release mode for the error to trigger and won't in Debug mode.

Known workarounds

Putting a do! task {} around the inner loop.

Related information

Provide any related information (optional):

  • Operating system: Win 11
  • .NET Runtime kind (.NET Core, .NET Framework, Mono): 9.0.104 SDK
  • Editing Tools (e.g. Visual Studio Version, Visual Studio): VS Code

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    Status

    New

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions