HFSM Validation Rules

To ensure that FSM state definitions are correct, valid, and executable, all HFSM configurations must comply with the following formalized validation rules:

1. Initial Transition Rule

Rule: Every state that declares states: must include an initial transition: ["", "*", <InitialSubState>].

Validation: Composite states require explicit initial transitions to define entry behavior.

Correct:

key: Light
transitions:
  - ["", "*", Off]  # Required initial transition
  - [Off, toggle, On]
  - [On, toggle, Off]
states:
  - key: Off
    description: Light is turned off
    events: [toggle]
  - key: On
    description: Light is turned on
    events: [toggle]

Incorrect:

key: Light
transitions:
  - [Off, toggle, On]  # Missing initial transition
states:
  - key: Off
  - key: On

2. Parent-Level Transition Declaration

Rule: All transitions between sibling states must be declared in their parent transitions: block.

Validation: Sibling-to-sibling transitions must not be placed inside child states.

Correct:

key: Light
transitions:
  - ["", "*", Off]
  - [Off, toggle, On]    # Declared at parent level
  - [On, toggle, Off]    # Declared at parent level
states:
  - key: Off
    description: Light is turned off
    events: [toggle]
  - key: On
    description: Light is turned on
    events: [toggle]

Incorrect:

key: Light
states:
  - key: Off
    transitions:
      - [Off, toggle, On]  # ❌ Should be at parent level
  - key: On

3. Exit Transition Handling

Rule: Use [SomeState, <event>, ""] to represent termination (exit) of the current parent scope.

Validation: Sub-state exit events must be captured and handled by the parent state.

Example:

key: TicketFlow
transitions:
  - ["", "*", Handle]
  - [Handle, resolved, Closed]   # Parent handles exit event from sub-state
  - [Closed, done, ""]
states:
  - key: Handle
    description: Handle the support ticket
    transitions:
      - ["", "*", Diagnose]
      - [Diagnose, notResolved, Escalate]
      - [Diagnose, resolved, ""]     # Sub-state exits to parent
      - [Escalate, resolved, ""]
    states:
      - key: Diagnose
        description: Identify the issue
        events: [resolved, notResolved]
      - key: Escalate
        description: Escalate to L2
        events: [resolved]
  - key: Closed
    description: Ticket is closed
    events: [done]

4. Reachability Requirement

Rule: Every state must be reachable from its parent via some chain of transitions starting at the parent’s initial transition.

Validation: Check that all defined states can be reached through valid transition paths.

5. Dead-End Prevention

Rule: Non-final states should have at least one outgoing transition defined at the appropriate parent level.

Validation: States must have exit paths unless they are intentionally terminal states.

6. Event Naming Requirements

Rule: All transitions must have a named event (non-empty), except:

Validation: Events must follow camelCase naming convention and be semantically meaningful.

7. Hierarchy Consistency

Rule: Transitions must reference states that are defined at the same parent level as the transition itself.

Validation: Cross-level jumps should be modeled through exit events handled by the parent rather than directly referencing deep descendants.

8. Single Source of Truth

Rule: Declare all relationships between siblings in the parent’s transitions: block to avoid ambiguity.

Validation: Sibling state relationships must have exactly one authoritative declaration point.

9. Determinism with Wildcards

Rule: If you use * (wildcard) transitions, ensure they do not make the machine ambiguous with overlapping specific events at the same priority level.

Validation: Wildcard usage must not create transition conflicts or ambiguous behavior.

10. Complex Process Validation Rules

10.1 Hierarchical State Decomposition

Rule: When encountering lengthy processes with many sequential steps, group related steps into logical phases represented as composite states with sub-states.

Validation:

Example:

key: OrderFulfillment
description: Complete order processing workflow
transitions:
  - ["", "*", OrderValidation]
  - [OrderValidation, validated, PaymentProcessing]
  - [PaymentProcessing, paymentCompleted, InventoryManagement]
  - [InventoryManagement, allocated, Shipping]
  - [Shipping, shipped, ""]
states:
  - key: OrderValidation
    description: Validate order details and customer information
    events: [validated, validationFailed]
  - key: PaymentProcessing
    description: Process payment and handle billing
    events: [paymentCompleted, paymentFailed]
  - key: InventoryManagement
    description: Allocate inventory for the order
    events: [allocated, outOfStock]
  - key: Shipping
    description: Ship the order to customer
    events: [shipped, shippingFailed]

10.2 Cycle Break Event Validation

Rule: Pay special attention to states with cycles to ensure there are events breaking these cycles (to avoid infinite loops).

Validation: Every cyclical pattern must have at least one exit condition that generates an event leading outside the cycle. All cycles must include:

Required Cycle Validation Checks:

Example - Valid Retry Loop:

key: DocumentReview
transitions:
  - ["", "*", UnderReview]
  - [UnderReview, approved, Approved]          # Success exit
  - [UnderReview, requiresRevision, RequiresRevision]
  - [RequiresRevision, revised, UnderReview]   # Cycle continuation
  - [RequiresRevision, maxRevisionsExceeded, Rejected]  # Failure exit
  - [Approved, published, ""]
  - [Rejected, archived, ""]
states:
  - key: UnderReview
    description: Document being reviewed by approvers
    events: [approved, requiresRevision]
  - key: RequiresRevision
    description: Document needs revisions from author
    events: [revised, maxRevisionsExceeded]
  - key: Approved
    description: Document approved and ready for publishing
    events: [published]
  - key: Rejected
    description: Document rejected after max revisions
    events: [archived]

10.3 Branching and Decision Point Validation

Rule: Identify and properly model conditional branching points and decision logic within processes.

Validation:

Required Branching Validation Checks:

Example - Valid Decision Branching:

key: AccountValidation
transitions:
  - ["", "*", ValidateCredentials]
  - [ValidateCredentials, validCredentials, CheckAccountStatus]
  - [ValidateCredentials, invalidCredentials, AuthenticationFailed]
  - [CheckAccountStatus, activeAccount, GrantAccess]
  - [CheckAccountStatus, suspendedAccount, AccountSuspended]
  - [CheckAccountStatus, expiredAccount, AccountExpired]
  - [GrantAccess, accessGranted, ""]
  - [AuthenticationFailed, loginFailed, ""]
  - [AccountSuspended, notifyUser, ""]
  - [AccountExpired, redirectRenewal, ""]
states:
  - key: ValidateCredentials
    description: Check username and password
    events: [validCredentials, invalidCredentials]
  - key: CheckAccountStatus
    description: Verify account is active and valid
    events: [activeAccount, suspendedAccount, expiredAccount]
  - key: GrantAccess
    description: Grant access to the system
    events: [accessGranted]
  - key: AuthenticationFailed
    description: Authentication has failed
    events: [loginFailed]
  - key: AccountSuspended
    description: Account is suspended
    events: [notifyUser]
  - key: AccountExpired
    description: Account has expired
    events: [redirectRenewal]

10.4 Sub-process Integration Validation

Rule: Sub-processes must be properly integrated with their parent processes while maintaining clear boundaries.

Validation:

11. Event-Transition Consistency Rules

11.1 Forward Event-Transition Validation

Rule: All events defined in a state’s events field must have corresponding transitions defined either in the current parent’s transitions section or in ancestor parent states’ transitions sections.

Validation: Every event that a state can emit must have a defined transition path that handles that event.

Correct:

key: OrderProcess
transitions:
  - ["", "*", ValidateOrder]
  - [ValidateOrder, orderValid, ProcessPayment]     # Handles orderValid event
  - [ValidateOrder, orderInvalid, RejectOrder]      # Handles orderInvalid event
  - [ProcessPayment, paymentSuccess, FulfillOrder]
  - [ProcessPayment, paymentFailed, NotifyFailure]
  - [FulfillOrder, orderFulfilled, ""]
  - [RejectOrder, orderRejected, ""]
  - [NotifyFailure, notificationSent, ""]
states:
  - key: ValidateOrder
    description: Validate order details
    events: [orderValid, orderInvalid]              # Both events have transitions
  - key: ProcessPayment
    description: Process customer payment
    events: [paymentSuccess, paymentFailed]         # Both events have transitions
  - key: FulfillOrder
    description: Fulfill the validated order
    events: [orderFulfilled]                        # Event has transition
  - key: RejectOrder
    description: Reject invalid order
    events: [orderRejected]                         # Event has transition
  - key: NotifyFailure
    description: Notify about payment failure
    events: [notificationSent]                      # Event has transition

Incorrect:

key: OrderProcess
transitions:
  - ["", "*", ValidateOrder]
  - [ValidateOrder, orderValid, ProcessPayment]
  # Missing transition for orderInvalid event
states:
  - key: ValidateOrder
    description: Validate order details
    events: [orderValid, orderInvalid]              # ❌ orderInvalid has no transition

11.2 Reverse Transition-Event Validation

Rule: All events referenced in transitions must exist in the events field of the corresponding source state or be inherited from parent states.

Validation: Every transition event must be declared as an emittable event by the source state.

Correct:

key: UserAuth
transitions:
  - ["", "*", Login]
  - [Login, loginSuccess, Dashboard]               # loginSuccess declared in Login state
  - [Login, loginFailed, RetryLogin]               # loginFailed declared in Login state
  - [RetryLogin, retry, Login]                     # retry declared in RetryLogin state
  - [RetryLogin, giveUp, LoginCancelled]           # giveUp declared in RetryLogin state
