Stateful Workflows & Human-in-the-Loop
Persist workflow state across asynchronous pauses, enforce human-in-the-loop approval gates before external side effects, and resume or halt runs cleanly in fde-03-3 with pytest and GitHub Actions.
Multi-step enterprise workflows often pause before executing external writes, carrier dispatches, billing adjustments, or account changes. In-memory run state is fragile when processes restart or human reviewers take hours to respond.
In this module, you will build a stateful workflow engine with JSON state persistence, human-in-the-loop (HITL) approval gates before external side effects, clean rejection and resumption flows, idempotency-aware execution boundaries, and automated pytest and GitHub Actions verification in fde-03-3.
Enterprise Scenario: Northwind Freight
Northwind’s operations team processes freight claim credits and carrier reroutes. Read-only lookups can run automatically, while high-impact external side effects (such as issuing a credit memo or reassigning a contracted carrier) must pause in a pending-approval state, record an explicit approver decision, and resume or halt cleanly without executing unapproved writes.
What You Will Build
- Stateful workflow and approval schemas: Define strict Pydantic v2 models for
WorkflowStateandApprovalDecisionwithextra="forbid",strict=True, validated run IDs, trimmed non-blank identifiers, and cross-field state invariants. - Durable checkpointing and approval gate: Persist workflow state across pauses and resumptions, pause before external side effects when approval is required, record approved or rejected decisions as one validated state transition, and execute side effects only after a trusted approval verifier accepts the decision.
- Safer side-effect execution: Pass a stable idempotency key to the external handler, persist checkpoints atomically, and explain the limits of file-based persistence and exactly-once execution across external systems.
- Runnable HITL tests + CI workflow: Add executable
pytesttests for pause, approval, rejection, verifier failure, persistence, path validation, and handler results, then run them locally and in the supplied GitHub Actions workflow.
1. Durable State and Human-in-the-Loop Gates
- Why persist state across human approval boundaries: Human review is asynchronous. Saving run state (current step, accumulated context, pending side-effect payload, and approval status) lets a worker release compute while waiting and resume deterministically once a decision is recorded.
- Separating side-effect intent from side-effect execution: A workflow can prepare and validate a proposed action before pausing, but the side-effect handler should only run after an explicit approval record has been verified by a trusted approval boundary. If rejected, the run moves to a terminal rejected state without invoking the external action.
- Idempotency and the external-system boundary: The caller must generate a unique, stable idempotency key for each proposed action and reuse that exact key for every retry of that same action. A different proposed action must receive a different key. The receiving system must enforce the key and return the original result for duplicate requests. A local JSON file cannot guarantee exactly-once execution across a network boundary. A crash after the external system commits but before the workflow saves its result creates an uncertain outcome that must be reconciled or safely retried using the same key.
- Reviewer identity and authorization: The example accepts an
approval_verifierdependency representing a trusted service boundary. It must authenticate the reviewer, authorize that reviewer for the specific action, and validate decision integrity. Areviewer_idfield alone is only data, not proof of identity or permission. The test verifier is simulated, not production authentication. - File-backed persistence limitations: The JSON store writes a temporary file in the same directory, flushes and synchronizes that file, then atomically replaces the target to reduce partial-write corruption. This example does not synchronize the containing directory after replacement, so it should not claim guaranteed survival of every power-loss or filesystem-crash scenario. It assumes a single writer per run. Atomic replacement does not provide multi-worker locking, transactions across files, tamper-evident audit history, or distributed coordination. Production systems need transactional storage, concurrency controls, durable queues, and audited approval records.
Workflow State Lifecycle
The table below describes the intended transitions used by this teaching workflow. The Pydantic model enforces valid state shapes and cross-field invariants, but it does not independently enforce every transition between two successive states. Production systems should route all state changes through a dedicated transition function or workflow engine that checks the previous and next status, rejects changes from terminal states, and persists the transition with concurrency control.
| State | Meaning | Next allowed transition |
|---|---|---|
running | Executing steps or preparing a side effect | awaiting_approval, completed, or failed |
awaiting_approval | Paused before an external side effect | approved or rejected |
approved | A trusted approval decision is recorded; execution has not yet completed | running or failed |
rejected | Human reviewer declined the action | Terminal; no external side effect runs |
completed | The side-effect handler returned successfully and the result was persisted | Terminal |
failed | Execution raised an error or needs operational reconciliation | Terminal in this teaching example; investigate before creating a new run |
2. Step-by-Step Build Walkthrough
- Create the
fde-03-3repository and project scaffold: The following commands create the package metadata and environment template before installing the project.mkdir -p fde-03-3/src/fde_03_3 fde-03-3/tests fde-03-3/.github/workflows cd fde-03-3 git init cat > .gitignore <<'EOF' .venv/ .env __pycache__/ .pytest_cache/ *.egg-info/ dist/ build/ EOF cat > pyproject.toml <<'EOF' [build-system] requires = ["setuptools>=68"] build-backend = "setuptools.build_meta" [project] name = "fde-03-3" version = "0.1.0" description = "Stateful workflows with human-in-the-loop approval gates" requires-python = ">=3.11" dependencies = ["pydantic>=2.6,<3"] [project.optional-dependencies] dev = ["pytest>=8.0,<9"] [tool.setuptools.packages.find] where = ["src"] [tool.pytest.ini_options] testpaths = ["tests"] EOF cat > .env.example <<'EOF' # This teaching example uses local JSON storage and needs no secrets. # Add service credentials here only when integrating a real external system. EOF python3 -m venv .venv source .venv/bin/activate python -m pip install --upgrade pip python -m pip install -e ".[dev]" cp .env.example .env - Define strict Pydantic v2 schemas in
src/fde_03_3/schemas.py: Validate safe run IDs and enforce cross-field invariants so each persisted status has the fields it requires."""Strict Pydantic v2 schemas for stateful workflows and HITL gates.""" from __future__ import annotations import re from typing import Any, Literal from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator WorkflowStatus = Literal["running", "awaiting_approval", "approved", "rejected", "completed", "failed"] def _require_non_blank(value: str, field_name: str) -> str: cleaned = value.strip() if not cleaned: raise ValueError(f"{field_name} must not be blank") return cleaned def _validate_run_id(value: str) -> str: clean_id = _require_non_blank(value, "run_id") if not re.fullmatch(r"[A-Za-z0-9_-]{1,80}", clean_id): raise ValueError("run_id may contain only letters, numbers, '_' and '-' (max 80)") return clean_id class ApprovalDecision(BaseModel): """Decision data; trust is established by an injected verifier, not this model.""" model_config = ConfigDict(extra="forbid", strict=True) run_id: str = Field(min_length=1) approved: bool reviewer_id: str = Field(min_length=1) reason: str = Field(min_length=1) @field_validator("run_id") @classmethod def validate_run_id(cls, value: str) -> str: return _validate_run_id(value) @field_validator("reviewer_id", "reason") @classmethod def validate_text(cls, value: str, info) -> str: return _require_non_blank(value, info.field_name) class WorkflowState(BaseModel): """Persisted state snapshot for one workflow run.""" model_config = ConfigDict(extra="forbid", strict=True, validate_assignment=True) run_id: str = Field(min_length=1) workflow_name: str = Field(min_length=1) status: WorkflowStatus current_step: int = Field(ge=0) requires_approval_for_side_effect: bool = True idempotency_key: str = Field(min_length=1) pending_action: dict[str, Any] | None = None approval_decision: ApprovalDecision | None = None completed_steps: list[str] = Field(default_factory=list) side_effect_result: str | None = None error_message: str | None = None @field_validator("run_id") @classmethod def validate_run_id(cls, value: str) -> str: return _validate_run_id(value) @field_validator("workflow_name", "idempotency_key") @classmethod def validate_text(cls, value: str, info) -> str: return _require_non_blank(value, info.field_name) @field_validator("current_step") @classmethod def reject_bool_step(cls, value: int) -> int: if isinstance(value, bool): raise ValueError("current_step must be an integer, not bool") return value @field_validator("completed_steps") @classmethod def validate_completed_steps(cls, values: list[str]) -> list[str]: return [_require_non_blank(item, "completed_steps") for item in values] @model_validator(mode="after") def validate_state_invariants(self) -> "WorkflowState": if self.status == "awaiting_approval": if not self.requires_approval_for_side_effect: raise ValueError("awaiting_approval requires approval to be enabled") if not self.pending_action or self.approval_decision is not None: raise ValueError("awaiting_approval requires a non-empty pending_action and no decision") elif self.status == "approved": if not self.requires_approval_for_side_effect: raise ValueError("approved requires approval to be enabled") if not self.pending_action or self.approval_decision is None or not self.approval_decision.approved: raise ValueError("approved requires a non-empty pending_action and an approved decision") elif self.status == "rejected": if not self.requires_approval_for_side_effect: raise ValueError("rejected requires approval to be enabled") if self.approval_decision is None or self.approval_decision.approved: raise ValueError("rejected requires a rejected decision") elif self.status == "completed": if self.side_effect_result is None or not self.side_effect_result.strip(): raise ValueError("completed requires a non-blank side_effect_result") if self.requires_approval_for_side_effect and ( self.approval_decision is None or not self.approval_decision.approved ): raise ValueError("completed requires an approved decision") elif self.status == "failed": if self.error_message is None or not self.error_message.strip(): raise ValueError("failed requires a non-blank error_message") if self.approval_decision and self.approval_decision.run_id != self.run_id: raise ValueError("approval decision run_id must match workflow run_id") return self - Implement safe JSON storage and approval-gated execution in
src/fde_03_3/workflow.py: Validate run IDs before constructing paths, atomically replace state files, persist theapprovedcheckpoint before execution, and pass the same idempotency key to the external system on every attempt."""Stateful workflow execution with JSON checkpointing and HITL gates.""" from __future__ import annotations import os import tempfile from pathlib import Path from typing import Any, Callable from fde_03_3.schemas import ApprovalDecision, WorkflowState, _require_non_blank, _validate_run_id SideEffectHandler = Callable[[dict[str, Any], str], str] ApprovalVerifier = Callable[[ApprovalDecision, WorkflowState], bool] def _require_handler_result(result: str) -> str: """Require a non-blank string result from the external side-effect handler.""" if not isinstance(result, str) or not result.strip(): raise ValueError("Side-effect handler must return a non-blank string") return result class JsonStateStore: """Single-writer teaching store; not a multi-worker transactional database.""" def __init__(self, directory: Path) -> None: self.directory = Path(directory) self.directory.mkdir(parents=True, exist_ok=True) def _path_for(self, run_id: str) -> Path: return self.directory / f"{_validate_run_id(run_id)}.json" def save(self, state: WorkflowState) -> None: path = self._path_for(state.run_id) payload = state.model_dump_json(indent=2) temp_path: Path | None = None try: with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=self.directory, prefix=f".{state.run_id}.", suffix=".tmp", delete=False) as temp_file: temp_path = Path(temp_file.name) temp_file.write(payload) temp_file.flush() os.fsync(temp_file.fileno()) os.replace(temp_path, path) finally: if temp_path is not None and temp_path.exists(): temp_path.unlink() def load(self, run_id: str) -> WorkflowState: path = self._path_for(run_id) if not path.exists(): raise KeyError(f"Workflow run not found: {run_id}") return WorkflowState.model_validate_json(path.read_text(encoding="utf-8")) def start_or_pause_workflow(store: JsonStateStore, run_id: str, workflow_name: str, pending_action: dict[str, Any], idempotency_key: str, requires_approval_for_side_effect: bool = True, side_effect_handler: SideEffectHandler | None = None) -> WorkflowState: """Create a run and pause before a side effect unless approval is not required.""" clean_run_id = _validate_run_id(run_id) clean_name = _require_non_blank(workflow_name, "workflow_name") clean_key = _require_non_blank(idempotency_key, "idempotency_key") if not pending_action: raise ValueError("pending_action must not be empty") try: store.load(clean_run_id) except KeyError: pass else: raise ValueError(f"Workflow run already exists: {clean_run_id}") state = WorkflowState(run_id=clean_run_id, workflow_name=clean_name, status="running", current_step=1, requires_approval_for_side_effect=requires_approval_for_side_effect, idempotency_key=clean_key, pending_action=dict(pending_action), completed_steps=["validate_request"]) if requires_approval_for_side_effect: state.status = "awaiting_approval" state.current_step = 2 store.save(state) return state if side_effect_handler is None: raise ValueError("side_effect_handler is required when approval is not required") store.save(state) try: state.side_effect_result = _require_handler_result( side_effect_handler(dict(state.pending_action), state.idempotency_key) ) state.completed_steps.append("execute_side_effect") state.current_step = 3 state.status = "completed" except Exception as exc: state.error_message = f"{type(exc).__name__}: {exc}" state.status = "failed" store.save(state) return state def apply_approval_and_resume(store: JsonStateStore, decision: ApprovalDecision, approval_verifier: ApprovalVerifier, side_effect_handler: SideEffectHandler) -> WorkflowState: """Verify, persist approval, then execute the side effect.""" state = store.load(decision.run_id) if state.status != "awaiting_approval": raise ValueError(f"Cannot apply decision in state '{state.status}'") if state.pending_action is None: raise ValueError("Cannot resume without a pending_action payload") if approval_verifier(decision, state) is not True: raise PermissionError("Approval decision was not authenticated and authorized") # validate_assignment=True checks every field assignment immediately. # Build the decision + matching status together so the model validator # never sees an invalid intermediate state. state = WorkflowState.model_validate({ **state.model_dump(), "approval_decision": decision, "status": "approved" if decision.approved else "rejected", "current_step": state.current_step + 1, }) store.save(state) if not decision.approved: return state state.status = "running" store.save(state) # Durable approval checkpoint before the external write. try: state.side_effect_result = _require_handler_result( side_effect_handler(dict(state.pending_action), state.idempotency_key) ) state.completed_steps.append("execute_side_effect") state.current_step += 1 state.status = "completed" except Exception as exc: state.error_message = f"{type(exc).__name__}: {exc}" state.status = "failed" store.save(state) return stateState-validation detail: Because
WorkflowStateenablesvalidate_assignment=True, each field assignment is checked immediately. When a transition changes multiple fields that must agree (such as adding an approval decision while moving fromawaiting_approvaltoapprovedorrejected), construct and validate the complete next state in one operation before saving it. When marking a runfailed, seterror_messagebefore changingstatus, because the failed-state invariant requires the error message.Important recovery boundary: If the worker crashes after persisting
approvedorrunning, this teaching implementation cannot automatically resume that run:apply_approval_and_resume()accepts onlyawaiting_approval. Treat strandedapprovedorrunningruns as requiring manual operational reconciliation. If the external system may already have committed the action, check its status before retrying and reuse the same idempotency key. Never create a new key or blindly repeat the write. This sample marks caught handler exceptions asfailed; crash recovery and automated reconciliation are outside its scope.Approval boundary: The
approval_verifiermust be implemented by a trusted service that verifies authenticated identity, action-specific authorization, and decision integrity. It must return the literal booleanTrueonly when every check passes;False,None, strings, and all other return values fail closed. This sample does not implement an identity provider, reviewer directory, cryptographic signature, or production approval service. Never trust a client-suppliedreviewer_idor bare boolean as proof of approval. - Add automated tests in
tests/test_workflow.py: These tests exercise the key approval, rejection, persistence, validation, and handler-result paths. The verifier is deliberately a test double; it is not production authentication.from pathlib import Path from unittest.mock import Mock from pydantic import ValidationError import pytest from fde_03_3.schemas import ApprovalDecision, WorkflowState from fde_03_3.workflow import ( JsonStateStore, apply_approval_and_resume, start_or_pause_workflow, ) def make_decision(run_id: str, approved: bool) -> ApprovalDecision: return ApprovalDecision( run_id=run_id, approved=approved, reviewer_id="reviewer-01", reason="Reviewed against the claim policy", ) def test_workflow_pauses_and_persists_before_side_effect(tmp_path: Path) -> None: store = JsonStateStore(tmp_path) handler = Mock(return_value="credit memo issued") state = start_or_pause_workflow( store, "claim-100", "freight_credit", {"claim_id": "C-100", "amount": 250}, "claim-100-credit-v1", ) assert state.status == "awaiting_approval" assert handler.call_count == 0 assert store.load("claim-100").status == "awaiting_approval" def test_approval_resumes_and_passes_stable_idempotency_key(tmp_path: Path) -> None: store = JsonStateStore(tmp_path) handler = Mock(return_value="credit memo issued") start_or_pause_workflow( store, "claim-101", "freight_credit", {"claim_id": "C-101", "amount": 250}, "claim-101-credit-v1", ) state = apply_approval_and_resume( store, make_decision("claim-101", True), approval_verifier=lambda decision, workflow: True, side_effect_handler=handler, ) assert state.status == "completed" handler.assert_called_once_with( {"claim_id": "C-101", "amount": 250}, "claim-101-credit-v1", ) assert store.load("claim-101").status == "completed" def test_rejection_does_not_call_external_handler(tmp_path: Path) -> None: store = JsonStateStore(tmp_path) handler = Mock(return_value="should not run") start_or_pause_workflow( store, "claim-102", "freight_credit", {"claim_id": "C-102", "amount": 250}, "claim-102-credit-v1", ) state = apply_approval_and_resume( store, make_decision("claim-102", False), approval_verifier=lambda decision, workflow: True, side_effect_handler=handler, ) assert state.status == "rejected" handler.assert_not_called() def test_failed_verification_blocks_execution(tmp_path: Path) -> None: store = JsonStateStore(tmp_path) handler = Mock(return_value="must not run") start_or_pause_workflow( store, "claim-103", "freight_credit", {"claim_id": "C-103", "amount": 250}, "claim-103-credit-v1", ) with pytest.raises(PermissionError): apply_approval_and_resume( store, make_decision("claim-103", True), approval_verifier=lambda decision, workflow: "yes", side_effect_handler=handler, ) handler.assert_not_called() def test_blank_handler_result_marks_run_failed(tmp_path: Path) -> None: store = JsonStateStore(tmp_path) state = start_or_pause_workflow( store, "claim-104", "freight_credit", {"claim_id": "C-104", "amount": 250}, "claim-104-credit-v1", ) state = apply_approval_and_resume( store, make_decision("claim-104", True), approval_verifier=lambda decision, workflow: True, side_effect_handler=lambda action, key: " ", ) assert state.status == "failed" assert "non-blank string" in state.error_message def test_duplicate_run_id_is_rejected(tmp_path: Path) -> None: store = JsonStateStore(tmp_path) args = ( store, "claim-105", "freight_credit", {"claim_id": "C-105", "amount": 250}, "claim-105-credit-v1", ) start_or_pause_workflow(*args) with pytest.raises(ValueError, match="already exists"): start_or_pause_workflow(*args) def test_unsafe_run_id_is_rejected(tmp_path: Path) -> None: store = JsonStateStore(tmp_path) with pytest.raises(ValueError): store.load("../outside") def test_approval_required_workflow_cannot_complete_without_approval() -> None: with pytest.raises(ValidationError): WorkflowState( run_id="claim-106", workflow_name="freight_credit", status="completed", current_step=3, requires_approval_for_side_effect=True, idempotency_key="claim-106-credit-v1", pending_action={"claim_id": "C-106"}, side_effect_result="credit memo issued", ) - Configure GitHub Actions in
.github/workflows/tests.yml: This workflow installs the package and development dependencies, then runs the test suite on pushes and pull requests.name: Python tests on: push: pull_request: jobs: test: runs-on: ubuntu-latest steps: - name: Check out repository uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.11" - name: Install package and test dependencies run: | python -m pip install --upgrade pip python -m pip install -e ".[dev]" - name: Run tests run: python -m pytest -v - Run tests and commit to Git:
python -m pytest -v git status git add . git commit -m "Complete FDE module 03.3"
3. Common Pitfalls and Operational Hygiene
- Allowing path traversal through run IDs: Validate run IDs against a strict allowlist before using them in filenames. Do not accept slashes, dots, or path separators.
- Executing external side effects before persisting the approval checkpoint: Persist the approved decision before calling the external handler. Pass a stable idempotency key and require the receiving system to enforce it.
- Assuming a local save makes a remote write exactly-once: A crash can occur after the external system commits but before the local completion state is saved. Reconcile uncertain outcomes and reuse the same idempotency key; do not generate a fresh key for a retry of the same action. Give every different proposed action its own unique key.
- Trusting reviewer metadata without verification: A reviewer ID is not authentication. Verify identity, action-specific authorization, and decision integrity through a trusted approval service.
- Treating atomic file replacement as complete durability or concurrency control: The temporary-file and atomic-replace pattern reduces partial-file corruption, but this example does not synchronize the containing directory after replacement and remains single-writer. Do not treat it as a guarantee against every power-loss scenario. Use database transactions, optimistic version checks or locks, and durable orchestration for concurrent production workers.
- Confusing state validation with transition enforcement: Pydantic validates each state snapshot, but does not by itself prevent every illegal transition from a prior state. Route production transitions through a dedicated transition function or workflow engine. Rejected, completed, and failed runs are terminal in this exercise. Stranded
approvedorrunningruns cannot be resumed automatically by this sample and require manual reconciliation.
4. Completion Criteria
WorkflowStateandApprovalDecisionvalidate inputs strictly, reject unsafe run IDs and boolean step counts, and enforce cross-field state invariants.JsonStateStorevalidates run IDs and uses temporary-file plus atomic-replace writes to reduce partial-file corruption; its lack of directory synchronization, single-writer assumption, and non-transactional limitations are documented.start_or_pause_workflowpersists the approval pause before returning, whileapply_approval_and_resumeverifies and persists approval before executing the external action, and records rejection without invoking the handler.- The external handler receives the supplied stable idempotency key for the proposed action. The included eight tests verify that approval pauses before execution, approved runs resume and pass the key to the handler, rejected runs do not execute the handler, non-
Trueverifier results block execution, blank handler results fail the run, duplicate run IDs are rejected, unsafe run IDs are rejected, and approval-required runs cannot be constructed as completed without an approved decision. - Run
python -m pytest -vlocally and confirm all eight tests pass. Push the repository to GitHub and verify that the supplied GitHub Actions workflow succeeds before marking the module complete. The included tests are a focused teaching suite, not exhaustive coverage of every invariant or production failure mode.
Build this
In fde-03-3, implement strict Pydantic v2 models in src/fde_03_3/schemas.py (WorkflowState and ApprovalDecision) and durable pause/resume/approval logic in src/fde_03_3/workflow.py (JsonStateStore, start_or_pause_workflow, and apply_approval_and_resume).
- Pause runs in
awaiting_approvalbefore executing external side effects when approval is required, persist state across store reloads, recordApprovalDecisiondetails, execute the side effect only when approved, and move torejectedwithout executing the side effect when rejected. - Reject invalid state transitions (such as resuming a
rejectedorcompletedrun), empty payloads, blank strings, and boolean step counts. - Add unit tests in
tests/test_workflow.pycovering pause/approve/resume across store reloads, rejection without side effects, invalid transitions, and schema validation, then runpython -m pytest -vand pushfde-03-3(including.github/workflows/pytest.yml) to GitHub.
Test your understanding
- Which actions in an enterprise workflow should require explicit human approval before execution?
- Why is persisting workflow state to durable storage essential when a workflow pauses for human review?
- What should happen when a human reviewer rejects a paused side effect, and why must rejected runs not silently execute the action?
- What production safeguards (beyond a basic JSON state store) are needed for external side effects and human approvals?
Reveal self-review answers (attempt the questions first)
- Actions requiring human approval: Require explicit approval before irreversible, high-cost, customer-facing, or externally visible actions such as issuing credits or refunds, dispatching or rerouting shipments, modifying production records, or sending external communications.
- Durable state persistence: Human approvals can take minutes, hours, or days. Persisting state ensures progress, context, and pending actions survive process restarts, worker scaling, and delays without losing the run.
- Handling rejection: Transition the run to a
rejectedstate, record the reviewer and reason, and skip the side-effect handler so unauthorized or declined actions never take effect. - Production safeguards: Add idempotency keys to prevent duplicate side effects on retries, authenticated and authorized reviewer identities, audit logs, concurrency locking, and approval timeouts or escalations.
Questions or notes on this module?