caishen

State Machine Runtime Engine

RISE Framework Specification

Spec ID: 61
Version: 1.1
Document ID: caishen-rise-smrt-v1.1
Last Updated: 2026-02-23
Source: Extracted from SCDE/SMCG/StateMachine/ (Context.cs, State.cs, Event.cs, IObserver.cs, ContextAsync.cs, ContextParallel.cs)
Implementation: smcraft — Python: smcraft/py/smcraft/runtime.py | TypeScript: smcraft/ts/src/runtime.ts

Creative Intent

What the Runtime Engine Enables Users to Create:

Desired Outcomes:

  1. State machines execute faithfully according to their definition
  2. Entry/exit actions fire in correct hierarchical order during transitions
  3. Observers receive all state lifecycle events for debugging and auditing
  4. Async machines safely process events from multiple sources
  5. Running state machines can be serialized, stored, and restored

Architecture Overview

┌──────────────────────────────────────────────────────────┐
│                    Runtime Engine                         │
│                                                          │
│  ┌─────────────┐  ┌──────────────┐  ┌────────────────┐  │
│  │   Context    │  │    State     │  │    Observer     │  │
│  │  (manages    │  │  (hierarchy  │  │  (monitors     │  │
│  │   lifecycle) │  │   & actions) │  │   transitions) │  │
│  └──────┬──────┘  └──────┬───────┘  └───────┬────────┘  │
│         │                │                   │           │
│  ┌──────▼──────┐  ┌──────▼───────┐          │           │
│  │   Event     │  │  Transition  │──────────┘           │
│  │  Dispatcher │  │   Helper     │                      │
│  └─────────────┘  └──────────────┘                      │
│                                                          │
│  ┌─────────────────────────────────────────────────────┐ │
│  │              Context Variants                       │ │
│  │  ┌──────────┐  ┌────────────┐  ┌───────────────┐   │ │
│  │  │  Sync    │  │   Async    │  │   Parallel    │   │ │
│  │  │ Context  │  │  Context   │  │   Context     │   │ │
│  │  └──────────┘  └────────────┘  └───────────────┘   │ │
│  └─────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────┘

Core Components

ContextBase

The abstract foundation for all state machine contexts.

Behavior:

Abstract Class ContextBase:

  Properties:
    - Name: string — context identifier
    - TransitionName: string — name of current transition in progress
    - Observer: IObserver — pluggable observer for state lifecycle events
    - ContextParallel: ContextParallel — parent parallel context (if in parallel region)

  Events:
    - OnEnd: EndHandler — fires when state machine completes (reaches final state)

  Methods:
    - EnterInitialState() → void
        Behavior: Enters the root state's initial child, triggering OnEntry chain
    - SetState(stateName: string) → void
        Behavior: Sets current state by name (for deserialization)
    - Serialize(writer: StreamWriter) → void
        Behavior: Writes current state to persistent storage
    - DeSerialize(reader: StreamReader) → void
        Behavior: Restores state from persistent storage

  Internal:
    - AddChild(child: ContextBase) → void
        Behavior: Registers a child context (parallel region)
    - OnEnd() → void
        Behavior: Fires the end event, notifies parent parallel context

Context (Synchronous)

Generic synchronous context that tracks current, previous, next, and history states.

Behavior:

Class Context<TState, TContextParent> extends ContextBase:

  Properties:
    - StateCurrent: TState — the currently active state
    - StatePrevious: TState — state before the last transition
    - StateNext: TState — target state during transition processing
    - StateHistory: TState — remembered state for history transitions
    - ContextParent: TContextParent — parent context reference

  Methods:
    - SetInitialState(state: TState) → void
        Behavior: Sets the initial state and triggers OnEntry
    - SaveState() → void
        Behavior: Records StateCurrent as StateHistory (for history states)
    - Serialize(writer: StreamWriter) → void
        Behavior: Writes StateCurrent name to stream
    - DeSerialize(reader: StreamReader) → void
        Behavior: Reads state name from stream, calls SetState()

ContextAsync (Asynchronous)

Extends synchronous context with event queuing and thread-pool dispatching.

Behavior:

