dotnet / dotnet/fsharp

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

Open
#18,848 1 comment 0 reactions 0 assignees View on GitHub
Area-Compiler-StateMachines Bug
Dominant language
F#
Stars
4.3k
Forks
876
Avg merge
4d 11h
Merged PRs (30d)
131

Description

Link: https://github.com/fsprojects/FSharp.Control.TaskSeq/issues/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

```fsharp
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

[]
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.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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.