Skip to content

Server: make StateMachines the one state-machine builder - #5225

Merged
marcschier merged 3 commits into
masterfrom
romanett/md1-statemachine-builder-6e82b3
Dec 1, 2026
Merged

marcschier merged 3 commits into
masterfrom
romanett/md1-statemachine-builder-6e82b3

Conversation

@romanett

@romanett romanett commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Proposed changes

Opc.Ua.Server had two state-machine builders: the Fluent IStateMachineBuilder (namespace Opc.Ua.Server.Fluent) and StateMachineBuilder<T> (namespace Opc.Ua.Server.StateMachines). Both namespaces define an AsStateMachine() extension on INodeBuilder<T>, so a file that imports both fails with an ambiguous-call error (MD-1).

StateMachineBuilder<T> is now the only implementation, and the Fluent builder forwards to it.

What changed

  • StateMachines gained the features that only Fluent had:
    • WithCause(MethodState method, uint causeId, bool reportExecutable = true) maps a method to an explicit cause id. The method can be anywhere in the node manager.
    • WithTimedCause(uint fromStateId, TimeSpan timeout, uint causeId) sets up a one-shot timed cause.
    • An internal source-state guard slot runs after the machine's existing OnBeforeTransition handler, which is the order Fluent guards ran in.
  • The Fluent builder is a thin adapter:
    • FluentStateMachineBuilderAdapter<T> wraps StateMachineBuilder<T>. It keeps the Fluent argument validation and the "method already has a handler" check.
    • The Fluent timed transition polls from the simulation loop and retries every tick while a guard rejects it. That logic moved into PolledTimedCauseScheduler.
    • The Fluent facade files moved to StateMachines/Fluent/. The namespace is unchanged.
  • Ambiguity fix (least-breaking option):
    • The Fluent AsStateMachine gained an optional TimeSpan? timedTransitionTickInterval = null parameter.
    • With both namespaces imported, C# overload resolution now prefers the StateMachines overload, because it needs no default argument. Fluent-only files still bind to the Fluent overload.
    • The old one-parameter signature is kept as a hidden ([EditorBrowsable(Never)]) non-extension method, so assemblies compiled against 2.0.x keep working.

Public API changes (all additions)

  • StateMachineBuilder<T>.WithCause(MethodState, uint, bool = true)
  • StateMachineBuilder<T>.WithTimedCause(uint, TimeSpan, uint)
  • Opc.Ua.Server.Fluent.StateMachineBuilderExtensions.AsStateMachine<T>(this INodeBuilder<T>, TimeSpan? = null); the old one-parameter signature is kept, hidden.
  • The internal FluentStateMachineBuilder<T> is removed.

Behaviour changes on the Fluent path only

  • Callbacks now run exit → transition → enter. Before this change the order was exit → enter → transition.
  • An exception from a transition observer is now logged instead of becoming the transition result.
  • WithCause on a FluentFiniteStateMachineState now adds the Part 16 HasCause references.

Transition-path unification

Related Issues

Types of changes

  • Bugfix (non-breaking change which fixes an issue)
  • Enhancement (non-breaking change which adds functionality)

Checklist

  • I have read the CONTRIBUTING doc.
  • I have signed the CLA.
  • I ran tests locally with my changes, all passed.
  • I fixed all failing tests in the CI pipelines.
  • I fixed all introduced issues with CodeQL and LGTM.
  • I have added tests that prove my fix is effective or that my feature works and increased code coverage.
  • I have added necessary documentation (if appropriate).
  • Any dependent changes have been merged and published in downstream modules.

Further comments

Tests. The new StateMachineBuilderEntryPointTests file imports both namespaces. It covers:

  • compiling and binding with both namespaces imported, including the old one-parameter entry point,
  • a parity test that drives the same machine through both entry points and compares results, callbacks, CurrentState/LastTransition, transition and audit events, and HasCause references,
  • the new WithCause and WithTimedCause overloads.

Local results on net10.0:

