Verified Semantic Compilation DOI: 10.5281/zenodo.19414309

Zero-token procedural execution for
autonomous AI agents

Semantic Harness compiles multi-turn LLM reasoning loops into deterministic, type-safe Python AST procedures. Re-execute recurring enterprise workflows in microseconds at 0 model tokens with 100% parameter accuracy.

21.2%
Token Reduction
Across mixed enterprise streams ($p = 0.005$)
0 Tokens
Warm-Path Cost
Compiled AST execution in Python REPL
80.3 µs
Sub-Millisecond Speed
>600× faster than raw inference (~9s)
100.0%
Parameter Accuracy
0 stale errors vs. 18 in traditional vector caches
The Missing Architectural Pillar

Closing the "Procedural Gap"

Every major breakthrough in LLM infrastructure has solved a distinct architectural bottleneck. Until now, no framework addressed why production agents re-reason through deterministic, identical steps every single turn.

Pillar 1
Knowledge Gap
Solved by RAG & Vector DBs
Retrieves external documents, facts, and embeddings to ground the model against hallucinations.
⚠️ Injects knowledge, but leaves computation non-deterministic.
Pillar 2
Context Length Gap
Solved by 1M+ Context Windows
Accommodates massive books and repos without buffer overflow or immediate context truncation.
⚠️ Inflates KV cache latency and drives linear token billing spikes.
Pillar 3
Domain Tone Gap
Solved by Fine-Tuning & LoRA
Adapts internal neural weights to specialize syntax, domain jargon, and organizational voice.
⚠️ Expensive to retrain; still produces probabilistic variations.
Pillar 4 (New)
The Procedural Gap
SOLVED BY SEMANTIC HARNESS
Compiles multi-turn LLM reasoning into verified, type-safe Python AST routines. Eliminates redundant LLM inference completely on recurring tasks.
✅ $0.00 token cost • Sub-microsecond dispatch • 100% parameter accuracy.
Operator Surface

Live Mission Control & Observability Console

Inspect real-time tokenomics, intelligent model routing, 4-tier memory capacities (Procedural, Semantic, Episodic, Working), and the interactive Knowledge Graph. Zero headless mystery.

