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:
- Trusted leaves — any method/type in a trusted assembly. Not walked; always allowed.
- Same compilation / project references — source walked via
DeclaringSyntaxReferences. A violation in such a method is reported as WF010 at the call inside the workflow, with an additional location at the offending line of the method. - Metadata-only (compiled NuGet / framework) references — not walkable. Invocations, object creations, and non-const field/property reads on such assemblies are rejected. If you need a helper routine, put it in a project reference, not a binary dependency.
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
- Compile-time constants (
constfields) on any type.int.MaxValueand userpublic const string Route = "/x"are always fine. - Static readonly fields on types in the current compilation or a project reference — the analyzer can walk the initializer and verify it’s canonical. This is how
static readonly EndpointAddress QueryAddress = new("service-a", "/records/query");stays legal for the analyzer. The source generator bundles such a field when its initializer has literal arguments; an initializer that uses constants gives WF021. - Any member on a type from a trusted assembly.
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:
- the builder methods
QueryGraphql,WaitForSignal,Map,ExternalActivityandRun; WorkflowExpr.BinaryandWorkflowExpr.FromValue;- an address that is not built in place in the
Callwith literal arguments: a helper that returns an address, or a constant passed as the service name; - a helper parameter used as a value (for example a
stringparameter passed toWorkflowExpr.String), and aparamshelper that builds an object from a collection expression; - a workflow name, version, display name or role list that is not a literal.
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
- Values are assembly name prefixes, matched ordinally.
Example.Workflowtrusts the assemblyExample.Workflowand anyExample.Workflow.*; it does not trustOther.Example.Workflow. - Separate multiple entries with commas or semicolons.
- The option is additive. It cannot remove
StellaOps.Workflow*from the trust set, so a configuration file can never break workflow authoring. - Caveat: this option reaches the analyzer only. The canonical artifact source generator is not influenced by per-project configuration and honours the attribute alone. An assembly trusted only by configuration may still raise WF021 from the generator. Prefer the attribute wherever you can apply it.
Design choices
- One source of truth. The runtime
WorkflowCanonicalDefinitionCompilerdefines the canonical JSON. The source generator bundles only the workflows it can evaluate at build time and leaves every other workflow to the runtime compiler (WF021) instead of guessing. - No severity configuration. Every rule except WF021 is an
Error, so the C# constructs that rules WF001 to WF006, WF010 and WF020 cover fail the build. WF021 is aWarning: a workflow the generator cannot evaluate still compiles at runtime, except a delegate form such asRun, which the runtime compiler rejects when the publisher or aStella.Enginehost starts (WF021). - No per-rule escape hatch. There is no attribute or option that suppresses an individual diagnostic on a specific member.
[WorkflowTrustedAssembly]andstellaops_workflow_trusted_assembly_prefixes(see Trusted assemblies) work at whole-assembly granularity and exist to admit other workflow-construction surfaces, not to whitelist a vetted BCL helper.
When the analyzer will NOT catch something
Helpers that build workflow types. A method that returns a workflow type (for example
WorkflowSpec<T>,WorkflowExpressionDefinitionor a flow builder), or avoidmethod that takes a flow builder, runs once when the class is built, and the analyzer does not check its body: itsif, loops and calls are construction-time logic. The definition it returns is what the engine gets. Keep such helpers free of time, environment and randomness.Reflection (
Type.GetMethod(...),Activator.CreateInstance(...)): flagged as WF003 (invocation of metadata-onlySystem.Reflection).Runtime-configured workflows built by a service/DI: the
Specproperty’s initializer is the entry point. If the workflow class has a constructor that fetches data before buildingSpec, the analyzer only walks theSpecgetter — the constructor runs at runtime and is outside scope. Keep workflow definitions pure (no constructor state dependency).
Quick reference
| ID | Short name | Severity |
|---|---|---|
| WF001 | Imperative control flow | Error |
| WF002 | Async/await | Error |
| WF003 | Call into non-trusted assembly | Error |
| WF004 | new on non-trusted type | Error |
| WF005 | C# ?: / ?? / ?. | Error |
| WF006 | Non-trusted field/property read | Error |
| WF010 | Reachable helper violation (cross-project) | Error |
| WF020 | Declarative workflow class cannot be read as a workflow | Error |
| WF021 | Workflow not bundled by the canonical artifact generator | Warning |
The StellaOps.Workflow.Analyzerpage of the .NET API reference lists the same diagnostics with their messages.