Suite Passed Failed
StateMachines, Fluent and Programs (filtered) 293 0
PackML 258 0
ISA95 157 0
Di 612 0
Full Opc.Ua.Server.Tests 12,548 8
  • The 8 failures are FileSystem symlink tests that fail locally with an insufficient-privileges error when creating symlinks, and look unrelated to this change. I didn't rerun them on master to confirm.
  • net48 builds with 0 errors and 0 warnings.

docs/StateMachines.md now explains which AsStateMachine() you get when both namespaces are imported.

🤖 Generated with Claude Code

The Fluent IStateMachineBuilder had its own transition-hook implementation
next to StateMachines.StateMachineBuilder<T>, and both namespaces exposed an
AsStateMachine() extension on INodeBuilder<T>, so a file importing both did
not compile.

- Fluent IStateMachineBuilder is now a thin adapter
  (FluentStateMachineBuilderAdapter) over StateMachineBuilder<T>. Its
  enter/exit/transition hooks, guards and causes go through the
  StateMachines dispatcher. The polled, retrying timed cause moved to
  PolledTimedCauseScheduler. The Fluent facade files now live under
  StateMachines/Fluent (namespace unchanged), so StateMachines owns all
  state-machine building.
- StateMachineBuilder<T> gains WithCause(MethodState, causeId),
  WithTimedCause(from, timeout, causeId) and an internal source-state guard
  slot that runs after the machine's pre-existing OnBeforeTransition (the
  Fluent guard contract).
- Fluent AsStateMachine takes an optional timedTransitionTickInterval. With
  both namespaces imported, the StateMachines overload is now the better
  match. The old single-parameter signature stays as a hidden non-extension
  method for binary compatibility.
- Fluent path behaviour changes: callbacks run exit -> transition -> enter
  (was exit -> enter -> transition); transition-observer exceptions are
  logged; WithCause on a FluentFiniteStateMachineState adds HasCause
  references.

Tests: compile test importing both namespaces, binary-compat entry point,
Fluent-vs-StateMachines parity (results, callbacks, CurrentState/
LastTransition, transition and audit events, HasCause references), and the
new WithCause/WithTimedCause overloads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings December 1, 2026 05:00
@romanett romanett changed the title Server: make StateMachines the one state-machine builder (MD-1) Server: make StateMachines the one state-machine builder Dec 1, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Dispatcher installation can silently remove an existing rejecting guard, while exceptions in pre-existing after-transition handlers suppress Fluent lifecycle callbacks and timed-cause rearming.

2 open issues
What changed in this PR

Consolidates server state-machine building around StateMachines.StateMachineBuilder<T>, retaining the Fluent API as an adapter and resolving the ambiguous AsStateMachine() call when both namespaces are imported.

Changes:

  • Adds explicit method-to-cause binding, one-shot timed causes, and Fluent-compatible source-state guards.
  • Replaces the separate Fluent implementation with an adapter, preserving polling retries and the legacy binary entry point.
  • Adds entry-point and behavior-parity tests, updates lifecycle tests, and documents overload selection.
File Description
tests/​Opc.Ua.Server.Tests/​StateMachines/​StateMachineLifetimeRegressionTests.cs Uses the adapter and direct scheduler access in existing tests.
tests/​Opc.Ua.Server.Tests/​StateMachines/​StateMachineBuilderEntryPointTests.cs Tests overload binding, behavior parity, and new cause APIs.
src/​Opc.Ua.Server/​StateMachines/​StateMachineBuilderExtensions.cs Clarifies an XML documentation reference to WithCause.
src/​Opc.Ua.Server/​StateMachines/​StateMachineBuilder.cs Adds explicit causes, timed causes, source-state guards, and polling logs.
src/​Opc.Ua.Server/​StateMachines/​Fluent/​StateMachineBuilderExtensions.cs Routes Fluent entry points through the adapter and resolves overload ambiguity.
src/​Opc.Ua.Server/​StateMachines/​Fluent/​PolledTimedCauseScheduler.cs Extracts Fluent timed-cause polling, retries, and warning suppression.
src/​Opc.Ua.Server/​StateMachines/​Fluent/​IStateMachineBuilder.cs Updates the relocated interface’s entry-point documentation reference.
src/​Opc.Ua.Server/​StateMachines/​Fluent/​FluentStateMachineBuilderAdapter.cs Delegates Fluent operations to the shared builder while retaining Fluent-specific behavior.
src/​Opc.Ua.Server/​Fluent/​StateMachineBuilder.cs Removes the separate Fluent builder implementation.
docs/​StateMachines.md Explains entry-point selection, semantic differences, and new cause APIs.

