#8467·elsa-core

An activity interrupted after its "Executing" commit is not re-run on restart when other work is scheduled

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: any; the repro uses the default flowchart mode. Needs the Executing activity commit strategy. Host: first seen in an ASP.NET Core app with the EF Core persistence providers and a real process kill. The repro below reproduces it with a plain IWorkflowRunner and a capturing ICommitStateHandler in place of the database.

Summary

The Executing activity commit strategy persists the workflow state just before an activity runs, so that the activity can be re-run if the process dies during its execution. That works when the activity is the only scheduled work.

It does not work when other work items were still in the scheduler at that commit, e.g. a parallel flowchart branch. On restart, WorkflowRunner sees a non-empty scheduler, runs only those work items, and does not re-schedule the interrupted activity. After that restart, its context is still IsExecuting = true, and the instance suspends on the other branch's bookmark. The branch the activity belonged to is orphaned without an incident. Whether a later restart would pick it up (e.g. once the other branch has finished) was not exercised.

Minimal repro

The process kill is simulated: an ICommitStateHandler keeps the state of the first commit, which is exactly what DefaultCommitStateHandler would have saved. That state is restored and run without a bookmark or activity handle. That is what the runtime's restart of an interrupted instance does: DefaultWorkflowRestarter dispatches a DispatchWorkflowInstanceRequest(instanceId), which reaches LocalWorkflowClient.RunInstanceAsync and then IWorkflowRunner.RunAsync(graph, state, options) with neither set.

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
// An activity with the "Executing" commit strategy, interrupted after that commit, is not re-run on restore
// when other work was still scheduled at the commit.
//   Flowchart: Start -> Invoice ("Executing" commit strategy)
//              Start -> Docs (bookmark)                         (omitted in the "alone" control)
// The process kill is simulated: a commit-state handler keeps the state of the first commit (Invoice's
// "Executing" commit), which is what a persistent store would hold if the process died right after it.
// Everything the original run did after that commit is discarded. The saved state is then restored and run
// without a bookmark, which is what the runtime's restart of an interrupted instance does.
// Expected in both cases: the restored run executes Invoice again.
using Elsa.Common;
using Elsa.Extensions;
using Elsa.Workflows;
using Elsa.Workflows.Activities;
using Elsa.Workflows.Activities.Flowchart.Activities;
using Elsa.Workflows.Activities.Flowchart.Models;
using Elsa.Workflows.CommitStates;
using Elsa.Workflows.Models;
using Elsa.Workflows.State;
using Microsoft.Extensions.DependencyInjection;

var failures = 0;
foreach (var withSibling in new[] { false, true })
{
    var services = new ServiceCollection();
    services.AddElsa(elsa => elsa.UseWorkflows(w => w.UseCommitStrategies(s => s.AddStandardStrategies())));
    var store = new FirstCommitStore();
    services.AddSingleton<ICommitStateHandler>(sp => store.With(sp));
    var sp = services.BuildServiceProvider();
    foreach (var task in sp.GetServices<IStartupTask>()) await task.ExecuteAsync(default); // as the host does; fills the commit-strategy registry
    var runner = sp.GetRequiredService<IWorkflowRunner>();
    var serializer = sp.GetRequiredService<IWorkflowStateSerializer>();

    var start = new Start();
    var invoice = new Invoice().SetCommitStrategy("Executing");
    var docs = new Wait();
    var flowchart = new Flowchart { Start = start, Activities = { start, invoice }, Connections = { new Connection(start, invoice) } };
    if (withSibling) { flowchart.Activities.Add(docs); flowchart.Connections.Add(new Connection(start, docs)); }
    var workflow = new Workflow { Root = flowchart };

    await runner.RunAsync(workflow); // the original run; everything after the first commit is "lost"
    Invoice.Runs = 0;
    var restored = serializer.Deserialize(store.Json!);
    var state = (await runner.RunAsync(workflow, restored)).WorkflowState; // the restart: no bookmark, no activity handle
    var ok = Invoice.Runs == 1;
    if (!ok) failures++;
    var executing = state.ActivityExecutionContexts.Where(x => x.IsExecuting).Select(x => x.ScheduledActivityNodeId.Split(':').Last());
    Console.WriteLine($"{(ok ? "PASS" : "FAIL")}: {(withSibling ? "with a sibling scheduled" : "alone"),-24} scheduled at commit={store.ScheduledAtCommit} " +
                      $"invoice re-runs={Invoice.Runs} status={state.Status}/{state.SubStatus} bookmarks=[{string.Join(",", state.Bookmarks.Select(b => b.Name))}] " +
                      $"still executing=[{string.Join(",", executing)}]");
}
return failures == 0 ? 0 : 1;

class Invoice : CodeActivity
{
    public static int Runs;
    protected override void Execute(ActivityExecutionContext context) => Runs++;
}

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

/// <summary>Keeps the serialized state of the first commit only (the "database" at the moment of the kill).</summary>
class FirstCommitStore : ICommitStateHandler
{
    private IServiceProvider _sp = null!;
    public string? Json;
    public int ScheduledAtCommit;
    public FirstCommitStore With(IServiceProvider sp) { _sp = sp; return this; }

    public Task CommitAsync(WorkflowExecutionContext context, CancellationToken cancellationToken = default) =>
        CommitAsync(context, _sp.GetRequiredService<IWorkflowStateExtractor>().Extract(context), cancellationToken);

    public Task CommitAsync(WorkflowExecutionContext context, WorkflowState state, CancellationToken cancellationToken = default)
    {
        if (Json != null) return Task.CompletedTask;
        ScheduledAtCommit = context.Scheduler.List().Count();
        Json = _sp.GetRequiredService<IWorkflowStateSerializer>().Serialize(state);
        return Task.CompletedTask;
    }
}

(The startup tasks are run by hand because the commit-strategy registry is filled by PopulateCommitStrategyRegistry, an IStartupTask. Without them SetCommitStrategy("Executing") resolves to no strategy in a bare ServiceCollection.)

Expected vs actual

Expected in both cases: the restored run executes Invoice again (invoice re-runs=1).

Actual on 3.8.4:

$ dotnet run -c Release
PASS: alone                    scheduled at commit=0 invoice re-runs=1 status=Finished/Finished bookmarks=[] still executing=[]
FAIL: with a sibling scheduled scheduled at commit=1 invoice re-runs=0 status=Running/Suspended bookmarks=[Docs] still executing=[Invoice1]

Analysis (source references at tag 3.8.4)

A likely fix, unverified: when neither a bookmark nor an activity handle is given, re-schedule every IsExecuting context that has no pending work item, in addition to the restored work items, not only when the scheduler is empty.

In the application this was found in, the interrupted activity created an invoice while a parallel "documents" branch was queued. After the restart, the activity execution record stayed Pending and the instance sat in Running/Suspended with only the documents bookmark. The payment branch did not continue after that restart, and no incident was raised.

Relation to existing issues

  • No existing issue found for this symptom (searched: "interrupted activity", "IsExecuting", "resume interrupted", "commit strategy restart").
  • #6733 (restart of interrupted workflows after an upgrade) and #8052 / #8059 (the recovery scanner requeuing finished instances) touch the same recovery machinery, but not this branch of WorkflowRunner.
  • 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), WorkflowRunner.cs and DefaultActivityInvokerMiddleware.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

Do not use the Executing commit strategy on an activity that can start while sibling work is scheduled (parallel flowchart branches, Fork branches). Use it only where the activity is the sole scheduled work, e.g. after a join. Make the activity's side effect idempotent and drive recovery from outside the engine, e.g. by re-delivering the command that started the step.

Source: elsa-workflows/elsa-core