Pattern Overview

State Invariance Verification is the pattern for proving that a workflow maintains all constraints specified in the original intent.

An invariant is a property that must remain true throughout execution.

The Problem

In traditional automation, there’s no way to prove that the system maintained all constraints:

Specification: "Deduct from merchant, credit customer, send email"
Execution: "Deducted from merchant, credited customer, email failed"
Result: Silent failure—no one knows the constraint was violated

The Solution

Define invariants explicitly and verify them at each step:

Invariant 1: merchant_balance >= 0
Invariant 2: customer_balance >= 0
Invariant 3: email_sent == true

At each step, verify:

Step 1: deduct_from_merchant
  → Check: merchant_balance >= 0 ✓

Step 2: credit_customer
  → Check: customer_balance >= 0 ✓

Step 3: send_email
  → Check: email_sent == true ✓

Implementation

1. Extract Invariants from Specification

From Gherkin:

Scenario: Process refund
  Given a completed transaction
  When the customer requests a refund
  Then deduct from merchant account
  And credit customer payment method
  And send confirmation email

Invariants:

2. Define Invariant Checks

def verify_invariants(state):
    assert state.transaction.status == "completed"
    assert state.merchant.balance >= 0
    assert state.customer.balance >= 0
    assert state.email.sent == True
    return True

3. Execute with Verification

def execute_refund(transaction):
    state = initial_state(transaction)
    
    # Step 1
    state = deduct_from_merchant(state)
    verify_invariants(state)  # Fail fast if violated
    
    # Step 2
    state = credit_customer(state)
    verify_invariants(state)
    
    # Step 3
    state = send_email(state)
    verify_invariants(state)
    
    return state

Why This Matters

Without Verification

With Verification