Engine: semantic-harness-runtime-01 • 0-Token Fast Path Active
Cache Hit Rate
84.6%
+12.4% vs uncompiled baseline
Cost Bypassed
$1,428.40
Zero-token procedural cache hits
Tokens Bypassed
2,418,920
78.2% of total token volume
Dispatch Latency
80.3 µs
>600× faster than frontier inference
Cognitive Execution Kernel & Hardware Telemetry All Systems Healthy
Hardware Accelerator
Apple MPS / CUDA Vector Engine
1-Bit Quantizer
PolarQuant FWHT (0.18ms Hamming)
Compiler Validation
C2C Self-Healing (100% Accuracy)
Prometheus Endpoint
:8080/metrics (Scraping)
Live Execution Stream (Recent Turns) Auto-updating · 100% Trace Logged
Turn ID User Intent Execution Path Billed Saved Turn Latency Status
#TRN-9402 Calculate closed-won revenue for Europe COMPILED_AST 0 tok ($0.00) +$0.0074 82 µs ✅ HIT (Verified)
#TRN-9401 Analyze customer churn for Mid-Market segment COMPILED_AST 0 tok ($0.00) +$0.0092 79 µs ✅ HIT (Verified)
#TRN-9400 Synthesize new multi-region compliance summary LLM_REASONING 1,820 tok ($0.014) $0.0000 1,940 ms ⚡ COMPILED NEW AST
Real-Time Token Consumption Breakdown 78.2% Token Bypassed
Bypassed ($0 Cost): 2,418,920 tokens (78.2%)
Prompt Tokens Billed: 412,800 tokens (14.8%)
Completion Tokens Billed: 128,450 tokens (7.0%)
Total Spend Incurred
$12.40
Frontier fallback turns
Net Procedural Savings
+$1,428.40
115.2× ROI Multiplier
Projected Annual Savings
$17,140.80
At current query cadence
Provider Tokenomics & Cost Registry
Model Name Provider Blended / 1M Tokens Calls Tokens Incurred Tokens Bypassed Net Saved
Claude 3.7 Sonnet Anthropic $9.00 / M 420 184,200 1,120,000 +$756.00
GPT-4o OpenAI $6.25 / M 380 158,100 980,000 +$487.50
Gemini 2.0 Flash Google DeepMind $0.25 / M 940 198,950 318,920 +$184.90
In-Process Llama 3.2 SLM Local TorchProvider $0.00 / M (MPS) 1,840 0 (Local RAM) — +$0.00 (Zero Cost)
Configured Model Fleet & Health Registry 5 Providers Online
Gemini 2.0 Flash ● Active
Google DeepMind • Fast Router
Latency (P50): 420 ms
Cost / 1M: $0.10 / $0.40
Success Rate: 99.8%
Claude 3.7 Sonnet ● Active
Anthropic • Complex Synthesizer
Latency (P50): 1,840 ms
Cost / 1M: $3.00 / $15.00
Success Rate: 99.5%
GPT-4.5 / 4o Standby
OpenAI • General Fallback
Latency (P50): 1,120 ms
Cost / 1M: $2.50 / $10.00
Success Rate: 99.4%
DeepSeek R1 Standby
DeepSeek • Math/Logic Verification
Latency (P50): 2,410 ms
Cost / 1M: $0.55 / $2.19
Success Rate: 98.9%
TorchProvider SLM ● In-Process
Llama 3.2 1B • Apple MPS Engine
Latency (P50): 38.4 ms
Cost / 1M: $0.00 (Zero)
Device Memory: 1.82 GB RAM
Cognitive Execution Routing Policy
Tier 1 • Deterministic
Procedural Memory
Compiled Python AST procedures, invariant schemas, and type-safe parameterized routines.
Allocated: 1.84 MB 142 / 2,048 (6.9%)
Active Routines: 142 Procedures
Reliability Rate: 99.4% Verified
Average Run Time: 80.3 µs
Persistence Engine: Atomic SQLite / Disk
Tier 2 • 1-Bit Vector
Semantic Memory
PolarQuant 1-bit quantized vector index with Fast Walsh-Hadamard Transform search.
Index Size: 420 KB 32× Compressed
Indexed Vectors: 1,024 Embeddings
Embedding Dimension: 768-dim
Cosine Threshold: 0.85 Minimum
Search Latency: 0.18 ms (Hamming)
Tier 3 • Multi-Turn
Episodic Memory
Historical session trajectories, trace logs, and cognitive activation decay (ACT-R scoring).
Trace Storage: 4.12 MB 58 Sessions
Total Turns Logged: 842 Turns
Compaction Ratio: 3.4× Compacted
Decay Factor: d = 0.5 (ACT-R)
Integrity Check: SHA-256 Passed
Tier 4 • Context Window
Working Memory
Active sliding context buffer, entity scratchpad, and short-term slot bindings.
Buffer: 1,640 Tokens 1,640 / 8,192 (20.0%)
Allocated RAM: 18.2 KB
Active Slot Bindings: 12 Entities
Task Frames: 3 Active
Eviction Policy: Priority FIFO
Compiled Procedural Memory Directory Click any procedure to inspect compiled AST code
Procedure Signature Intent Matcher Executions Success Rate Reliability Action
crm_closed_won_revenue(region: str) "Calculate enterprise sales revenue for {region}" 412 100.0% RELIABLE
compute_churn_ltv(segment: str) "Compute customer churn and LTV for {segment}" 289 100.0% RELIABLE
carrier_delay_vs_returns(carrier: str) "Analyze delivery delay vs return rate for {carrier}" 198 100.0% RELIABLE
inventory_reorder_trigger(sku: str) "Check inventory reorder safety threshold for {sku}" 84 98.8% RELIABLE
proc:crm_closed_won PROCEDURE
Verified compiled Python AST procedure. Re-executes regional closed-won revenue calculation in 80µs at $0.00 token cost.
Graph Relations:
→ calls sql_repl_engine
→ validates inv:RegionEnum
→ derives_from ent:SalesforceOpportunity
Executable AST Code:
def crm_closed_won_revenue(region: str) -> dict:
    query = f"SELECT SUM(amount) FROM opps WHERE region='{region}'"
    res = sql_engine.execute(query)
    return {"amount": res[0][0], "status": "verified"}
Economic Amortization

Token Savings & ROI Calculator

Model reasoning is an upfront compilation investment. Input your monthly LLM spend to calculate amortized savings from procedural execution.

$25,000
45% Overlap
Recurring queries, schema reports, API workflows, and structured extraction.
5 Turns
Projected Monthly Net Savings
$10,778
Direct cash saved from bypassed model inference
Annual Cost Reduction
$129,330
Tokens Bypassed / Mo
1.80B Tokens
Latency Saved / Mo
486 hrs
Break-Even Point (r*)
Turn 1.2
After Turn 1, recurring agent steps execute at $0.00 in <1µs.
View FastAPI Setup
Zero-Friction Integration

Drop-In FastAPI & ASGI Middleware

Add SemanticHarnessMiddleware to any existing Python backend in 3 lines of code. Automatically intercepts API routes, checks compiled procedural memory, and adds transparent cost-saving headers.

main.py (FastAPI App)
from fastapi import FastAPI
from pydantic import BaseModel
from semantic_harness.integrations.fastapi import (
    SemanticHarnessMiddleware,
    procedural_route,
)

app = FastAPI(title="Enterprise Agent Backend")

# 1. Add middleware to intercept and accelerate agent endpoints
app.add_middleware(
    SemanticHarnessMiddleware,
    cache_paths=["/api/v1/agent", "/api/v1/generate"],
    pricing_model="gpt-4o",
)

class AnalysisOutput(BaseModel):
    summary: str
    action_items: list[str]

# 2. Or decorate specific routes with procedural validation
@app.post("/api/v1/agent")
@procedural_route(validates=AnalysisOutput, cache=True)
async def run_agent_workflow(payload: dict):
    # Executes once via LLM; repeat calls execute at $0 in <1ms!
    return await my_agent_core.run(payload["query"])
HTTP Response Headers (Warm Path) 200 OK
X-Semantic-Harness-Cache: HIT (Zero-Token Fast Path)
X-Semantic-Harness-Cost-Saved: $0.007400
X-Semantic-Harness-Tokens-Bypassed: 1,480 tokens
X-Semantic-Harness-Latency-Saved-Ms: 1,842.10 ms
X-Semantic-Harness-Procedural-Hash: 4a2f8b19e2c041a8
Content-Type: application/json
Interactive Playground

See the Execution Difference

Click any quick scenario or customize parameters to see how Semantic Harness compiles and re-executes verified ASTs compared to standard LLMs and traditional vector caches.

Quick Scenarios:
1
Exact Hash
2
PolarQuant Match
3
AST Slot Binding
4
Python REPL Exec
5
Live Output
1. Stateless LLM
Full Inference
Tokens Billed: 260 tokens
Turn Latency: 9,081 ms
Inference Cost: $0.0039
Returned Value:
$300,000
✅ Valid Output (~9s delay)
2. Semantic Vector Cache
Response-Level
Tokens Billed: 0 tokens
Turn Latency: 915 ms
Accuracy Rate: 62.5%
Returned Value:
$44,410,000
❌ STALE DATA ERROR
3. Semantic Harness
Verified AST
Tokens Billed: 0 tokens ($0.00)
Turn Latency: 1.1 ms (80.3 µs)
Accuracy Rate: 100.0% Verified
Returned Value:
$300,000
✅ Live AST Execution (0 Tokens)
Live Sandboxed AST & REPL Execution Trace
Zero Model Tokens
# Step 1: Inbound Request -> "Calculate total closed won revenue for Europe region"
# Step 2: TurboQuant PolarQuant Fuzzy Match (Similarity: 0.94, Confidence: 0.92 >= 0.85)
# Step 3: Parameter Slot Binding -> params = {'region': 'Europe', 'stage': 'Closed Won'}
# Step 4: Python REPL Exec -> execute_ast(crm_revenue_ast, params=params)
# Step 5: Live Database Result -> {"revenue": 300000.0, "region": "Europe"} (1.12 ms)
Core Innovations

