#8465·elsa-core

Counter-based flowchart: a join whose inbound branch contains a loop is skipped (WaitAll) or fires early (WaitAllActive), and the workflow still ends Finished

Author: MBrekhofCreated Sep 25, 2026Updated Sep 26, 2026
Labelsbugprio highelsa 3triaged

Elsa version: 3.8.4 (also reproduced on 3.9.0-preview.5709 and 3.10.0-preview.5706) Execution mode: counter-based flowchart (the default). Token-based handles this graph correctly. Host: plain IWorkflowRunner, in memory; the state is serialized and deserialized between runs.

Summary

Two parallel branches meet in a FlowJoin. One branch contains a rework loop (a decision whose "rejected" outcome loops back to it through a wait).

  • WaitAll: after one rejection, the join is skipped and so is everything after it. When the loop finally exits, nothing happens, and the workflow ends Finished/Finished without an incident. The failure is silent.
  • WaitAllActive: the join fires early, as soon as the other branch arrives, while the looping branch is still in its rework wait.

This is the classic "parallel review with rework" shape (#6725, #7724 describe it from the application side).

Minimal repro

Repro.csproj:

xml
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <!-- dotnet run -p:ElsaVersion=<version> to try another build -->
    <ElsaVersion Condition="'$(ElsaVersion)' == ''">3.8.4</ElsaVersion>
    <RestorePackagesWithLockFile>false</RestorePackagesWithLockFile>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Elsa" Version="$(ElsaVersion)" />
  </ItemGroup>
</Project>

Program.cs:

csharp
// A flowchart join whose inbound branch contains a loop.
//   Start -> Review (decision: False the first time, True the second)
//   Review False -> Rework (bookmark) -> Review  (loop back-edge)
//   Review True  -> Join
//   Start -> Other -> Join
//   Join = FlowJoin(mode) -> Active
// Steps: run (Review rejects, Other completes, Rework waits), then resume Rework.
// Expected in every configuration: Active runs exactly once, after Review returned True, and the workflow ends Finished.
using Elsa.Extensions;
using Elsa.Workflows;
using Elsa.Workflows.Activities;
using Elsa.Workflows.Activities.Flowchart.Activities;
using Elsa.Workflows.Activities.Flowchart.Extensions;
using Elsa.Workflows.Activities.Flowchart.Models;
using Elsa.Workflows.Models;
using Elsa.Workflows.Options;
using Microsoft.Extensions.DependencyInjection;

var failures = 0;
foreach (var (execution, joinMode) in new[]
         {
             (FlowchartExecutionMode.CounterBased, FlowJoinMode.WaitAll),
             (FlowchartExecutionMode.CounterBased, FlowJoinMode.WaitAllActive),
             (FlowchartExecutionMode.TokenBased, FlowJoinMode.WaitAll),
         })
{
    var log = new List<string>(); var reviews = 0;
    var services = new ServiceCollection();
    services.AddElsa(elsa => elsa.UseFlowchart(f => f.UseExecution(execution)));
    var sp = services.BuildServiceProvider();
    var runner = sp.GetRequiredService<IWorkflowRunner>();
    var serializer = sp.GetRequiredService<IWorkflowStateSerializer>();

    var start = new Start();
    var review = new FlowDecision(_ => { var ok = ++reviews > 1; log.Add(ok ? "approved" : "rejected"); return ok; });
    var rework = new Wait();
    var other = new Inline(() => log.Add("other"));
    var join = new FlowJoin { Mode = new(joinMode) };
    var active = new Inline(() => log.Add("ACTIVE"));
    var workflow = new Workflow
    {
        Root = new Flowchart
        {
            Start = start,
            Activities = { start, review, rework, other, join, active },
            Connections =
            {
                new Connection(start, review),
                new Connection(new Endpoint(review, "False"), new Endpoint(rework)),
                new Connection(rework, review),
                new Connection(new Endpoint(review, "True"), new Endpoint(join)),
                new Connection(start, other),
                new Connection(other, join),
                new Connection(join, active),
            }
        }
    };

    var state = (await runner.RunAsync(workflow)).WorkflowState;
    log.Add("|");
    var bookmark = state.Bookmarks.SingleOrDefault();
    if (bookmark != null) // resume Rework, with the state persisted and reloaded as the runtime does
        state = (await runner.RunAsync(workflow, serializer.Deserialize(serializer.Serialize(state)), new RunWorkflowOptions { BookmarkId = bookmark.Id })).WorkflowState;
    var ok = log.Count(x => x == "ACTIVE") == 1 && log.IndexOf("ACTIVE") > log.IndexOf("approved") && log.Contains("approved")
             && state.Status == WorkflowStatus.Finished && state.SubStatus == WorkflowSubStatus.Finished;
    if (!ok) failures++;
    Console.WriteLine($"{(ok ? "PASS" : "FAIL")}: {execution,-12} {joinMode,-13} trace=[{string.Join(" ", log)}] status={state.Status}/{state.SubStatus}");
}
return failures == 0 ? 0 : 1;

class Wait : Activity
{
    protected override void Execute(ActivityExecutionContext context) =>
        context.CreateBookmark(new CreateBookmarkArgs { BookmarkName = "Rework", Callback = OnResumeAsync });
    private ValueTask OnResumeAsync(ActivityExecutionContext context) => context.CompleteActivityAsync();
}

Expected vs actual

Expected in all three configurations: ACTIVE exactly once, after approved; the workflow ends Finished/Finished. (| in the trace separates the first run from the resume.)

Actual on 3.8.4:

$ dotnet run -c Release
FAIL: CounterBased WaitAll       trace=[rejected other | approved] status=Finished/Finished
FAIL: CounterBased WaitAllActive trace=[rejected other ACTIVE | approved] status=Finished/Finished
PASS: TokenBased   WaitAll       trace=[rejected other | approved ACTIVE] status=Finished/Finished

Analysis (source references at tag 3.8.4)

The counter scheduler records, for each connection, how often it was visited and whether its last visit was followed (FlowScope.cs).

  • When an activity completes, every outbound connection is registered as visited, followed or not (Flowchart.Counters.cs#L188-L191). Each loop iteration that does not exit therefore registers the loop's exit connection (Review -True-> Join) as "visited, not followed". To the join, that is indistinguishable from a branch that was decided not to take this path.
  • AllInboundConnectionsVisited becomes true as soon as Other -> Join has also been visited.
  • WaitAll (L269-L281): not all connections were followed, so the join is skipped through SkipOutboundActivityAsync. The skip also counts as a visit of the join (visit count 1). When the loop later exits and follows Review -> Join (count 2), the minimum over the inbound connections is still 1 (Other -> Join). That is not greater than the join's visit count, so the join is never "all visited" again. The flowchart then completes normally with no pending work.
  • WaitAllActive (L287-L299): "all visited, any followed" is already true when Other arrives, so the join is scheduled while the looping branch is still open.

The underlying issue: in the counter model, a connection leaving a loop is visited on every iteration, not once, so its state does not mean "this path is decided".

Relation to existing issues

  • #6725 "FlowJoin with WaitAll mode not waiting" (open since 2025-06): the same symptom (a loop in one branch, and the join does not wait), reported from an application workflow. This repro may serve as its minimal case.
  • #7724 (open) and #7013 (open) describe the same shape (a branch loops back, the join misbehaves) on 3.4 and later.
  • #6229 (open): a join inside a loop runs only once. Related counter logic, but a different shape.
  • As of 2026-09-25 (source fetched with gh api raw file reads at main = c4961ca601 and release/3.9.0 = c547266514, compared against tag 3.8.4 = 33181ae304), Flowchart.Counters.cs and FlowScope.cs are byte-identical on both branches. Verified by running: the repro fails the same way on 3.9.0-preview.5709 and 3.10.0-preview.5706 (feedz).

Workaround

  • Use token-based execution for such flowcharts. Its Merge mode waits correctly here (third line of the output). Beware of the companion token-mode issue (a FlowJoin(WaitAny) completes the flowchart early; link to be added once filed) if the flowchart also contains a WaitAny join.
  • Or express the looping branches as structured activities (Fork(WaitAll) { While(...) { ... }, ... }) inside a single flowchart node.

Source: elsa-workflows/elsa-core