Deterministic Compliance Enclave · PEP 695 & Pydantic v2
Deterministic Statecharts, Compile-Time Dominator Proofs & Zero-Trust Tool Gating for Regulated Python AI
Give your Python runtime 100% ownership of workflow transitions, guard conditions, and stage-scoped memory dispatch tables. Restrict Large Language Models strictly to bounded slot extraction (Pass 1) and response rendering (Pass 2).
FIG 1.0A // WESTINGHOUSE MECHANICAL INTERLOCKING PRINCIPLE:
On physical railways, electrical track circuits divide the line into discrete block sections, and mechanical tappet interlocking prevents a signalman from clearing a lever into an unverified block. Blockstate brings this formal discipline to enterprise AI: blockstate verify proves mathematically via the Lengauer-Tarjan algorithm in under 50ms that mandatory compliance checkpoints (such as step_up_mfa_kyc) strictly dominate privileged actions (such as faster_payments_uk) before code reaches production.
Eliminate combinatorial graph edge spaghetti with declarative @Stage and @Transition decorators, Pydantic v2 slot hydration, and pushdown TaskStack digression handling. Mounts directly into LangGraph or Semantic Kernel via as_tool().
Core Python statechart runtime overhead per turn above model execution
SPEC 02 // LENGAUER-TARJAN CI
<50ms
Compile-time dominator tree verification across all primary and fallback edges
SPEC 03 // ENCLAVE FOOTPRINT
≤40MB
Core runtime memory footprint with zero database or cloud SDK bloat
SPEC 04 // CYCLONEDX SBOM
0%
Copyleft (GPL/AGPL/LGPL) dependency risk across audited runtime tree
FIG 1.1 // MECHANICAL INTERLOCKING SIGNAL BOX & STATECHART BENCHWESTINGHOUSE 4-LEVER FRAME · AI GOVERNOR & TRUST BUILDER TELEMETRY
Interactive Hardware-Boundary Verification Bench
Throw the Signal Levers to Test Dominator Proofs, Memory Locks & Pushdown Detours
Pull any of the four colour-coded mechanical levers below or switch scenario tabs to test how Blockstate blocks unverified fast-track edges at build time, halts prompt-injected tool calls at the Python MappingProxyType memory boundary, and absorbs customer FAQ tangents on the LIFO TaskStack.
TAPPET INTERLOCK: PROVEN (step_up_mfa_kyc dom ALL RAILS)
OPERATE SIGNAL LEVERS: Click any lever unit to throw its mechanical tappet and update the live statechart & Governor telemetry.CHROMATICS: [BLUE] FACING-POINT LOCK · [RED] DANGER / BYPASS · [OCHRE] CAUTION / SIDING
The 3 Failure Modes of Probabilistic Orchestration
Passing a global tool catalogue to a ReAct loop or unconstrained graph runner conflates conversational comprehension with workflow control flow. In banking, insurance, healthcare, and telecommunications, this creates three structural blockers.
FAILURE MODE 01 · OWASP LLM01 & LLM06
Unconstrained Tool Agency
Standard agent frameworks bind every registered tool into the prompt context and rely on system prompt instructions to prevent premature calls (for example, telling the LLM to verify identity before calling authorise_bacs_payout). Adversarial prompt injection bypasses prompt wording because the function pointer remains live in the active execution scope.
Real customers ask clarifying questions mid-form (such as asking whether a windscreen claim affects their no-claims discount right after giving their postcode). Supporting tangents across N collection steps and M FAQ handlers in directed graph runners requires wiring O(N × M) manual edges, frequently overwriting or dropping previously validated fields.
Blockstate Fix: LIFO TaskStack pushdown automaton reducing complexity to O(N + M).
FAILURE MODE 03 · RICE'S THEOREM & MRM VETO
Regulatory Audit Vetoes
Under UK FCA SYSC 13.7, PRA SS1/23, EU AI Act Articles 12 & 14, and HIPAA, Model Risk Management (MRM) committees cannot sign off on a "97% empirical eval pass rate". Furthermore, under Rice's Theorem, unconstrained Python reflection (getattr) is mathematically undecidable by static analysis.
FIG 1.3 // PATENT SPECIFICATION SUBSYSTEM INDEXUKIPO PRIORITY FILING 28 OCT 2026 · CLAIMS 1 TO 15
UK Patent Pending Architecture (Claims 1 to 15)
The 7 Patented Core Subsystems of Blockstate
Every subsystem is implemented in strict PEP 695 typed Python 3.12+ and verified by automated interface contract suites and Hypothesis property-based fuzzers.
1. Declarative Control Grammar (DCG) & Zero-Execution AST Compiler
Under Rice's Theorem, unconstrained dynamic dispatch makes static graph verification undecidable. Blockstate parses agent source files via ast.parse without executing bytecode. It enforces static @Stage, @Transition, and @Guard declarations and immediately halts the build with DynamicTransitionError (BLK-AST-014 / [Blockstate E014]) if a stage calls getattr, passes a non-literal variable to Transition.to(), or embeds a transition directive inside a Pydantic @field_validator.
@Stage(name="verify_identity", initial=True, max_turns=3)
@Guard(requires=("is_authenticated",))
@Transition(targets=("collect_refund", "security_lockout"))
async def verify_identity(self) -> Transition["collect_refund" | "security_lockout"]:
# Static string literal targets pass ast.parse verification in <25ms:if not self.session.get("is_authenticated", False):
return Transition.to("security_lockout")
return Transition.to("collect_refund")
# Any dynamic reflection or computed target halts CI immediately:[Blockstate E014] Dynamic transition destination detected at mortgage_flow.py:42.Transitions must reference static State definitions to enable Lengauer-Tarjan dominator verification.
2. Compile-Time Lengauer-Tarjan Dominator Tree Precursor Verification
During CI/CD, blockstate verify constructs the directed Control Flow Graph (including deterministic fallback edges on_refusal, on_max_turns_exceeded, on_breach, and on_security_violation), verifies BFS reachability from initial_stage, and computes depth-first numbering (dfnum), semidominators (sdom), and immediate dominators (idom) via LengauerTarjanSolver using path compression (_link, _eval, _compress). On violation, it synthesises the exact breadth-first counterexample bypass path in G \ {u}.
CI Gate: blockstate verify & blockstate exportDOMINANCE PROVEN
Upon entering any @Stage, ToolGatekeeper constructs an ephemeral, read-only types.MappingProxyType dispatch table and outbound LLM tool schema restricted exclusively to stage_def.tools. Context is injected via a deep-frozen ReadOnlySessionView, parameters annotated with Detokenise[T] are unwrapped in volatile RAM solely for the duration of that call, and string or mapping tool outputs are automatically re-sanitised through PIIVault.
Hardware-Boundary Tool IsolationBLK-SEC-001 ARMED
@Stage(
name="ncd_policy_faq",
tools=["query_policy_handbook_rag"], # Only this function exists in MappingProxyType
max_turns=2,
)
async def ncd_policy_faq(self, query: str) -> Transition[None]:
# If prompt injection attempts self.tools.authorise_bacs_payout(...):# Raises SecurityViolationError (BLK-SEC-001) before function lookup!
excerpt = await self.tools.query_policy_handbook_rag(topic=query)
return Transition.pop_frame(message=f"Policy Handbook: {excerpt}")
Blockstate separates persistent SessionState from a bounded Last-In, First-Out (LIFO) TaskStack of TaskFrame contexts (raising StackOverflowErrorBLK-SEC-003 if depth exceeds the configured circuit breaker). When a user digresses to an allowed FAQ stage, Blockstate pushes a child frame, locks parent dot-separated slot paths against mutation (UnauthorisedMutationErrorBLK-SEC-002 when allow_slot_overrides=False), answers the query, and executes Transition.pop_frame() to resume parent slot collection.
O(N + M) Pushdown Digression HandlingPARENT SLOTS LOCKED
Stages bind to standard Pydantic v2 models up to max_nesting_depth (BLK-CFG-002). Blockstate synthesises a recursive PartialSlotModel using the singleton UNSET sentinel. Candidate values are validated at individual flattened leaf paths, preserving valid sibling leaves when one leaf fails (BLK-VAL-002). Custom @field_validator methods unwrap Vaulted[T] tokens in volatile memory via wrap_detokenising_validator, immediately re-bind tokens, scrub PII from validation exceptions, and route immediately to on_breach on DisqualifyingBreachError (BLK-VAL-003).
Ingress utterances are scanned by deterministic checksum detectors (including Luhn modulo-10 for payment cards and NHS Modulus-11 check-digit validation, plus UK National Insurance numbers and postcodes) with longest-span and priority-rank overlap resolution that protects existing <VAULT:...> tokens. Entities are deduplicated per session via keyed HMAC-SHA256 into <VAULT:CATEGORY_NN> tokens, and the token map is encrypted with AES-256-GCM using a 12-byte random nonce and colon-separated session_id:schema_version:revision_id Associated Authenticated Data (AAD).
Selective Volatile Unwrapping: Detokenise[T]ZERO RAW PII IN LOGS
from blockstate import Detokenise
# LLM prompts, SessionState, and TurnLedger only ever see "<VAULT:NHS_NUMBER_01>"async def lookup_patient_ehr_record(
nhs_number: Detokenise[str],
postcode: Detokenise[str],
) -> dict[str, str]:
# Unwrapped to plaintext "485 777 3456" solely inside this volatile call framereturn {"registration_status": "ACTIVE", "gp_practice_code": "Y00124"}
Every turn generates a 12-field TurnLedgerRecord chained from a genesis hash of 64 zeroes ("0" * 64), serialised via RFC 8785 JSON Canonicalisation Scheme (JCS) UTF-8 and hashed with SHA-256. Records stream through a SessionPartitionedRingBuffer with os.fsync spill to .blockstate/wal/ledger.wal and causal startup replay (recover_wal). Distributed state persists via the async StorageBackend SPI (In-Memory, SQLite WAL, PostgreSQL) with fenced LeaseHandle tokens (BLK-CON-409), SessionLeaseHeartbeat renewal, Compare-And-Swap revision checks (BLK-STO-002), and sequential SchemaUpcaster migrations.
Mount Inside LangGraph, Semantic Kernel, AutoGen or AWS Bedrock via as_tool()
Keep your existing high-level conversational router for open-domain search and concierge dialogue. When a customer triggers a regulated transaction, invoke Blockstate as a deterministic compliance enclave returning a frozen discriminated union.
from blockstate.adapters.langchain import as_tool
from my_insurance_agent import MotorInsuranceClaimAgent
# Wrap the verified statechart as a standard tool for LangGraph
claim_enclave_tool = as_tool(
agent_cls=MotorInsuranceClaimAgent,
name="motor_claim_enclave",
description="Executes FNOL motor insurance claims under FCA compliance.",
)
langgraph_router.bind_tools([claim_enclave_tool])
2. Typed Wire Boundary Discriminated Union (Claim 15)PEP 695 Match
from blockstate import (
BlockstateTurnYield,
BlockstateTurnComplete,
BlockstateTurnAborted,
)
outcome = await claim_agent.run_as_subflow(
session_id=session_id,
user_message=user_utterance,
initial_context={"is_authenticated": True},
)
match outcome:
case BlockstateTurnYield(message=prompt_msg, missing_slots=delta):
return prompt_msg
case BlockstateTurnComplete(result=claim, ledger_head_hash=h):
return f"Approved (Audit SHA-256: {h[:12]})"case BlockstateTurnAborted(error_code=code, reason=reason):
return f"[{code}] Escalating to specialist: {reason}"
How Blockstate Compares Across Critical Compliance Dimensions
Compare Blockstate's compile-time verification and hardware-boundary memory gating with general-purpose orchestrators and DSL guardrails. For deep code-level comparisons, visit the Technical Comparison Hub.
SCHEDULE 2.0 // COMMERCIAL PRODUCTION & PATENT LICENSINGUK PATENTS ACT 1977 S.62(1) · ZERO ESTOPPEL SCHEDULE
Source-Available Dual Licence · Zero Estoppel Ambiguity
Transparent Dual Licensing & Commercial Production Tiers
Blockstate is distributed under the Blockstate Source-Available & Commercial Dual Licence (v1.0) and is protected by a pending United Kingdom Patent Application. Developers evaluate and run CI verification free of charge; regulated production deployments license the runtime and patent portfolio annually. Machine-readable specification: /pricing.md.
LICENCE SECTION 1 · EVALUATION
Community, Dev & 90-Day Evaluation Tier
£0
Free under conditional copyright & evaluation covenant
✔Local developer prototyping, benchmarking, and academic research
1. Does Blockstate replace LangGraph, Microsoft Semantic Kernel, AutoGen, or AWS Bedrock?
No. Blockstate is architected to avoid the Enterprise Island Trap. Your high-level orchestrator (LangGraph, Semantic Kernel, AutoGen, or AWS Bedrock) continues to manage open-ended conversational routing and RAG search. Whenever a customer enters a regulated workflow (such as mortgage origination, wire transfers, or FNOL insurance claims), the outer orchestrator invokes Blockstate via our 1-line as_tool() adapter. Blockstate executes the verified statechart enclave and returns a strictly typed discriminated union (BlockstateTurnYield | BlockstateTurnComplete | BlockstateTurnAborted).
2. Why not write a standard Python if/else or Enum state machine?
Hand-rolled Python if/else trees lack five critical compliance primitives that you would otherwise have to build and maintain from scratch: (1) zero-execution static AST extraction and Lengauer-Tarjan dominator verification in CI/CD (blockstate verify), (2) automatic recursive PartialSlotModel Δ-hydration with per-leaf locking across multi-turn conversations, (3) a LIFO TaskStack pushdown automaton for mid-flow customer digressions, (4) stage-scoped types.MappingProxyType memory tool gating, and (5) an RFC 8785 JCS SHA-256 hash-chained TurnLedger with WAL crash recovery.
3. Why does Blockstate reject getattr() and dynamic transition targets with [Blockstate E014]?
By Rice's Theorem, any non-trivial semantic property of an unconstrained Turing-complete program is mathematically undecidable by static analysis. If an agent class computes transition targets dynamically at runtime or dispatches stages via getattr(self, state_name)(), no compiler can prove before deployment that step_up_mfa_kyc dominates faster_payments_uk. Enforcing static string literals in the Declarative Control Grammar via ast.parse makes Lengauer-Tarjan dominator tree verification 100% sound and decidable in under 50ms.
4. Does Pass 1 slot extraction still rely on a probabilistic language model?
Pass 1 uses a fast classifier or structured Small Language Model (such as local ONNX ModernBERT or a constrained Pydantic-AI extractor) strictly to parse untrusted user text into candidate slot values. Crucially, the Pass 1 model has zero authority to invoke tools, mutate locked slots, or choose stage transitions. Every candidate leaf value must pass deterministic Pydantic v2 constraints, custom @field_validator methods, and pure Python @Guard predicates before the Python statechart engine executes a transition.
5. How does PIIVault allow backend tools to use real NHS numbers or postcodes without exposing them to the LLM?
At ingress, PIIVault.sanitise() detects sensitive entities using Luhn modulo-10 and NHS Modulus-11 check-digit algorithms, replacing them with session-consistent HMAC-SHA256 tokens (such as <VAULT:NHS_NUMBER_01>) and encrypting the mapping with AES-256-GCM bound to session_id:schema_version:revision_id AAD. The LLM and TurnLedger only ever see the opaque token. When a whitelisted backend tool requires the plaintext identifier, the developer annotates that parameter with Detokenise[str]. ToolGatekeeper unwraps the value inside volatile RAM solely for that function call and automatically re-sanitises the tool's return value.
6. Which database backends are supported in Version 1?
Version 1 ships with three canonical asynchronous implementations of the StorageBackend Service Provider Interface (src/blockstate/ports/storage.py), all verified against the identical StorageBackendContractSuite: (1) InMemoryStorageBackend for hermetic unit testing and CI, (2) SQLiteStorageBackend with Write-Ahead Logging (PRAGMA journal_mode=WAL via aiosqlite) for local development and single-node edge deployments, and (3) PostgresStorageBackend (via SQLAlchemy[asyncio] and asyncpg) for cloud production deployments with fenced leases (BLK-CON-409) and optimistic Compare-And-Swap (BLK-STO-002). Redis, Microsoft SQL Server, and AWS DynamoDB are scheduled for v1.2+ via the pluggable SPI.
7. Why is Blockstate Source-Available Dual Licensed and UK Patent Pending rather than MIT?
Blockstate is built for regulated financial, insurance, healthcare, and telecommunications institutions that require indemnified commercial support, verifiable regulatory compliance artefacts, and long-term R&D sustainability. Our Source-Available Dual Licence (LICENSE v1.0) gives individual developers, researchers, open-source CI pipelines, and enterprise teams evaluating in staging for up to 90 days full source inspection and free execution (£0 under Section 1), while requiring a Commercial Production and Patent Licence (Section 2) when deployed in live commercial production or managed services.
8. How can our Model Risk Management (MRM) or CISO team verify regulatory compliance?
Visit our MRM & CISO Governance Portal or download the MRM & CISO Compliance Approval Pack, which maps Blockstate's compile-time and runtime controls clause-by-clause to UK FCA SYSC 13.7, FCA Consumer Duty (PS22/9), Bank of England PRA SS1/23, EU AI Act Articles 9, 12, 14 & 15, HIPAA Safe Harbor (45 CFR § 164.514), UK/EU GDPR Articles 25 & 32, and the OWASP Top 10 for LLM Applications 2025.
Zero-Cookie Local Attribution Tracker (window.BlockstateTelemetry):Source: direct | Logged Micro-Conversions: 0