The Four Architectural Pillars

How Semantic Harness combines verified execution contracts with extreme vector compression.

1. Verified Semantic Compilation

Treats multi-turn LLM reasoning as a JIT program synthesis step. Once verified against Pydantic schema contracts, execution paths are compiled into parameterized ASTs for zero-token re-execution.

2. Chaos2Clarity (C2C) Self-Healing

Intercepts schema validation failures and synthesizes minimal, targeted differential prompts. Elevates Small Language Model (≤3B) structured output pass rates from 41.2% to 96.8%.

3. Google TurboQuant / PolarQuant

Compresses continuous procedural intent vectors by $8\times\text{--}16\times$ using random orthogonal polar transforms with QJL 1-bit residual correction for unbiased sub-microsecond retrieval.

4. ACT-R Cognitive 3-Tier Memory

Integrates a sliding Short-Term FIFO buffer, an embedded Long-Term SQLite datastore ranked by ACT-R cognitive activation equations $A_i(t)$, and quantized procedural caching.

System Architecture

Unified 5-Layer Stack

Decoupled hierarchy bridging probabilistic reasoning models with deterministic execution engines.

Layer 1

DeepSeek Harness (DSH) — Lifecycle & Governance

Waterfall event pipeline (turn/start → step/start → step/end → turn/end) with immutable append-only JSONL session logging and proactive loop guards.

Layer 2

NVIDIA Object-Oriented Agents (NOOA) — Execution Model

Class-as-Agent contracts with docstring prompt binding and a stateful, sandboxed CodeAct Python REPL for persistent multi-turn variables and AST capture.

Layer 3

Semantic Harness Core — Cognitive Middleware & C2C

Deterministic Pydantic validation, dynamic context token budgeting, and the Beta-Bernoulli conjugate reliability gate for safe fast-path routing ($0.00\%$ False Reuse Rate).

Layer 4

Google TurboQuant / PolarQuant — Vector Compression

1-Bit polar vector quantization and fast Walsh-Hadamard transforms enabling CPU bitwise XOR search ($1.5\ \mu\text{s}$ per query).

Layer 5

Multi-Provider Inference Layer

Universal model interoperability across local Ollama SLMs (Qwen, Gemma), vLLM engines, and cloud providers (OpenAI, Anthropic, Gemini).

Empirical Evaluation

Research Figures & Benchmark Data

Evaluated across 89 verified unit test suites, a 48-turn enterprise runtime stream, and a 200-turn relational SQL benchmark.

Token Avoidance Distribution
Figure 1: Token & Latency Avoidance Distribution. Demonstrates 21.16% total token avoidance across the mixed stream ($p = 5.06 \times 10^{-3}$ on Wilcoxon signed-rank test), with 100% token cost reduction on warm procedural hits.
Signature Parameter Experiment
Figure 2: The Signature Experiment. Traditional semantic vector caches suffer 18 stale-data errors (accuracy drops to 62.5%) when parameters change. Semantic Harness re-executes compiled ASTs with new arguments at 100.0% accuracy and 0 tokens.
Speedup Pareto Frontier
Figure 3: Latency-Accuracy Pareto Frontier. Shows execution speedup across recurring business intelligence workflows, achieving $80.3\ \mu\text{s}$ average latency (>500× speedup) on warm procedural paths.
Error Taxonomy Distribution
Figure 4: Formal 5-Class Error Taxonomy Suppression. Schema hallucinations ($E_1$) drop from 38.0% down to 6.0% ($-84.2\%$ relative reduction) via C2C type enforcement ($\chi^2 = 12.25, p = 0.00047$).
Longitudinal Learning Curve
Figure 5: 200-Turn Longitudinal Procedural Learning. Non-parametric session learning evolves first-pass execution success from 50.0% up to 86.0% as verified procedures are cached.
Integration Guide