Review effort: Balanced

…ailures

- Capture the machine's transition callback factories when a dispatcher
  installs itself, not when it is constructed. Two builders created for
  the same machine before either registered a hook both captured the
  empty factory, so the second install silently dropped the first's
  guards and observers.
- A throwing pre-existing OnAfterTransition (or synchronizer) no longer
  skips the exit/transition/enter callbacks and timer re-arming after the
  state has committed. The failure still reaches the caller once the
  lifecycle has been dispatched, matching the asynchronous path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Code coverage

✅ Coverage gate passed.

Check Result Threshold
✅ Project line rate 89.50% (515331/575760 lines) >= 70.00%
✅ Project branch rate 80.15% >= 60.00%
✅ Patch coverage 97.51% (196/201 changed lines) >= 75.00% (> 100 changed lines)
ℹ️ Baseline delta (advisory) +15.90 pp 73.60% recorded
Uncovered changed lines
  • src/Opc.Ua.Server/StateMachines/StateMachineBuilder.cs: 2215, 2217, 2218, 2232
  • src/Opc.Ua.Server/StateMachines/Fluent/PolledTimedCauseScheduler.cs: 121

Coverage is above the recorded baseline - consider ratcheting coverage-thresholds.json.

Thresholds live in coverage-thresholds.json. Whole report before exclusions: line 89.05%, branch 79.66%.

@marcschier
marcschier requested a balanced review from Copilot December 1, 2026 07:01
…dard into romanett/md1-statemachine-builder-6e82b3

# Conflicts:
#	src/Opc.Ua.Server/Fluent/StateMachineBuilder.cs

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues block the state-machine builder consolidation.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

@codecov

codecov Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.02985% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 83.86%. Comparing base (1b57a2c) to head (ad6a1a2).
⚠️ Report is 5 commits behind head on master.

Files with missing lines Patch % Lines
...Opc.Ua.Server/StateMachines/StateMachineBuilder.cs 91.07% 4 Missing and 1 partial ⚠️
...achines/Fluent/FluentStateMachineBuilderAdapter.cs 95.69% 0 Missing and 4 partials ⚠️
.../StateMachines/Fluent/PolledTimedCauseScheduler.cs 93.47% 1 Missing and 2 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #5225      +/-   ##
==========================================
- Coverage   83.88%   83.86%   -0.03%     
==========================================
  Files        3879     3880       +1     
  Lines      575744   575760      +16     
  Branches    99275    99273       -2     
==========================================
- Hits       482956   482848     -108     
- Misses      60108    60206      +98     
- Partials    32680    32706      +26     
Flag Coverage Δ
actions 83.86% <94.02%> (-0.03%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...teMachines/Fluent/StateMachineBuilderExtensions.cs 72.34% <100.00%> (ø)
...ver/StateMachines/StateMachineBuilderExtensions.cs 50.00% <ø> (+50.00%) ⬆️
.../StateMachines/Fluent/PolledTimedCauseScheduler.cs 93.47% <93.47%> (ø)
...achines/Fluent/FluentStateMachineBuilderAdapter.cs 95.69% <95.69%> (ø)
...Opc.Ua.Server/StateMachines/StateMachineBuilder.cs 79.90% <91.07%> (+0.95%) ⬆️

... and 66 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@marcschier
marcschier enabled auto-merge (squash) December 1, 2026 12:17
@marcschier marcschier added the ready Ready to merge once CI Passes label Dec 1, 2026
@marcschier
marcschier merged commit 33abf88 into master Dec 1, 2026
252 of 254 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready Ready to merge once CI Passes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants