Inverting the Control Hierarchy: The LLM is Never the Orchestrator
Blockstate (pip install blockstate) replaces probabilistic ReAct loops with a Deterministic Python Pushdown Statechart Engine, a Declarative Control Grammar (DCG), physical per-stage tool containment, and a first-class as_tool() Transactional Compliance Execution Enclave for regulated industries (EU AI Act, UK FCA SYSC 13.7, HIPAA, SOC 2).
TaskStack manipulation, and MappingProxyType tool dispatch lookup.≤ 50ms; end-to-end template / ChoicePayload turns < 120ms.≤ 40MB core resident RAM footprint.≥ 90% branch) on core, compiler, and security + Port Contract Suites.- Global Tool Bag Exposure: Every tool exists in the model's prompt and dispatcher on every turn; prompt injection can trigger unauthorised payouts or account mutations.
- Rice's Theorem & Unverifiable Flow: Arbitrary Python reflection and free-text LLM reasoning make it mathematically undecidable to prove that KYC always precedes disbursement.
- The Enterprise Island Trap: Demanding that enterprises rip-and-replace existing LangGraph, Semantic Kernel, or Bedrock estates blocks adoption.
- PII Leakage & Mutable Logs: Raw postcodes, NHS numbers, and card details enter commercial LLM prompts and un-chained JSON logs.
- Single-Owner State Mutation (
AD-2): OnlyStatechartEngine.commit_turn()mutates state; guards and tools receive frozenReadOnlySessionViewsnapshots. - Zero-Trust Tool Gating (
AD-3): Unlisted tools are physically absent from both the JSON schema and the turn's frozenMappingProxyTypedispatch table. - Declarative Control Grammar & AST Compiler (
AD-4):blockstate verifyrejects dynamic reflection ([Blockstate E014]) and proves Lengauer-Tarjan dominators in< 50ms. - Transactional Enclave & Sliced v1 Storage (
AD-9,AD-10): Plug into LangGraph viaas_tool()with v1StorageBackendSPI (In-Memory, SQLite WAL, PostgreSQL).
Hexagonal Core Isolation, StorageBackend SPI & PEP 621 Extras
The Pure Domain Kernel (blockstate.core, blockstate.compiler, blockstate.security) depends strictly on Python 3.12+ stdlib, pydantic, and cryptography. Version 1 slices persistence to three canonical backends behind the async StorageBackend SPI (In-Memory, SQLite WAL, PostgreSQL), deferring Redis, MS SQL Server, and DynamoDB to v1.2+.
CI runs uv run lint-imports on every push. Any import from blockstate.adapters inside blockstate.core, compiler, or security fails the build immediately.
v1 ships 3 focused backends: In-Memory (CI/tests), Local SQLite with WAL mode (PRAGMA journal_mode=WAL), and PostgreSQL (async SQLAlchemy + asyncpg). Redis, MS SQL Server, and DynamoDB are deferred to v1.2+ via the StorageBackend SPI.
SessionCheckpoint carries a mandatory schema_version: int and CAS revision_id: int, running pure SchemaUpcaster migrations on load so active sessions survive deployments.
Two-Pass Turn Loop, TaskStack Digressions & as_tool() Enclave
Each utterance traverses a three-stage pipeline: fast non-autoregressive extraction (Pass 1), synchronous Python statechart resolution (≤ 5ms), and scoped rendering (Pass 2)—exposed to LangGraph, Semantic Kernel, and AutoGen as a single transactional compliance enclave tool.
- System-1 ONNX / ModernBERT: Local CPU/GPU inference offloaded via
asyncio.to_threadachieves p95≤ 50ms(withtokenizers). - Scoped Δ Target: Pass 1 receives only the unhydrated leaf paths (
Δ = Required \ Hydrated) of the activePartialSlotModel. - Refusal Short-Circuit (
FR-3): Upstream safety refusals route immediately toon_refusalwithout burning ordinary retries.
- Recursive
PartialSlotModel(AD-5): Nested Pydantic models validate supplied fields per turn and lock valid leaf paths inTaskFrame.locked_slots. - Pushdown Digressions (
FR-8/9): Off-topic allowed intents push a childTaskFrame(max depth6) with read-only parent slot isolation (allow_slot_overrides=False). - Fail-Safe Counter-Metric (
SM-C1): Unmapped intents trigger deterministic clarification or escalation—never probabilistic guessing.
- Defeating the Enterprise Island Trap: Keep existing LangGraph / Semantic Kernel / AutoGen conversational routers intact.
- Transactional Enclave Tool: Bind any verified Blockstate statechart as a single tool via
from blockstate.adapters.langchain import as_tool. - Typed Wire Union: Returns
BlockstateTurnYield,BlockstateTurnAborted, orBlockstateTurnComplete[T].
Turn 1 [Stage: intake_claim] User supplies policy_number="POL-884120", city="Manchester"
├─► Locked Leaf Paths: {policy_number, location.city}
└─► Remaining Delta (Δ): {location.street, location.postcode, estimated_damage_gbp}
Turn 2 [Digression Classified] User asks: "Wait, will claiming for a bumper hurt my no-claims bonus?"
├─► TaskStack.push(TaskFrame(stage="ncd_policy_faq", tools=[query_policy_handbook_rag]))
├─► Parent 'intake_claim' slots frozen in read-only isolation (UnauthorisedMutationError)
└─► FAQ answered -> Transition.pop_frame() pops child frame
Turn 3 [Resume: intake_claim] User supplies street="Deansgate", postcode="M1 1AG", estimated_damage_gbp=180.0
├─► Δ == ∅ -> Strict MotorClaimSlots instantiated!
└─► Pure Python guard (180.0 ≤ 250.0) -> Transition.to("tier_auto_payout")
from blockstate.adapters.langchain import as_tool
from my_regulated_workflows import MortgageOriginationEnclave
# Expose the entire formal statechart as a single validated tool to LangGraph
langgraph_agent.bind_tools([
as_tool(MortgageOriginationEnclave, name="execute_mortgage_transaction")
])
# High-level orchestrator handles open-ended Q&A; the moment regulated data
# or money moves, execution enters the deterministic Blockstate enclave.
Defeating Rice's Theorem: DCG AST Verification (blockstate verify)
By Rice's Theorem, semantic properties of arbitrary Turing-complete Python code (such as getattr(self, dynamic_state)()) are undecidable. blockstate.compiler enforces the Declarative Control Grammar (DCG)—restricting topology to @Stage, @Transition, and @Guard decorators with static state references—and proves Lengauer-Tarjan dominators in < 50ms.
Every path from entry to any disbursement rail passes through step_up_mfa_kyc. Compiler emits a signed Markdown/JSON MRM audit certificate.
Immediate dominator of faster_payments_uk shifts to select_payment_rail. Compiler prints exact counter-example path and file:line numbers.
$ blockstate check mortgage_flow.py [Blockstate E014] Dynamic transition destination detected at mortgage_flow.py:42. Transitions must reference static State definitions to enable Lengauer-Tarjan dominator verification.
Zero-Trust Tool Isolation, PIIVault & Tamper-Evident TurnLedger
Sensitive customer data is stripped at the outermost ingress boundary before Pass 1, encrypted at rest with AES-256-GCM, and detokenised solely inside whitelisted tool handlers requesting Detokenise[T].
- No Global Tool Registry: Tools are bound exclusively to
@Stage(tools=[...])definitions. - Frozen
MappingProxyType: Rebuilt fresh on every turn for the active stage on top ofTaskStack. - Least-Privilege Injection: Tool functions receive only explicitly declared
RunContext[Deps]dependencies. - Instant Lockout: Hallucinated or injected tool calls raise
SecurityViolationError, log toTurnLedger, and transition to lockout.
- Ingress Tokenisation: Replaces NINo, NHS numbers, SSNs, postcodes, cards, emails, and phones with HMAC tokens (
<VAULT:POSTCODE_01>). - Encrypted Vault Map: Cleartext mappings live only in
SessionCheckpoint.vault_mapencrypted via AES-256-GCM with AAD binding and key-rotation support. - Zero Exception Leakage: Pydantic
ValidationErrorreprs are scrubbed so raw invalid PII never appears in logs or traces.
- Synchronous Chain Commit: Computes
SHA256(RFC8785_JCS(prev_hash, prompt_hash, vaulted_input_hash, vaulted_output_hash, exposed_tools, ...))before releasing session lease. - Session-Partitioned Buffer: Preserves monotonic causal turn ordering across distributed workers.
- 10s
SIGTERMWAL Drain: Spills un-flushed records to.blockstate/wal/ledger.walon shutdown or sink backpressure.
| Protection Layer | Mechanism / Tool | What It Blocks |
|---|---|---|
| 1. Cryptographic Secret Scan | gitleaks v8.30.1 + detect-secrets v1.5.0 |
API keys (OpenAI, Anthropic, AWS), private keys, high-entropy JWTs, and database passwords in staged diffs & history. |
| 2. Staged PII Pattern Guard | blockstate-pii-guard (pre-commit hook) |
Accidental commits containing UK NINo, NHS numbers, US SSNs, Luhn-valid payment cards, or Bearer tokens in code/tests. |
| 3. Sensitive Artifact Blocker | .gitignore + block-dotenv-and-trace-artifacts |
Blocks staging of any .env* (except .env.example), .blockstate/ trace folders, *.wal, *.db, *.pem, and *.key. |
| 4. Runtime Secret Masking | BlockstateSettings(BaseSettings) + SecretStr |
Wraps all BLOCKSTATE_ DSNs, API keys, and vault keys in pydantic.SecretStr so stack traces and logs print **********. |
Enforced Multi-Tier Coverage, Port Contract Suites & Audited Licences
Pragmatic, high-water-mark unit and branch coverage paired with reusable Port Contract Suites and Hypothesis property fuzzing guarantees zero adapter integration drift across the v1 StorageBackend SPI and 100% permissive subcomponent licensing.
| Verification Layer | Scope & Target | Enforced Threshold / Contract |
|---|---|---|
| Tier 1: Kernel Unit & Boundary | core, compiler, security |
≥ 95% Line / ≥ 90% Branch Coverage (empty strings, 64KB payloads, depth=8 nesting, [Blockstate E014] DCG checks, Unicode RTL/null bytes). |
| Tier 2: Repository Coverage | All packages incl. adapters & cli |
≥ 90% Line / ≥ 85% Branch Coverage via pytest --cov=blockstate --cov-branch. |
| Port & Enclave Contract Suites | StorageBackend SPI, LedgerSink, PIIStripper, IntentClassifier, ResponseRenderer, as_tool() |
Every v1 storage adapter (In-Memory, SQLite WAL, PostgreSQL) subclasses and passes 100% of StorageBackendContractSuite on every PR. |
| Property-Based Fuzzing | Hypothesis v6.170+ (500 examples/prop) |
Fuzzes recursive PartialSlotModel hydration, DCG AST constraints, and Lengauer-Tarjan dominators against brute-force graph paths. |
| Subcomponent | Pinned Version | SPDX Licence | Scope |
|---|---|---|---|
python (CPython Stdlib) |
>=3.12,<3.15 |
PSF-2.0 |
Core Runtime |
pydantic & pydantic-settings |
>=2.14.1 / >=2.16.1 |
MIT |
Core Runtime |
cryptography |
>=50.0.2,<51.0 |
Apache-2.0 / BSD-3 |
Core Security |
typer & rich |
>=0.27.3 / >=15.0.0 |
MIT |
Core CLI |
pydantic-ai-slim / litellm |
>=2.61.0 / >=1.106.0,<1.107.0 |
MIT |
Extra: models / litellm |
onnxruntime & tokenizers |
>=1.31.0 / >=0.23.0 |
MIT / Apache-2.0 |
Extra: onnx (local) |
SQLAlchemy & aiosqlite |
>=2.1.6 / >=0.22.1 |
MIT |
v1 StorageBackend Extras: sql, sqlite (WAL) |
asyncpg, aioboto3, opentelemetry-sdk |
>=0.32.0 / >=15.5.0 / >=1.45.1 |
Apache-2.0 |
Extras: postgres, s3, otel |