Drop-In Usage Recipes

Get started with one decorator, or build object-oriented stateful agents.

step_decorator_example.py
from pydantic import BaseModel
from semantic_harness import step

class RevenueReport(BaseModel):
    region: str
    total_revenue: float
    deal_count: int

# Validates Pydantic schema and compiles procedural fast-path
@step(validates=RevenueReport, cache=True)
def get_regional_sales(region: str) -> dict:
    prompt = f"Extract revenue figures for {region} from current pipeline."
    return llm_client.generate_json(prompt)

# Turn 1 (Cold): Calls LLM -> Validates schema -> Compiles AST logic
report1 = get_regional_sales(region="North America")

# Turn 2 (Warm): Re-executes AST in REPL -> 1.1 ms response, 0 TOKENS billed!
report2 = get_regional_sales(region="Europe")
print(report2)
financial_analyst_agent.py
from semantic_harness import Agent, AgentConfig

class FinancialAnalyst(Agent):
    """You are an autonomous corporate financial analyst."""

    def calculate_margin(self, revenue: float, cost: float) -> float:
        """Compute gross profit margin percentage."""
        return ((revenue - cost) / revenue) * 100.0

agent = FinancialAnalyst(config=AgentConfig(model="qwen2.5-coder:3b", strategy="codeact"))

# Store enterprise metadata with ACT-R importance ranking
agent.long_term.remember(
    key="q4_targets",
    content="Q4 revenue target is $100M with max operating expense of $65M.",
    importance=0.95
)

# Run multi-turn task with persistent CodeAct variables
result = agent.run("Evaluate projected Q4 EBITDA margin based on target figures.")
print(result)
agent.ts
import { Agent, step } from "semantic-harness";
import { z } from "zod";

const UserProfileSchema = z.object({
  userId: z.number(),
  name: z.string(),
  activeSubscription: z.boolean(),
});

export class CustomerSupportAgent extends Agent {
  @step({ schema: UserProfileSchema, cache: true })
  async lookupUser(email: string) {
    // Re-executes verified AST without token inference on warm paths
    return await this.callLLM(`Fetch structured profile for ${email}`);
  }
}
langgraph_node.py
from semantic_harness import ProceduralMemory, C2CValidator

proc_mem = ProceduralMemory(enable_fuzzy_search=True)

def validated_tool_node(state):
    intent = state["current_intent"]
    
    # 1. Zero-Token Fast Path Check
    cached_proc = proc_mem.lookup(intent)
    if cached_proc and cached_proc.is_reliable:
        state["result"] = cached_proc.execute(state["params"])
        state["tokens_used"] = 0
        return state

    # 2. Standard LLM Execution + C2C Validation
    raw_output = call_llm(state["prompt"])
    state["result"] = C2CValidator(state["schema"]).validate(raw_output)
    proc_mem.cache(intent, state["result"])
    return state
Academic Research

Citation & Zenodo DOI

Semantic Harness is archived on Zenodo with an open-access Digital Object Identifier.

Academic Paper Published v0.2.5

Semantic Harness: Cognitive Middleware, Procedural Acceleration, and Layered Runtime Architecture for Autonomous AI Agents

Author: Bankupalli Ravi Teja • Affiliation: Independent Research / Open Source Systems

BibTeX Citation
@article{bankupalli2026semanticharness,
  author       = {Bankupalli, Ravi Teja},
  title        = {{Semantic Harness: Cognitive Middleware, Procedural Acceleration, and Layered Runtime Architecture for Autonomous AI Agents}},
  year         = {2026},
  month        = {August},
  journal      = {arXiv preprint},
  publisher    = {Zenodo},
  version      = {0.2.5},
  doi          = {10.5281/zenodo.19414309},
  url          = {https://zenodo.org/records/19414309}
}