Chapter 14: Chapter 14. Dependent state machines: handling feedback and errors
This introduction reviews typed state-transition guarantees and explains why realistic state machines must account for failures and environmental responses.
After this chapter you will be able to
- Typed transition guarantees. Explain how preconditions and postconditions in a dependent type describe valid state transitions and what type-checking guarantees.
- Environment-dependent state changes. Explain why a requested state change may fail or depend on an environmental response, using an example from the section.
- Door transitions and failure. Explain what the existing DoorCmd model guarantees about Open and why real hardware may not follow that guarantee.
- Result dependent door states. Explain how DoorCmd represents an output state that depends on an operation’s result, using a jammed door as an example.
- Result dependent command sequencing. Trace how sequencing DoorCmd operations connects the first result to the second operation’s input state and explain why the result must be checked.
- Result dependent door protocol. Explain how doorProg handles both outcomes of Open while ensuring the door finishes closed.
- Hole guided state refinement. Describe how a hole and a case split help diagnose and resolve the type error after Open.
- State-Based ATM Security. Explain how explicit states in operation types support the ATM’s cash-dispensing security property. Describe when the machine is in a valid state to dispense cash.
- ATM Session States. Distinguish Ready, CardInserted, and Session in terms of card presence and PIN validation.
- External PIN Validation. Explain why the ATM model cannot know in advance which inputs lead to which states.
- State Restricted ATM Operations. Describe how the ATM’s operations can have state preconditions, using card handling and cash dispensing as examples.
- PIN dependent session refinement. Trace how checking pinOK refines the hole types and guides completion of the two ATM paths.
- Type checked security property. Explain the security property of a type-checking atm definition and the constraints shared by alternative implementations.
- ATM Console Interpreter. Describe how runATM executes an ATMCmd description as console-based IO actions.
- Description and Implementation Separation. Explain why the ATM command description is separate from its IO interpreter, using the simulated PIN as an example.
- Card Ejection Preconditions. Explain how the HasCard predicate restricts EjectCard to valid ATM states.
- Automatic Predicate Evidence. Explain how an auto-implicit HasCard argument lets Idris check EjectCard without requiring explicit predicate values at each use.
- State Types and Game Rules. Explain why the earlier game type does not guarantee correct play, and describe the role of a dependent GameCmd type in expressing game rules.
- Abstract Game State. Describe the NotRunning and Running states and why Running tracks remaining guesses and letters.
- Game Operations and Preconditions. Describe the four basic game operations and the conditions for declaring a win or loss.
- Guess Transition Contract. Explain the precondition and postcondition of Guess.
- Game Loop Rule Guarantees. Explain how GameLoop supports ongoing play and what a well-typed, total gameLoop guarantees about following the rules and ending.
- Guess Result State Refinement. Trace how gameLoop uses a guess result and the type of its continuation to determine the current game state.
- Continuation and Termination Conditions. Explain when gameLoop can continue and how it ends after a win or loss.
- Abstract and concrete game states. Distinguish GameState from Game and describe how they relate.
- Result-dependent output state. Explain how GameResult represents a successful execution and why its output state can depend on the result.
- Fuel and execution failure. Explain why run uses Fuel and how GameResult represents running out of it.
- Game description and execution. Explain how GameCmd and GameLoop separate the game rules from their execution by runCmd and run. Describe how successful execution returns a result and updated state.
- Input validation and fuel. Explain how ReadGuess handles invalid input and why runCmd uses fuel. Describe the role of forever in the main program.
What it builds on
- Finite state machines: modeling a door as a type (chapter 13) · The door state machine and its typed operations.
- Interactive development of sequences of door operations (chapter 13) · Sequences of door operations connect one operation’s output state to the next operation’s input state.
- Interactive command summary (chapter 3) · Interactive commands support inspecting and refining incomplete definitions.
- Pattern-matching bindings (chapter 5) · Pattern-matching bindings in interactive programs.
- A verified vending machine description (chapter 13) · The vending-machine example checked command validity locally.
- Removing an element from a Vect: types as contracts (chapter 9) · Predicates can express conditions as type-level contracts.
- auto-implicit arguments: automatically constructing proofs (chapter 9) · Auto-implicit arguments can automatically construct predicate evidence.
- Infinite states: modeling a vending machine (chapter 13) · The vending machine state tracks pounds and chocolates.
Section by section
Introduction
This introduction reviews typed state-transition guarantees and explains why realistic state machines must account for failures and environmental responses.
- Typed transition guarantees: Explain how preconditions and postconditions in a dependent type describe valid state transitions and what type-checking guarantees.
Why it matters: These types let you check the validity of a protocol’s state transitions before running it. - Environment-dependent state changes: Explain why a requested state change may fail or depend on an environmental response, using an example from the section.
Why it matters: A realistic protocol model must allow for outcomes the program cannot control.
Key terms: dependent type, precondition, postcondition, state transition, operation failing, response from the environment, DoorClosed
14.1 Dealing with errors in state transitions
This section contrasts the door model’s guaranteed state transitions with the possibility of real hardware failure.
- Door transitions and failure: Explain what the existing DoorCmd model guarantees about Open and why real hardware may not follow that guarantee.
Why it matters: A model of a real protocol must account for failures that its idealized transitions rule out.
Key terms: DoorCmd, Open, DoorClosed, DoorOpen, state transitions
14.1.1 Refining the door model: representing failure
This section refines the door state machine so an operation’s resulting state can depend on its return value, including failure.
- Result dependent door states: Explain how DoorCmd represents an output state that depends on an operation’s result, using a jammed door as an example.
Why it matters: This lets the type describe both successful and failed door transitions accurately. - Result dependent command sequencing: Trace how sequencing DoorCmd operations connects the first result to the second operation’s input state and explain why the result must be checked.
Why it matters: Result-dependent sequencing keeps later operations consistent with the state actually reached. - Constant output state functions: Describe how const expresses an output state that does not depend on an operation’s result.
Why it matters: This lets operations with fixed outcomes fit the same result-dependent state representation.
Key terms: DoorCmd, DoorResult, Open, DoorOpen, DoorClosed, OK, (>>=), state2_fn, state3_fn, input state
14.1.2 A verified, error-checking, door-protocol description
This section develops a verified door protocol that handles failed opening operations using result-dependent states.
- Result dependent door protocol: Explain how doorProg handles both outcomes of Open while ensuring the door finishes closed.
Why it matters: The protocol prevents a close operation from being used when opening failed. - Hole guided state refinement: Describe how a hole and a case split help diagnose and resolve the type error after Open.
Why it matters: Inspecting holes turns a confusing type error into concrete branch-specific requirements. - State independent display: Explain why a Display operation can occur before checking the result of Open.
Why it matters: Not every operation requires an immediate branch on a potentially failing result. - Pattern matching failure paths: Describe how pattern-matching bindings provide a concise success path and an alternative path for a failed Open.
Why it matters: This form makes success and failure paths easier to express in longer protocols. - Pure result and state: Explain why Pure OK fits the open-state branch of logOpen.
Why it matters: Pure can return a result while satisfying a result-dependent state specification.
Key terms: DoorCmd, Open, OK, Jammed, DoorOpen, DoorClosed, hole, type error, case-split, DoorResult
14.2 Security properties in types: modeling an ATM
This section introduces using state-aware operation types to enforce an ATM cash-dispensing security property.
- State-Based ATM Security: Explain how explicit states in operation types support the ATM’s cash-dispensing security property. Describe when the machine is in a valid state to dispense cash.
Why it matters: This shows how types can enforce a security rule about when an operation is allowed.
Key terms: explicit states, type checking, security property, validated card
14.2.1 Defining states for the ATM
This section defines the ATM’s states and basic operations, including state-dependent restrictions and runtime PIN validation.
- ATM Session States: Distinguish Ready, CardInserted, and Session in terms of card presence and PIN validation.
Why it matters: These distinctions let the model express which stage of an ATM interaction has been reached. - External PIN Validation: Explain why the ATM model cannot know in advance which inputs lead to which states.
Why it matters: The model must accommodate a state outcome that depends on a runtime check. - State Restricted ATM Operations: Describe how the ATM’s operations can have state preconditions, using card handling and cash dispensing as examples.
Why it matters: These conditions express when sensitive ATM actions are permitted.
Key terms: Ready, CardInserted, Session, PIN, external service, runtime, preconditions, postconditions, EjectCard, GetPIN
14.2.2 Defining a type for the ATM
This section uses state-indexed ATM commands and type-guided refinement to describe a session that safely handles PIN outcomes and returns to Ready.
- ATM command state transitions: Describe what ATMCmd represents and how GetAmount and Message affect the machine state.
Why it matters: The command type makes the machine’s state part of the description of an ATM session. - PIN dependent session refinement: Trace how checking pinOK refines the hole types and guides completion of the two ATM paths.
Why it matters: The hole types show how the PIN result determines which actions can complete the session. - Type checked security property: Explain the security property of a type-checking atm definition and the constraints shared by alternative implementations.
Why it matters: The types enforce the important dispensing rule without requiring a single fixed sequence of user interactions.
Key terms: ATMCmd, state transitions, GetAmount, Message, pinOK, PINCheck, CorrectPIN, IncorrectPIN, Session, CardInserted
14.2.3 Simulating an ATM at the console: executing ATMCmd
This section describes a console interpreter for ATMCmd and explains why ATM command descriptions are separated from their implementations.
- ATM Console Interpreter: Describe how runATM executes an ATMCmd description as console-based IO actions.
Why it matters: This interpreter lets you try the ATM description as an interactive console simulation. - Description and Implementation Separation: Explain why the ATM command description is separate from its IO interpreter, using the simulated PIN as an example.
Why it matters: The same command description can be interpreted differently for a simulation and a real device.
Key terms: ATMCmd, runATM, IO, inState, outState_fn, interpreter, state transitions
14.2.4 Refining preconditions using auto-implicits
This section refines ATM card-ejection preconditions with a predicate and auto-implicits, then practices state-dependent protocols in security and vending exercises.
- Card Ejection Preconditions: Explain how the HasCard predicate restricts EjectCard to valid ATM states.
Why it matters: This makes the type reject attempts to eject a card when none is present. - Automatic Predicate Evidence: Explain how an auto-implicit HasCard argument lets Idris check EjectCard without requiring explicit predicate values at each use.
Why it matters: Automatic evidence keeps valid ATM programs convenient while rejecting invalid ejections. - Security Protocol State Rules: Describe the security exercise’s password, secret-reading, and logout state rules.
Why it matters: These rules show how state-indexed commands can describe an access-control protocol. - Coin Insertion Outcomes: Describe how the vending exercise makes the state after InsertCoin depend on whether the coin is accepted or rejected.
Why it matters: Result-dependent states let the vending protocol account for rejected coins.
Key terms: EjectCard, ATMState, HasCard, CardInserted, Session, Ready, auto implicit, badATM, HasCard Ready, ShellCmd
14.3 A verified guessing game: describing rules in types
This section recaps the Hangman state model and explains why enforcing game rules requires more than precisely typed game states.
- Hangman State and Completion: Describe how the earlier Hangman model represents an ongoing game and its two possible endings.
Why it matters: This recap establishes the state and outcomes that the verified game needs to represent. - State Types and Game Rules: Explain why the earlier game type does not guarantee correct play, and describe the role of a dependent GameCmd type in expressing game rules.
Why it matters: The distinction explains why a well-typed result alone is not enough to verify the game's rules.
Key terms: WordState, Finished, game, GameCmd, dependent type, game state
14.3.1 Defining an abstract game state and operations
This section defines an abstract guessing-game state, its basic operations, and the conditions for declaring a win or loss.
- Abstract Game State: Describe the NotRunning and Running states and why Running tracks remaining guesses and letters.
Why it matters: Tracking these counts lets the game state express when the game is won or lost. - Game Operations and Preconditions: Describe the four basic game operations and the conditions for declaring a win or loss.
Why it matters: These operations and preconditions capture the game’s rules independently of its implementation.
Key terms: NotRunning, Running, guesses remaining, letters still to guess, NewGame, Guess, Won, Lost, preconditions
14.3.2 Defining a type for the game state
This section defines game commands and loop types that express guessing rules and constrain valid game implementations.
- Game Commands and Interface: Describe the role of GameCmd and the commands needed to interact with a player.
Why it matters: These commands connect the game’s state and rules to player interaction. - Guess Transition Contract: Explain the precondition and postcondition of Guess.
Why it matters: The Guess type rules out guesses in an invalid state and captures how each outcome changes the game. - Distinct Word Letters: Describe how letters obtains the distinct letters of a word.
Why it matters: The game needs the different letters in a word rather than repeated occurrences. - Game Loop Rule Guarantees: Explain how GameLoop supports ongoing play and what a well-typed, total gameLoop guarantees about following the rules and ending.
Why it matters: The loop type permits repeated play while constraining implementations to the stated game rules.
Key terms: GameCmd, GameState, Pure, (>>=), ShowState, Guess, precondition, postcondition, S guesses, S letters
14.3.3 Implementing the game
This section implements a type-checked Hangman game loop that responds to guesses and describes valid game actions.
- Guess Result State Refinement: Trace how gameLoop uses a guess result and the type of its continuation to determine the current game state.
Why it matters: The result of a guess determines which game actions are valid next. - Continuation and Termination Conditions: Explain when gameLoop can continue and how it ends after a win or loss.
Why it matters: The loop’s state requirements ensure it continues only while play is possible and exits in a permitted state. - Game Description and Execution: Distinguish the gameLoop description from what is needed to run the game.
Why it matters: A valid description of a game is not yet an executable implementation.
Key terms: GameLoop, Guess, GuessResult, Correct, Incorrect, Running, NotRunning, Won, ShowState, Exit
14.3.4 Defining a concrete game state
This section describes concrete game state and result representations for executing a potentially looping game.
- Abstract and concrete game states: Distinguish GameState from Game and describe how they relate.
Why it matters: The distinction connects the game's tracked state to the actual data needed to run it. - Result-dependent output state: Explain how GameResult represents a successful execution and why its output state can depend on the result.
Why it matters: The result representation makes the relationship between an operation's outcome and its new state explicit. - Fuel and execution failure: Explain why run uses Fuel and how GameResult represents running out of it.
Why it matters: Fuel gives the execution result a way to represent failure when a potentially looping run cannot continue.
Key terms: GameState, Game, abstract state, concrete game state, GameResult, outstate_fn, output state, Guess, Correct, Incorrect
14.3.5 Running the game: executing GameLoop
This section explains how to execute the verified Hangman game loop and commands while handling guesses and preserving totality.
- Game description and execution: Explain how GameCmd and GameLoop separate the game rules from their execution by runCmd and run. Describe how successful execution returns a result and updated state.
Why it matters: Separating the rules from their execution lets the types constrain valid game implementations. - Missing letters and guesses: Describe how the Guess case uses the in-progress game state to check a guessed character.
Why it matters: The missing-letter vector gives the command a concrete representation against which to check a guess. - Input validation and fuel: Explain how ReadGuess handles invalid input and why runCmd uses fuel. Describe the role of forever in the main program.
Why it matters: Fuel allows invalid-input retries while preserving the totality needed to reason about command execution.
Key terms: GameCmd, GameLoop, runCmd, run, ok, InProgress, Game, Guess, vector of missing letters, ReadGuess
14.4 Summary
Concepts explained in this chapter
- automated teller machineAn automated teller machine is a self-service banking machine used as an example domain for type-checked state changes.
- auto implicit argumentAn Idris implicit argument marked with auto, for which the compiler searches automatically for a value.
- preconditionA condition that must hold before an operation or process can be executed.
- state transitionA state transition is a change from one state of a system to another as a result of an operation.
- state monadThe state monad represents computations that read and update state while producing a result.
- type checkingType checking is the process of verifying that a program satisfies the constraints imposed by its types.
- case statementAn expression that evaluates a value and selects a result by matching it against alternatives.
- FuelAn Idris data type representing a supply of computation steps used to bound recursive execution.
- abstract stateAbstract state is a representation of system state that expresses selected properties without specifying all of its concrete information.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