Class ContextAsync<TState, TContextParent> extends Context<TState, TContextParent>:

  Properties:
    - MaxEventProcessed: int (default 1024) — max events per ProcessEvents cycle

  Internal State:
    - eventQueue: Queue<EventBase> — FIFO event queue
    - lockObject: object — synchronization lock

  Methods:
    - ScheduleEvent(event: EventBase) → void
        Behavior: Enqueues event, schedules ProcessEvents on thread pool
    - ProcessEvents() → void
        Behavior:
          1. Lock the queue
          2. Dequeue up to MaxEventProcessed events
          3. For each event, dispatch to current state's handler
          4. If queue still has events, schedule another ProcessEvents
    - SerializeEvents(writer: StreamWriter) → void
        Behavior: Writes queued event IDs to stream
    - DeSerializeEvents(reader: StreamReader) → void
        Behavior: Restores event queue from stream

ContextParallel

Manages orthogonal regions that execute independently within a parallel state.

Behavior:

Abstract Class ContextParallel:

  Properties:
    - ActiveState: int — count of currently active orthogonal regions

  Methods:
    - TransitionToNextState() → void (abstract)
        Behavior: Called when ActiveState reaches 0 (all regions complete).
                  Transitions the parent context to the parallel element's nextState.

State

Represents a node in the state hierarchy.

Behavior:

Enum StateKind:
  - Leaf        — no children, processes events
  - Composite   — has child states, first child is initial
  - Root        — outermost state (composite)
  - Final       — terminal state, triggers OnEnd
  - Parallel    — contains orthogonal regions
  - History     — remembers previous sibling state

Abstract Class State<TContext, TState>:

  Properties:
    - Name: string — unique state identifier
    - Kind: StateKind — classification
    - StateParent: TState — parent in state hierarchy (null for root)

  Methods:
    - OnEntry(context: TContext) → void (abstract)
        Behavior: Executes entry actions for this state
    - OnExit(context: TContext) → void (abstract)
        Behavior: Executes exit actions for this state

Event System

Provides typed event dispatching with 0–4 parameters.

Behavior:

Abstract Class EventBase:
  Properties:
    - EventId: string — matches the definition event ID

  Methods:
    - Dispatch() → void (abstract)
        Behavior: Invokes the bound handler delegate

Delegate Types:
  - Handler0: () → void
  - Handler1<T>: (T) → void
  - Handler2<T1, T2>: (T1, T2) → void
  - Handler3<T1, T2, T3>: (T1, T2, T3) → void
  - Handler4<T1, T2, T3, T4>: (T1, T2, T3, T4) → void

Class EventFactory:
  Static Methods:
    - Create(id: string, handler: Handler0) → EventBase
    - Create<T>(id: string, handler: Handler1<T>, param1: T) → EventBase
    - Create<T1,T2>(id: string, handler: Handler2<T1,T2>, p1: T1, p2: T2) → EventBase
    - Create<T1,T2,T3>(id: string, handler: Handler3, p1, p2, p3) → EventBase
    - Create<T1,T2,T3,T4>(id: string, handler: Handler4, p1, p2, p3, p4) → EventBase

Transition Helper

Processes state transitions with correct hierarchical entry/exit ordering.

Behavior:

Static Class TransitionHelper:

  Methods:
    - ProcessTransitionBegin(context: ContextBase, statePrev: State, stateNext: State, transitionName: string) → void
        Behavior:
          1. Set context.TransitionName
          2. Walk exit chain: call OnExit from statePrev up to common ancestor
          3. Notify observer: OnTransitionBegin(context, statePrev, stateNext, transitionName)

    - ProcessTransitionEnd(context: ContextBase, statePrev: State, stateNext: State) → void
        Behavior:
          1. Walk entry chain: call OnEntry from common ancestor down to stateNext
          2. Notify observer: OnTransitionEnd(context, statePrev, stateNext)
          3. Clear context.TransitionName
          4. If stateNext is Final, call context.OnEnd()

  Internal:
    - WalkChainExit(context, stateFrom, stateTo) → void
        Behavior: Recursively calls OnExit up the parent chain until reaching stateTo
    - WalkChainEntry(context, stateFrom, stateTo) → void
        Behavior: Recursively calls OnEntry down the parent chain from stateFrom to stateTo

Observer

Pluggable monitoring interface for state machine lifecycle events.

Behavior:

