Skip to main content
Glama
README.md
# FalsifySQL — Neurosymbolic Verification, Conformal Plausibility & RLVR Control Plane for AI Data Agents

[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-3776AB?logo=python&logoColor=white)](pyproject.toml)
[![License: Apache-2.0](https://img.shields.io/badge/license-Apache%202.0-22c55e)](LICENSE)
[![CI](https://github.com/Sumesh-Chakkaravarthi/falsifysql/actions/workflows/ci.yml/badge.svg)](https://github.com/Sumesh-Chakkaravarthi/falsifysql/actions/workflows/ci.yml)
[![SilentSQL-Bench](https://img.shields.io/badge/SilentSQL--Bench-100%25%20BTR%20%7C%200%25%20FSR-38bdf8)](docs/BENCHMARK_REPORT.md)
[![Latency](https://img.shields.io/badge/Gateway%20P50-8.59%20ms-a855f7)](docs/ARCHITECTURE.md)
[![MCP](https://img.shields.io/badge/MCP-stdio%20%2B%20Streamable%20HTTP-f59e0b)](src/falsifysql/gateway/mcp_server.py)

**FalsifySQL** is an open-core **Neurosymbolic Verification Gateway, Conformal Plausibility Adjudicator, and Reinforcement Learning with Verifiable Rewards (RLVR) Self-Healing Control Plane** for AI data agents (Claude, Cursor, LangGraph, Snowflake Cortex, Databricks Genie).

Instead of trusting text-to-SQL wrappers that cheerfully return **plausible, silently wrong numbers** to executive dashboards, FalsifySQL intercepts queries at the **Model Context Protocol (MCP)** boundary and attempts to mathematically, structurally, and statistically **falsify** every query before a result leaves the warehouse.

![FalsifySQL Captioned Walkthrough — 3x Fan-Out Interception, Counterexample Micro-DB, Conformal/PELT & DoWhy Causal Gate](assets/falsifysql_demo.gif)

> **Full 720p H.264 Captioned Demo Video:** [`assets/falsifysql_demo.mp4`](assets/falsifysql_demo.mp4) (`1280×720`, 30s 6-scene walkthrough — ready for LinkedIn / job applications)

---

## Why FalsifySQL? The Silent Semantic Failure Crisis

A syntax error fails safely. The expensive production failure is SQL that compiles cleanly, runs in under a millisecond, and silently corrupts a financial or operational metric:

1. **Fan-Out & Chasm Traps (Grain Multiplication):** `SUM(orders.amount)` joined to 1:N `payments` or `order_items` silently inflates a `$150` order across 3 installments into `$450`.
2. **Snapshot-Sum Overcounts:** Summing `inventory_snapshots.inventory_value` across 90 daily partitions turns `$10M` of daily stock into **`$900M` (90× overcount)**.
3. **Partial-Period Comparison Bias:** Comparing 12 days of month-to-date revenue against a full 31-day prior month fabricates an artificial collapse.
4. **Fabricated Filter Literals & Implicit Exclusions:** `WHERE region = 'APAC'` against `'Asia-Pacific'` silently returns zero rows, while dropping `status = 'completed'` counts churned trials as revenue.
5. **Undocumented Regime Breaks & Causal Hallucinations:** A mid-quarter `lead_score` cutoff shift (70 → 80) looks like a marketing collapse unless caught by PELT changepoints, and observational `GROUP BY` churn correlations masquerade as causal effects without backdoor + placebo refutation.

---

## 5-Layer Neurosymbolic & RLVR Architecture

![FalsifySQL Architecture](assets/falsifysql_architecture_card.png)

| Layer | Core Engine | What It Guarantees |
| :--- | :--- | :--- |
| **Gate 1: AST & Empirical Grain-FD** (`src/falsifysql/gate1`) | `sqlglot[c]` + Empirical Schema Profiler + AST Security | Single-statement `SELECT`/`WITH` allowlist, UDF blocklist, AST `tenant_id` injection, `EXPLAIN` dry-run, 1:N fan-out detection, snapshot-sum pin, partial-period alignment, live enum grounding. |
| **Gate 2: Regime, Conformal & SHAP** (`src/falsifysql/gate2`) | `ruptures` PELT + `TabICLv2`/`MAPIE` CQR + ACI + `OnlineMartingaleTest` + SHAP | Flags structural time-series breaks linked to Living Context commits; enforces distribution-free 95% conformal intervals $P(Y \in \hat{C}_\alpha(X)) \ge 1 - \alpha$; computes Shapley slice attributions & ratio-of-totals invariants. |
| **Gate 3: Causal Refutation** (`src/falsifysql/gate3`) | `DoWhy` + `EconML` / Doubly-Robust AIPW | Enforces Specify → Identify → Estimate → Refute (placebo permutation + unobserved confounder sensitivity) before allowing causal narration. |
| **Layer 4: RLVR Repair & Serving** (`src/falsifysql/rlvr`) | Unsloth 4-bit QLoRA GRPO (`Qwen3-8B`) + vLLM + XGrammar EBNF + Counterexample Micro-DB | Rewrites broken SQL via grain-safe CTEs / snapshot pins / calibrated `REFUSE()`, verified against an adversarial Counterexample Micro-DB to block reward hacking. |
| **Layer 5: MCP Gateway & SaaS Plane** (`src/falsifysql/gateway`) | FastMCP (`stdio` + `/mcp` HTTP) + Postgres/`pgvector` Context + Stripe Billing Meters + CI PR Guard | One-line agent integration, versioned analyst-confirmed rules, usage-based Stripe metering, and GitHub Actions SQL PR checks. |

---

## SilentSQL-Bench Results (260 Adversarial Tasks + 20 Clean Controls)

![SilentSQL-Bench Results](assets/falsifysql_benchmark_chart.png)

| System Configuration | Business Truth Rate (BTR) | False Success Rate (FSR) | Clean Control Precision | Gateway Latency |
| :--- | :---: | :---: | :---: | :---: |
| **Raw Unguarded SQL** | `0.0%` | `93.1%` | `100.0%` | — |
| **Gate 1 Only (Detection)** | `80.0%` | `20.0%` | `100.0%` | — |
| **FalsifySQL Full Control Plane** | **`100.0%`** | **`0.0%`** | **`100.0%`** | **`8.59 ms` P50 / `91.77 ms` P95** |

Reproduce locally in < 10 seconds:

```bash
PYTHONPATH=src python3 benchmarks/run_benchmarks.py --assert-btr-min 0.98
```

---

## 30-Second Quickstart & Interactive Control Plane

Launch the **Zero-Signup Interactive Web Playground & Control Plane** (with live AST/Grain SVG topology, PELT + Conformal Canvas, SHAP attributions, Counterexample Micro-DB diff, DoWhy Causal Refutation, and Stripe Meter telemetry):

```bash
git clone https://github.com/Sumesh-Chakkaravarthi/falsifysql.git
cd falsifysql
PYTHONPATH=src python3 -m falsifysql.cli playground --port 8787
# Open http://127.0.0.1:8787
```

### CLI & MCP Gateway Commands

```bash
# Verify & auto-repair a single SQL query via CLI
PYTHONPATH=src python3 -m falsifysql.cli verify \
  --sql "SELECT o.order_id, SUM(o.amount) AS rev FROM orders o JOIN payments p ON o.order_id = p.order_id WHERE o.order_id = 1001 GROUP BY o.order_id" \
  --prompt "Total revenue for Order 1001"

# Launch stdio MCP server for Claude Desktop / Cursor / Claude Code
PYTHONPATH=src python3 -m falsifysql.cli mcp --transport stdio

# Run CI PR Guard over SQL / dbt files
PYTHONPATH=src python3 -m falsifysql.cli pr-guard path/to/models/

# Validate 4-signal GRPO/RLVR training corpus & rewards (no GPU needed for dry-run)
PYTHONPATH=src python3 -m falsifysql.cli train-grpo --dry-run

# Run full unit & integration test suite (22 tests)
PYTHONPATH=src python3 -m unittest discover -s tests -v
```

---

## Repository Layout

```text
falsifysql/
├── assets/                   # Architecture card, SilentSQL-Bench chart, animated demo GIF
├── benchmarks/               # 260-task SilentSQL-Bench generator & evaluation runner
├── deploy/k8s/               # Production Kubernetes Deployment, Service & ConfigMap
├── docs/                     # ARCHITECTURE.md, BENCHMARK_REPORT.md, MONETIZATION_AND_COMPLIANCE.md
├── scripts/                  # Visual asset generator & macOS AVAssetWriter helper
├── src/falsifysql/
│   ├── sql_ast.py            # SQL lexer/AST parser, sqlglot[c] adapter & tenant node injector
│   ├── warehouse/            # Read-only connectors, enterprise demo warehouse, Counterexample Micro-DB
│   ├── gate1/                # Empirical Grain-FD profiler, AST security & deterministic verifiers
│   ├── gate2/                # PELT changepoints, TabICLv2/MAPIE CQR + ACI + Martingale, SHAP & invariants
│   ├── gate3/                # DoWhy/EconML causal DAG, AIPW backdoor & placebo/sensitivity refutation
│   ├── rlvr/                 # Silent-bug mutator, 4-signal reward, repair solver, Unsloth/TRL GRPO, vLLM/XGrammar
│   ├── gateway/              # FalsifyPipeline, pgvector Living Context Store, FastMCP, Stripe Meters, PR Guard
│   └── web/                  # Flask API + Obsidian Cyber-FinTech Interactive Playground UI
└── tests/                    # Comprehensive unit, integration, MCP, and benchmark CI gate tests
```

See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md), [docs/BENCHMARK_REPORT.md](docs/BENCHMARK_REPORT.md), and [docs/MONETIZATION_AND_COMPLIANCE.md](docs/MONETIZATION_AND_COMPLIANCE.md).