BLOCKSTATE
Enterprise Architecture Spine Deck v1.0 · Deterministic Agent Governance & Transactional Compliance Enclave
Slide 1 of 6 · Architectural Vision & Non-Functional Envelope

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).

Core Turn OverheadNFR-10.1
≤ 5ms
Pure Python guard evaluation, TaskStack manipulation, and MappingProxyType tool dispatch lookup.
Pass 1 & Choice SLASM-4
< 100ms
System-1 local ONNX p95 extraction ≤ 50ms; end-to-end template / ChoicePayload turns < 120ms.
Memory & ThroughputNFR-10.1
≥ 250 TPS
Concurrent turns/sec per 2 vCPU async worker with ≤ 40MB core resident RAM footprint.
Enforced CoverageAD-11
≥ 95%
Line coverage (≥ 90% branch) on core, compiler, and security + Port Contract Suites.
Why Legacy ReAct Loops Fail Regulated AuditsProbabilistic Risk
  • 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.
The Blockstate Architectural Guarantees (AD-1 to AD-14)Deterministic Assurance
  • Single-Owner State Mutation (AD-2): Only StatechartEngine.commit_turn() mutates state; guards and tools receive frozen ReadOnlySessionView snapshots.
  • Zero-Trust Tool Gating (AD-3): Unlisted tools are physically absent from both the JSON schema and the turn's frozen MappingProxyType dispatch table.
  • Declarative Control Grammar & AST Compiler (AD-4): blockstate verify rejects dynamic reflection ([Blockstate E014]) and proves Lengauer-Tarjan dominators in < 50ms.
  • Transactional Enclave & Sliced v1 Storage (AD-9, AD-10): Plug into LangGraph via as_tool() with v1 StorageBackend SPI (In-Memory, SQLite WAL, PostgreSQL).
Slide 2 of 6 · AD-1 & AD-9 · Hexagonal Architecture & Version 1 Storage Slicing

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+.

OUTER RING: blockstate.adapters.* & blockstate.cli (PEP 621 Optional Extras) adapters.storage (v1) In-Memory · SQLite (WAL) PostgreSQL (SQLAlchemy Async) adapters.models ONNX System-1 (<50ms) PydanticAI · LiteLLM (<1.107) adapters.ledger Session Ring Buffer + WAL PostgresSink · S3 WORM Sink blockstate.cli blockstate check / verify blockstate trace / export adapters.telemetry OpenTelemetry GenAI 1.30 .blockstate/traces.jsonl adapters.langchain as_tool() Enclave Adapter LangGraph / SK / AutoGen PROTOCOL & SPI RING: blockstate.ports (typing.Protocol) StorageBackend SPI · IntentClassifier · ResponseRenderer · LedgerSink · PIIStripper PURE DOMAIN KERNEL (Stdlib + Pydantic + Cryptography ONLY) blockstate.core StatechartEngine · TaskStack · PartialSlotModel · ToolGatekeeper blockstate.compiler DCG AST · [Blockstate E014] blockstate.security PIIVault · AES-256-GCM blockstate.testing.contracts StorageBackendContractSuite, Enclave & Hypothesis Fuzzers
import-linter EnforcementAD-1

CI runs uv run lint-imports on every push. Any import from blockstate.adapters inside blockstate.core, compiler, or security fails the build immediately.

Version 1 Storage SlicingAD-9 · StorageBackend SPI

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.

Rolling-Deploy UpcastersAD-9

SessionCheckpoint carries a mandatory schema_version: int and CAS revision_id: int, running pure SchemaUpcaster migrations on load so active sessions survive deployments.

Slide 3 of 6 · AD-2, AD-5, AD-6, AD-10 · Runtime Pipeline & Enclave Adapter

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.

1. Pass 1: Fast Extraction< 100ms Budget
  • System-1 ONNX / ModernBERT: Local CPU/GPU inference offloaded via asyncio.to_thread achieves p95 ≤ 50ms (with tokenizers).
  • Scoped Δ Target: Pass 1 receives only the unhydrated leaf paths (Δ = Required \ Hydrated) of the active PartialSlotModel.
  • Refusal Short-Circuit (FR-3): Upstream safety refusals route immediately to on_refusal without burning ordinary retries.
2. Core Engine & TaskStack≤ 5ms Pure Python
  • Recursive PartialSlotModel (AD-5): Nested Pydantic models validate supplied fields per turn and lock valid leaf paths in TaskFrame.locked_slots.
  • Pushdown Digressions (FR-8/9): Off-topic allowed intents push a child TaskFrame (max depth 6) 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.
3. Outer Enclave EntrypointAD-10 · as_tool()
  • 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, or BlockstateTurnComplete[T].
TaskStack Pushdown Automata vs Traditional Graph EdgesO(N + M) vs O(N × M)
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")
LangGraph Transactional Compliance Enclave IntegrationAD-10 · AD-11
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.
Slide 4 of 6 · AD-4 · Declarative Control Grammar (DCG) & Lengauer-Tarjan Dominator Verification

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.

Compliant Topology: Dominance ProvenExit Code 0
select_payment_rail step_up_mfa_kyc (DOM) faster_payments_uk sepa_euro_transfer swift_international

Every path from entry to any disbursement rail passes through step_up_mfa_kyc. Compiler emits a signed Markdown/JSON MRM audit certificate.

PR Bypass Violation: Blocked in CIExit Code 1 (BLK-AST-002)
select_payment_rail VIP Bypass (<£10) step_up_mfa_kyc faster_payments_uk sepa_euro_transfer swift_international

Immediate dominator of faster_payments_uk shifts to select_payment_rail. Compiler prints exact counter-example path and file:line numbers.

Declarative Control Grammar (DCG) Static Reflection Rejection[Blockstate E014]
$ 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.
Slide 5 of 6 · AD-3, AD-7, AD-8, AD-13 · Security & Audit Provenance

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].

Physical Tool GatingAD-3 · BLK-SEC-001
  • 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 of TaskStack.
  • Least-Privilege Injection: Tool functions receive only explicitly declared RunContext[Deps] dependencies.
  • Instant Lockout: Hallucinated or injected tool calls raise SecurityViolationError, log to TurnLedger, and transition to lockout.
PIIVault & Detokenise[T]AD-7 · AES-256-GCM
  • 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_map encrypted via AES-256-GCM with AAD binding and key-rotation support.
  • Zero Exception Leakage: Pydantic ValidationError reprs are scrubbed so raw invalid PII never appears in logs or traces.
SHA-256 TurnLedger & WALAD-8 · EU AI Act Art. 12
  • 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 SIGTERM WAL Drain: Spills un-flushed records to .blockstate/wal/ledger.wal on shutdown or sink backpressure.
Zero-Leakage Git Hooks & SecretStr Environment Boundary (AD-13)Pre-Commit & Pre-Push Enforced
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 **********.
Slide 6 of 6 · AD-11 & AD-12 · Quality Assurance & Supply-Chain Governance

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.

Three-Tier Testing & Contract Matrix (AD-11)CI Hard Gate
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.
Audited Subcomponent Licence Manifest (AD-12)Zero Copyleft
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