Interface IObserver:

  Methods:
    - OnEntry(contextName: string, stateName: string) → void
    - OnExit(contextName: string, stateName: string) → void
    - OnTransitionBegin(contextName: string, statePrev: string, stateNext: string, transitionName: string) → void
    - OnTransitionEnd(contextName: string, statePrev: string, stateNext: string, transitionName: string) → void
    - OnTimerStart(contextName: string, timerName: string, duration: int) → void
    - OnTimerStop(contextName: string, timerName: string) → void

Built-in Implementations:
  - ObserverNull: All methods are no-ops. Default observer. Singleton.
  - ObserverConsole: Logs all events to stdout with format "{context}: {event} {details}". Singleton.
  - ObserverTrace: Logs all events to a named trace source at Verbose level.

Message Bus Integration (CreasTypes)

Extended integration layer for pub/sub event distribution.

Behavior:

Interface IBusPublisher:
  Methods:
    - PublishBusMessage<T>(message: T) → void

Interface IBusSubscriber:
  Methods:
    - SubscribeWithReceiver<T>() → void
    - UnSubscribeReceiver<T>() → void

Interface IMessageReceiver<T>:
  Properties:
    - OnMessageReceived: event handler
  Methods:
    - Subscribe() → void
    - UnSubscribe() → void

Interface IEntityState:
  Properties:
    - CurrentStateName: string — current state machine state name

Service Contracts

IStateMachineRuntime

Interface IStateMachineRuntime:

  Method CreateContext:
    Input: definition: StateMachineDefinition, objects: Map<string, object>
    Output: ContextBase
    Behavior: Instantiates a context from a definition, wiring object references

  Method LoadContext:
    Input: serializedState: string, definition: StateMachineDefinition
    Output: ContextBase
    Behavior: Restores a previously serialized context

  Method SetObserver:
    Input: context: ContextBase, observer: IObserver
    Output: void
    Behavior: Attaches an observer to the context

Creative Advancement Scenarios

Scenario: Strategy State Machine Execution

Desired Outcome: A BDBO trading strategy naturally advances through its lifecycle states
Current Reality: Strategy state is tracked manually with if/else chains
Natural Progression:

  1. Strategy context is created from the BDBO definition (Spec 60)
  2. EnterInitialState() places the machine in Idle
  3. Market events feed into the context: PriceBreakout, SignalFound, OrderFilled
  4. TransitionHelper walks the state hierarchy, firing entry/exit actions
  5. Observer logs every transition for audit trail
  6. When Completed (final) is reached, OnEnd fires and strategy is archived
    Resolution: Strategy lifecycle is fully managed by the runtime with complete observability

Scenario: Async Multi-Source Event Processing

Desired Outcome: A state machine safely handles events from multiple concurrent sources
Current Reality: Manual locking and queue management code
Natural Progression:

  1. ContextAsync is instantiated with asynchronous mode
  2. Market data thread calls ScheduleEvent(PriceBreakout)
  3. Timer thread calls ScheduleEvent(Timeout)
  4. Events are safely enqueued with lock protection
  5. ProcessEvents dequeues and dispatches sequentially — no race conditions
  6. State transitions proceed in correct order regardless of event source timing
    Resolution: Thread-safe event processing without manual synchronization code

Scenario: State Machine Persistence and Recovery

Desired Outcome: A running strategy survives application restart
Current Reality: State is lost on crash, requiring manual re-creation
Natural Progression:

  1. Context.Serialize() writes current state name and event queue to storage
  2. Application restarts and reads the serialized data
  3. Context.DeSerialize() restores the state machine to its exact prior position
  4. Processing resumes from where it left off — no events lost
    Resolution: State machine continuity across process boundaries

Timer Implementation

Timers are managed by the runtime:

Timer Lifecycle:
  1. TimerStart action creates a platform timer with specified duration
  2. Timer runs in background
  3. When duration elapses, timer fires its event ID into the context
  4. For ContextAsync: event is scheduled via ScheduleEvent
  5. For Context (sync): event is dispatched immediately
  6. TimerStop action cancels the timer before it fires
  7. Entering a state with timerStart in onEntry automatically starts the timer
  8. Exiting a state with timerStop in onExit automatically stops the timer

Dependencies


Implementation Notes

Python Implementation Guidance

TypeScript Implementation Guidance