states:
  - key: Login
    description: User login attempt
    events: [loginSuccess, loginFailed]             # Events match transitions
  - key: RetryLogin
    description: Allow user to retry login
    events: [retry, giveUp]                         # Events match transitions
  - key: Dashboard
    description: User dashboard
    events: []
  - key: LoginCancelled
    description: Login process cancelled
    events: []

Incorrect:

key: UserAuth
transitions:
  - ["", "*", Login]
  - [Login, loginSuccess, Dashboard]
  - [Login, unauthorizedAccess, SecurityAlert]     # ❌ unauthorizedAccess not in Login events
states:
  - key: Login
    description: User login attempt
    events: [loginSuccess, loginFailed]             # Missing unauthorizedAccess event

11.3 Hierarchical Event Inheritance

Rule: Child states can emit events that are handled by parent state transitions, but such events must be explicitly documented in the child state’s events field.

Validation: Event handling can bubble up the hierarchy, but event emission must be explicitly declared at each level.

Correct:

key: DocumentWorkflow
transitions:
  - ["", "*", Editing]
  - [Editing, documentCompleted, Review]           # Parent handles child's exit event
  - [Review, approved, Published]
  - [Review, rejected, Editing]
states:
  - key: Editing
    description: Document editing phase
    transitions:
      - ["", "*", Draft]
      - [Draft, save, Draft]
      - [Draft, submit, Validation]
      - [Validation, valid, ""]                    # Exit to parent with documentCompleted
      - [Validation, invalid, Draft]
    states:
      - key: Draft
        description: Drafting the document
        events: [save, submit]
      - key: Validation
        description: Validate document before submission
        events: [valid, invalid, documentCompleted] # documentCompleted for parent
  - key: Review
    description: Document review phase
    events: [approved, rejected]
  - key: Published
    description: Document is published
    events: []

11.4 Exit Event Propagation

Rule: When a child state uses ["<state>", "<event>", ""] to exit to its parent, the parent must handle that event in its own transitions.

Validation: Exit events from child states must be caught and processed by parent states.

Correct:

key: TaskExecution
transitions:
  - ["", "*", Execute]
  - [Execute, taskCompleted, Cleanup]              # Parent handles exit event
  - [Execute, taskFailed, ErrorHandling]           # Parent handles exit event
  - [Cleanup, cleanupDone, ""]
  - [ErrorHandling, errorResolved, ""]
states:
  - key: Execute
    description: Execute the task
    transitions:
      - ["", "*", Prepare]
      - [Prepare, ready, Run]
      - [Run, success, ""]                         # Exit with taskCompleted
      - [Run, failure, ""]                         # Exit with taskFailed
    states:
      - key: Prepare
        description: Prepare for execution
        events: [ready]
      - key: Run
        description: Run the task
        events: [success, failure, taskCompleted, taskFailed] # Include exit events

Event-Transition Consistency Validation Checklist

Add these checks to your validation process:

Forward Validation (Events → Transitions)

Reverse Validation (Transitions → Events)

Hierarchical Event Flow

Event Scope Validation

Semantic Validation

Formal Validation Checklist

Before finalizing any HFSM definition, verify the following:

Structural Validation

Complex Process Validation

Field Validation

Semantic Validation

Event-State Compatibility Rule

Rule: Ensure that transitions to the same target state only happen when the originating step outcomes are semantically compatible.

Wrong:

transitions: 
  - [ValidateAccount, accountValid, HandleRequest]
  - [ValidateAccount, accountInvalid, HandleRequest]  # Incompatible outcomes

Correct:

transitions: 
  - [ValidateAccount, accountValid, HandleRequest]
  - [ValidateAccount, accountNotFound, CreateAccount]
  - [CreateAccount, accountCreated, HandleRequest]  # Compatible outcomes

Validation Implementation

When implementing HFSM validation, incorporate these programmatic checks:

  1. Structural Integrity: Verify parent-child relationships and transition declarations
  2. Event Flow Validation: Ensure events emitted by states correspond to valid transitions
  3. Reachability Analysis: Perform graph traversal to verify all states are accessible
  4. Semantic Consistency: Validate that event semantics align with state outcomes
  5. Naming Convention Compliance: Check camelCase for events, PascalCase for states
  6. Cycle Detection and Validation: Identify cycles and verify proper exit conditions
  7. Hierarchical Complexity Analysis: Ensure appropriate decomposition of complex processes
  8. Decision Logic Validation: Verify complete and non-ambiguous branching conditions