StellaOps.Workflow.Analyzer

The workflow analyzer checks your workflow classes while you build. It reports most C# code that cannot be compiled to a canonical workflow definition as a build error at the line that causes it, so you find the problem before the workflow runs. A C# delegate (a Run step, or a signal name, payload, delay or condition given as context => ...) is checked like any other code: a body that breaks a rule fails the build, and a clean body builds with the warning WF021. Either way a delegate has no canonical form, so the publisher and a host on Stella.Engine reject it when they start. This page lists each rule with its fix, most of them with an example, and shows how to trust an assembly of your own.

What the analyzer is for

IDeclarativeWorkflow<T> implementations build a WorkflowSpec<T> from a fluent builder. At runtime, WorkflowCanonicalDefinitionCompiler turns that spec into a canonical JSON document that the engine can execute, store, compare and render.

For that to work, the spec must be pure and declarative: its shape can only depend on compile-time literals and the workflow builder surface, not on build-time state (time, environment, DB reads) or runtime C# semantics (imperative branching, exceptions, async).

The analyzer enforces this at compile time. A project that restores the StellaOps.Workflow.Abstractions package gets it automatically: that package depends on the StellaOps.Workflow.Analyzer package, which carries the analyzer under analyzers/dotnet/cs. Once referenced, every IDeclarativeWorkflow<T> class in the consumer compilation is checked on every build.

Activation

The analyzer activates only when the compilation references StellaOps.Workflow.Abstractions— specifically, when it can resolve both IDeclarativeWorkflow<T> and WorkflowSpec<T>. Absent those, it is a no-op. Authoring workflows against the StellaOps abstractions needs no opt-in attribute; the attribute described under Trusted assemblies is only for an assembly that supplies its own workflow construction surface.

Scope

The analyzer inspects the Spec property of every IDeclarativeWorkflow<T>-implementing class in the compilation. From each Spec initializer it walks transitively into every method call whose target is available as source:

Rules

All diagnostics except WF021 are Error severity and fail dotnet build. WF021 is a Warning.

WF001

Imperative control flow

Bad

public WorkflowSpec<OrderRequest> Spec { get; } = WorkflowSpec.For<OrderRequest>()
    .StartWith(flow =>
    {
        if (DateTime.UtcNow.Hour > 12)
        {
            flow.Set("lane", WorkflowExpr.String("afternoon"));
        }

        flow.Complete();
    })
    .Build();

Why it fails — The if runs once, when the class is built. The definition then holds whichever branch the clock chose at that moment; the condition never reaches the workflow.

Fix — Express the branch in the definition, so it is decided for each instance:

// The decision is part of the definition: it is taken for each instance, at run time.
public WorkflowSpec<OrderRequest> Spec { get; } = WorkflowSpec.For<OrderRequest>()
    .StartWith(flow => flow
        .WhenExpression(
            "Afternoon?",
            WorkflowExpr.Gt(WorkflowExpr.Path("start.hour"), WorkflowExpr.Number(12)),
            afternoon => afternoon.Set("lane", WorkflowExpr.String("afternoon")).Complete(),
            morning => morning.Set("lane", WorkflowExpr.String("morning")).Complete()))
    .Build();

Forbidden constructs: if, for, foreach, while, do, switch (statement form), try / catch / finally, throw, lock, using, goto, break, continue, yield.

WF002

Async/await

Bad

public WorkflowSpec<OrderRequest> Spec { get; } = WorkflowSpec.For<OrderRequest>()
    .StartWith(async flow =>
    {
        await Task.Delay(TimeSpan.FromSeconds(1));
        flow.Complete();
    })
    .Build();

Why it fails — The workflow Spec is constructed once, synchronously. await / async / Task.Run / Thread introduce runtime concurrency primitives that cannot be represented in the canonical definition.

Fix — Remove the async machinery. If the work you were doing was async only because it read from a database or an API, read it in a step of the workflow, for each instance:

// What the async code read when the class was built is read by a step, for each instance.
public WorkflowSpec<OrderRequest> Spec { get; } = WorkflowSpec.For<OrderRequest>()
    .StartWith(flow => flow
        .Call<object>(
            "Read customer",
            new EndpointAddress("crm", "/customers/read"),
            WorkflowExpr.Obj(WorkflowExpr.Prop("customer", WorkflowExpr.Path("start.customer"))),
            resultKey: "customer")
        .Complete())
    .Build();

WF003

Call into non-trusted assembly

Bad

public WorkflowSpec<OrderRequest> Spec { get; } = WorkflowSpec.For<OrderRequest>()
    .InitializeState(WorkflowExpr.Obj(
        WorkflowExpr.Prop("reference", WorkflowExpr.String(string.Join("-", "ORD", "2026")))))
    .StartWith(flow => flow.Complete())
    .Build();

Why it fails — string.Join is a method of System.Runtime, a compiled assembly the analyzer cannot walk. Its result would be computed once, when the class is built, and fixed in the definition.

Fix — Compute the value with an expression when the instance runs. For runtime data, bind through a path reference (WorkflowExpr.Path("start.orderId")); for literals, use the typed builders (WorkflowExpr.String("fixed-value")); for helper routines, put them in a project-referenced class so the analyzer can walk them.

// The core function `concat` builds the value when the instance starts.
public WorkflowSpec<OrderRequest> Spec { get; } = WorkflowSpec.For<OrderRequest>()
    .InitializeState(WorkflowExpr.Obj(
        WorkflowExpr.Prop("reference", WorkflowExpr.Func(
            "concat",
            WorkflowExpr.String("ORD-"),
            WorkflowExpr.Path("start.orderId")))))
    .StartWith(flow => flow.Complete())
    .Build();

Lambda invocations via func() (where func is an Action/Func<T>/custom delegate) are not flagged as WF003 — the lambda body is walked inline. nameof(...) expressions are also skipped.

WF004

new on non-trusted type

Bad

public WorkflowSpec<OrderRequest> Spec { get; } = WorkflowSpec.For<OrderRequest>()
    .InitializeState(WorkflowExpr.Obj(
        WorkflowExpr.Prop("requestId", WorkflowExpr.String(new Guid().ToString()))))
    .StartWith(flow => flow.Complete())
    .Build();

Why it fails — new Guid() instantiates a BCL type at workflow-build time, and its value is fixed in the definition instead of being taken for each instance.

Fix — Use a workflow expression. Workflow types (EndpointAddress, WorkflowBusinessReferenceDeclaration, WorkflowNamedExpressionDefinition, etc.) that live in a trusted assembly are trusted and may be instantiated freely.

// The identifier comes with the start request; workflow types such as EndpointAddress may be created.
public WorkflowSpec<OrderRequest> Spec { get; } = WorkflowSpec.For<OrderRequest>()
    .InitializeState(WorkflowExpr.Obj(
        WorkflowExpr.Prop("requestId", WorkflowExpr.Path("start.orderId"))))
    .StartWith(flow => flow.Call("Notify", new EndpointAddress("crm", "/notifications"), WorkflowExpr.Obj()).Complete())
    .Build();

WF005

C# conditional operator in workflow code

Bad

private const bool UseFastLane = true;

public WorkflowSpec<OrderRequest> Spec { get; } = WorkflowSpec.For<OrderRequest>()
    .InitializeState(WorkflowExpr.Obj(
        WorkflowExpr.Prop("route", WorkflowExpr.String(UseFastLane ? "fast" : "slow"))))
    .StartWith(flow => flow.Complete())
    .Build();

The null-coalescing ?? and the null-conditional ?. are reported the same way.

Why it fails — ?:, ??, and ?. resolve at workflow-build time. Whichever branch wins when the Spec is constructed is what ends up in the canonical JSON; the runtime condition never enters the workflow at all.

Fix — Use the canonical equivalents, the functions if and coalesce:

// `if` and `coalesce` decide for each instance, from its data.
public WorkflowSpec<OrderRequest> Spec { get; } = WorkflowSpec.For<OrderRequest>()
    .InitializeState(WorkflowExpr.Obj(
        WorkflowExpr.Prop("route", WorkflowExpr.Func(
            "if",
            WorkflowExpr.Path("start.fastLane"),
            WorkflowExpr.String("fast"),
            WorkflowExpr.String("slow"))),
        WorkflowExpr.Prop("customer", WorkflowExpr.Func(
            "coalesce",
            WorkflowExpr.Path("start.customer"),
            WorkflowExpr.String("anonymous")))))
    .StartWith(flow => flow.Complete())
    .Build();

WF006

Non-trusted field/property read

Bad

public WorkflowSpec<OrderRequest> Spec { get; } = WorkflowSpec.For<OrderRequest>()
    .InitializeState(WorkflowExpr.Obj(
        WorkflowExpr.Prop("year", WorkflowExpr.Number(DateTime.UtcNow.Year))))
    .StartWith(flow => flow.Complete())
    .Build();

Why it fails — Reading a non-const field or property on a type that isn’t in a trusted or source-walkable assembly bakes the read value into the canonical JSON. DateTime.UtcNow.Year gives you the year when the class was built, not a per-execution value.

What is allowed

Fix — Use WorkflowExpr.Path(...) to bind a runtime value, or a const on your own class for compile-time constants:

// A constant of your own is allowed; a value of the instance comes from a path.
private const int FirstFiscalYear = 2020;

public WorkflowSpec<OrderRequest> Spec { get; } = WorkflowSpec.For<OrderRequest>()
    .InitializeState(WorkflowExpr.Obj(
        WorkflowExpr.Prop("year", WorkflowExpr.Path("start.year")),
        WorkflowExpr.Prop("firstFiscalYear", WorkflowExpr.Number(FirstFiscalYear))))
    .StartWith(flow => flow.Complete())
    .Build();

WF010

Reachable helper violation

Emitted when a helper method reachable from a workflow’s Spec (in the same project or in a project reference) itself contains a WF001–WF006 violation. The primary location points at the call site inside the workflow; the additional location points at the offending line inside the helper.

The rule applies to a helper in the same project as the workflow and to one in a project reference alike: the diagnostic sits at the call, so one fix in the helper clears every call site.

Fix — Fix the helper. One fix clears the diagnostic at every call site.

WF020

Declarative workflow class cannot be read as a workflow

The package also carries a source generator, WorkflowCanonicalArtifactGenerator. For every IDeclarativeWorkflow<T> of the compilation that it can evaluate at build time, it writes the canonical definition into the assembly; the publisher reads the bundle from there. Its output follows the format of the runtime WorkflowCanonicalDefinitionCompiler but is not byte-identical to it for every construct; the publisher publishes each definition as the component that produced it wrote it.

WF020 (Error) is reported for a class that implements IDeclarativeWorkflow<T> but has no Spec property: neither the generator nor the runtime compiler can build its definition. The message reads “The canonical artifact generator cannot read this class as a workflow: …”.

Fix — Give the class a Spec property built with WorkflowSpec.For<T>().

WF021

Workflow not bundled by the canonical artifact generator

WF021 (Warning) is reported where the generator cannot evaluate a construct at compile time. The workflow still builds and runs: it is left out of the bundle and listed for runtime compilation, and the publisher compiles it with the runtime compiler when it starts. A host that registers the workflow in code is not affected: on Stella.Engine it compiles every registered workflow with the runtime compiler when it starts. The message reads “The canonical artifact generator cannot evaluate this at compile time, so the workflow is not bundled and the publisher compiles it when it starts: …”, followed by the construct. Constructs that report WF021:

A construct whose value is a C# delegate has no canonical definition at all, whichever compiler runs: Run, WaitForSignal with a signal-name delegate, QueryGraphql with a variables delegate, and the delegate forms of Set, Repeat, timers and child workflows. The runtime compiler rejects them with WFCD codes: the publisher reports such a workflow as not publishable, and a host on Stella.Engine that registers it stops at start with them. Use the WorkflowExpr form of the construct; for GraphQL variables, the QueryGraphql overloads that take a variables expression.

Fix — Nothing is required for a workflow you register in code, unless it uses a delegate. To keep a workflow in the build-time bundle, use the forms the generator evaluates: literals in place, and the add function for arithmetic (WorkflowExpr.Func("add", ...)). A build that treats warnings as errors fails on WF021; exempt it with <WarningsNotAsErrors>WF021</WarningsNotAsErrors> or change the construct.

Trusted assemblies

A trusted assembly is one whose types the analyzer treats as canonicalizable leaves: it allows calls into them, instantiation of them, and member reads on them without walking their bodies. It also grants the compile-time construction factory exemption — a helper whose return type comes from a trusted assembly is exempt from WF010, because such a helper runs once while the Spec is built and its imperative C# is metaprogramming, not runtime workflow logic.

Trust is deliberately narrow. Granting it to an assembly that does runtime work silently disables the diagnostics that keep workflow definitions canonical.

What is trusted by default

Only this product’s own workflow assemblies: StellaOps.Workflow and its dotted children (StellaOps.Workflow.Abstractions, StellaOps.Workflow.Contracts, …). Nothing else is trusted out of the box, and this default cannot be turned off.

Opting an assembly in — the attribute

An assembly that supplies its own workflow builder, expression, spec, or task-definition types opts in by applying the assembly-level attribute from StellaOps.Workflow.Abstractions:

// AssemblyInfo.cs, or any file in the assembly
[assembly: StellaOps.Workflow.Abstractions.WorkflowTrustedAssembly]

This is the preferred mechanism. It requires no build configuration, it travels with the assembly to every consumer, and it is the only mechanism the canonical artifact generator honours (see the caveat below).

Apply it only to an assembly whose public surface is compile-time workflow construction.

Opting an assembly in — configuration

For a binary you consume but do not build, and therefore cannot annotate, name it in an analyzer configuration option. Put this in a .globalconfig, or under [*.cs] in .editorconfig:

stellaops_workflow_trusted_assembly_prefixes = Example.Workflow, Example.Flow.Extensions

Design choices

When the analyzer will NOT catch something

Quick reference

IDShort nameSeverity
WF001Imperative control flowError
WF002Async/awaitError
WF003Call into non-trusted assemblyError
WF004new on non-trusted typeError
WF005C# ?: / ?? / ?.Error
WF006Non-trusted field/property readError
WF010Reachable helper violation (cross-project)Error
WF020Declarative workflow class cannot be read as a workflowError
WF021Workflow not bundled by the canonical artifact generatorWarning

The StellaOps.Workflow.Analyzerpage of the .NET API reference lists the same diagnostics with their messages.