From 11fd9ab44c41aa2c9243c22a5e56aca7606d7366 Mon Sep 17 00:00:00 2001 From: Michael Glass Date: Sat, 26 Sep 2026 16:50:24 +0200 Subject: [PATCH 1/2] AsyncLazy: only complete the run that produced the result When all requests for a running computation were canceled, the run was abandoned and a later request started a new one. The completion handler of the abandoned run could still execute afterwards, and it completed whatever run was in progress at that moment. The cache then held the result of the canceled run while the new run was still going, and returned it to later requests. The completion handler now only updates the state if it is still the run that produced the result. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../.FSharp.Compiler.Service/11.0.200.md | 1 + src/Compiler/Facilities/AsyncMemoize.fs | 7 +- .../CompilerService/AsyncMemoize.fs | 70 +++++++++++++++++++ 3 files changed, 75 insertions(+), 3 deletions(-) diff --git a/docs/release-notes/.FSharp.Compiler.Service/11.0.200.md b/docs/release-notes/.FSharp.Compiler.Service/11.0.200.md index b88496f259e..baf2b3848aa 100644 --- a/docs/release-notes/.FSharp.Compiler.Service/11.0.200.md +++ b/docs/release-notes/.FSharp.Compiler.Service/11.0.200.md @@ -32,6 +32,7 @@ * Preserve SRTP extension scopes across source files and competing witnesses through imported inline calls. Compile generic extension forwarding, including quotations, in unoptimized builds. Preserve applicable built-in operator priority in imported inline quotations. Do not reuse SRTP specializations across different selected witnesses. ([Issue #20683](https://github.com/dotnet/fsharp/issues/20683), [Issue #20684](https://github.com/dotnet/fsharp/issues/20684), [Issue #20685](https://github.com/dotnet/fsharp/issues/20685), [PR #20717](https://github.com/dotnet/fsharp/pull/20717)) * Transparent compiler: with `enablePartialTypeChecking`, a project that is only referenced by another project is type checked from its signatures. Implementation files that have a signature file are no longer parsed or type checked to produce the referenced assembly. `ParseAndCheckProject` still checks all files. ([PR #20703](https://github.com/dotnet/fsharp/pull/20703)) * With `enablePartialTypeChecking`, a project that is only referenced by another project no longer type checks its implementation files that have a signature file. Producing the referenced assembly only needs the signatures, but finalizing the project also collected the diagnostics of the skipped files, which type checked all of them and kept their results in memory. `ParseAndCheckProject` still reports the diagnostics of these files. ([PR #20699](https://github.com/dotnet/fsharp/pull/20699)) +* Transparent compiler: a cached computation that was canceled and restarted no longer takes the result of the canceled run while the new run is still going. ([PR #XXXXX](https://github.com/dotnet/fsharp/pull/XXXXX)) ### Changed diff --git a/src/Compiler/Facilities/AsyncMemoize.fs b/src/Compiler/Facilities/AsyncMemoize.fs index cc652c24f90..3d353869889 100644 --- a/src/Compiler/Facilities/AsyncMemoize.fs +++ b/src/Compiler/Facilities/AsyncMemoize.fs @@ -60,10 +60,11 @@ type AsyncLazy<'t> private (initial: AsyncLazyState<'t>, cancelUnawaited: bool, return! work |> Async.AwaitTask } - let onComplete (t: Task<'t>) = + // Only complete the run that produced this result. The run may have been canceled and replaced by a new one. + let onComplete (runCts: CancellationTokenSource) (t: Task<'t>) = updateState <| function - | Running(computation, _, _, _) -> + | Running(computation, _, cts, _) when obj.ReferenceEquals(cts, runCts) -> try Completed t.Result with exn -> @@ -80,7 +81,7 @@ type AsyncLazy<'t> private (initial: AsyncLazyState<'t>, cancelUnawaited: bool, let work = Async .StartAsTask(computation, cancellationToken = cts.Token) - .ContinueWith(onComplete, TaskContinuationOptions.NotOnCanceled) + .ContinueWith(onComplete cts, TaskContinuationOptions.NotOnCanceled) Running(computation, work, cts, 1), detachable work | Running(c, work, cts, count) -> Running(c, work, cts, count + 1), detachable work diff --git a/tests/FSharp.Compiler.ComponentTests/CompilerService/AsyncMemoize.fs b/tests/FSharp.Compiler.ComponentTests/CompilerService/AsyncMemoize.fs index 497098aa5c9..00fe792e566 100644 --- a/tests/FSharp.Compiler.ComponentTests/CompilerService/AsyncMemoize.fs +++ b/tests/FSharp.Compiler.ComponentTests/CompilerService/AsyncMemoize.fs @@ -241,6 +241,76 @@ let ``Job is actually cancelled and restarted`` () : Task = Assert.Equal(1, finishedCount) } +/// Queues tasks until RunPending is called. +type ManualTaskScheduler() = + inherit TaskScheduler() + + let queue = System.Collections.Concurrent.ConcurrentQueue() + + member _.QueuedCount = queue.Count + + member _.RunPending() = + let mutable task = null + while queue.TryDequeue &task do + base.TryExecuteTask task |> ignore + + override _.QueueTask task = queue.Enqueue task + override _.TryExecuteTaskInline(task, _) = base.TryExecuteTask task + override _.GetScheduledTasks() = queue.ToArray() + +[] +let ``Completion of a canceled run does not complete the run that replaced it`` () : Task = + task { + let mutable runs = 0 + let runCanComplete = [| TaskCompletionSource(); TaskCompletionSource() |] + + let computation = async { + let run = Interlocked.Increment &runs + do! Async.AwaitTask runCanComplete[run - 1].Task + return run + } + + let memoize = AsyncMemoize<_, int, _>() + let events = observe memoize + let key = 1 + + // Request the job from a task on our own scheduler. The handler that records the result of the + // first run is queued on it, so it only runs when we let it. + let scheduler = ManualTaskScheduler() + use cts1 = new CancellationTokenSource() + + let startRequest1 = + Task.Factory.StartNew( + (fun () -> Async.StartImmediateAsTask(memoize.Get(wrapKey key, computation), cts1.Token)), + CancellationToken.None, + TaskCreationOptions.None, + scheduler) + + scheduler.RunPending() + let request1 = startRequest1.Result + do! waitUntil events (received Started) + + // The first run finishes, but the handler that records its result stays queued. + runCanComplete[0].SetResult() + Assert.True(SpinWait.SpinUntil((fun () -> scheduler.QueuedCount = 1), TimeSpan.FromSeconds 10.)) + + // The only request is canceled, so the first run is abandoned. + cts1.Cancel() + do! assertTaskCanceled request1 + + // A new request starts a second run. + let request2 = Async.StartAsTask(memoize.Get(wrapKey key, computation)) + do! waitUntil events (countOf Started >> (=) 2) + + // Now the handler of the abandoned first run gets to run. The second run is still going. + scheduler.RunPending() + Assert.Equal(None, memoize.TryGet(key, fun _ -> true)) + + runCanComplete[1].SetResult() + let! result2 = request2 + Assert.Equal(2, result2) + } + [] let ``Job keeps running if only one requestor cancels`` () : Task = task { From 6dcc8d0de710620d87f1fa183b1528e444258963 Mon Sep 17 00:00:00 2001 From: Michael Glass Date: Sat, 26 Sep 2026 17:48:50 +0200 Subject: [PATCH 2/2] Release notes: link PR #20644 Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/release-notes/.FSharp.Compiler.Service/11.0.200.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/release-notes/.FSharp.Compiler.Service/11.0.200.md b/docs/release-notes/.FSharp.Compiler.Service/11.0.200.md index baf2b3848aa..5165720f8dd 100644 --- a/docs/release-notes/.FSharp.Compiler.Service/11.0.200.md +++ b/docs/release-notes/.FSharp.Compiler.Service/11.0.200.md @@ -28,11 +28,11 @@ * `GetProjectSnapshotFromScript` uses the document source of the checker when none is passed, also for the TransparentCompiler's `GetProjectOptionsFromScript`. A file from a `DocumentSource.Custom` keeps its snapshot version until its text changes, and a file for which the source returns `None` is read from disk. `FSharpFileSnapshot.CreateFromDocumentSource` now returns `Async`. `SourceTextNew.ofISourceText` returns an `ISourceTextNew` unchanged, and otherwise computes the checksum from the text instead of from `ToString()`. ([Issue #20750](https://github.com/dotnet/fsharp/issues/20750), [PR #20751](https://github.com/dotnet/fsharp/pull/20751)) * Build parser diagnostic messages without runtime printf specialization or reflective function construction, so Native AOT hosts report indentation and invalid-character diagnostics instead of failing during formatting. Preserve `#r` reference tooltips while script project options remain alive, including after garbage collection or cache eviction. ([PR #20658](https://github.com/dotnet/fsharp/pull/20658)) * Preserve tupled lambda argument groups when reducing state-machine applications, avoiding invalid argument substitutions and runtime failures with inline formatters. ([Issue #20675](https://github.com/dotnet/fsharp/issues/20675), [PR #20700](https://github.com/dotnet/fsharp/pull/20700)) +* Transparent compiler: a cached computation that was canceled and restarted no longer takes the result of the canceled run while the new run is still going. ([PR #20644](https://github.com/dotnet/fsharp/pull/20644)) * Transparent compiler: `ParseFile` no longer imports the references of the project, which also type checked the projects it references. Parsing only needs the compiler options of the project. ([PR #20704](https://github.com/dotnet/fsharp/pull/20704)) * Preserve SRTP extension scopes across source files and competing witnesses through imported inline calls. Compile generic extension forwarding, including quotations, in unoptimized builds. Preserve applicable built-in operator priority in imported inline quotations. Do not reuse SRTP specializations across different selected witnesses. ([Issue #20683](https://github.com/dotnet/fsharp/issues/20683), [Issue #20684](https://github.com/dotnet/fsharp/issues/20684), [Issue #20685](https://github.com/dotnet/fsharp/issues/20685), [PR #20717](https://github.com/dotnet/fsharp/pull/20717)) * Transparent compiler: with `enablePartialTypeChecking`, a project that is only referenced by another project is type checked from its signatures. Implementation files that have a signature file are no longer parsed or type checked to produce the referenced assembly. `ParseAndCheckProject` still checks all files. ([PR #20703](https://github.com/dotnet/fsharp/pull/20703)) * With `enablePartialTypeChecking`, a project that is only referenced by another project no longer type checks its implementation files that have a signature file. Producing the referenced assembly only needs the signatures, but finalizing the project also collected the diagnostics of the skipped files, which type checked all of them and kept their results in memory. `ParseAndCheckProject` still reports the diagnostics of these files. ([PR #20699](https://github.com/dotnet/fsharp/pull/20699)) -* Transparent compiler: a cached computation that was canceled and restarted no longer takes the result of the canceled run while the new run is still going. ([PR #XXXXX](https://github.com/dotnet/fsharp/pull/XXXXX)) ### Changed