Skip to content

smyansengupta/guardrails-atomic

Repository files navigation

Guardrails: Atomic

AI-powered code generation with formal correctness guarantees for distributed systems using CEGIS and Z3 SMT solver.

TypeScript Next.js Z3

What is Guardrails: Atomic?

Guardrails: Atomic automatically generates formally verified TypeScript handlers for distributed systems. It uses:

  • πŸ€– AI Code Generation: GPT-4 via OpenRouter
  • βœ… Formal Verification: Z3 SMT Solver proves correctness
  • πŸ”„ CEGIS Loop: Iterative synthesis with counterexample-guided repair
  • πŸ›‘οΈ Fault Tolerance: Handles at-least-once delivery, reordering, crashes

Why?

Writing correct distributed systems code is hard. Common bugs include:

  • Double-spending under duplicate message delivery
  • Race conditions from message reordering
  • Partial state updates after crashes
  • Idempotency violations

Guardrails: Atomic proves your code is correct before you deploy it.


Quick Start

Prerequisites

Optional (for production):

Installation

# 1. Clone the repository
git clone https://github.com/yourusername/guardrails-atomic.git
cd guardrails-atomic

# 2. Install dependencies
pnpm install

# 3. Set up environment variables
cp .env.local.example .env.local
# Edit .env.local and add your OPENROUTER_API_KEY

# 4. Run development server
pnpm dev

Open http://localhost:3000


How It Works

The CEGIS Loop

User YAML Spec
      ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  CEGIS Loop (max 8 iterations) β”‚
β”‚                                 β”‚
β”‚  1. LLM generates TypeScript    β”‚
β”‚  2. Translate to Z3 constraints β”‚
β”‚  3. Run Z3 solver               β”‚
β”‚  4. If 'sat' (bug found):       β”‚
β”‚     β†’ Extract counterexample    β”‚
β”‚     β†’ Repair code with LLM      β”‚
β”‚  5. If 'unsat' (verified): βœ…   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
      ↓
Formally Verified Code

Example Workflow

  1. Describe your distributed system handler in YAML:

    name: transfer_atomic
    invariants:
      - type: idempotent        # No double-spending
      - type: conservation      # Balance preserved
    faultModel:
      delivery: at_least_once   # Messages may duplicate
  2. Generate code with AI

  3. Verify with Z3:

    • ❌ If bugs found β†’ Z3 provides counterexample β†’ LLM repairs
    • βœ… If verified β†’ You get proven-correct code!

Example

Input: YAML Specification

name: transfer_atomic
signature:
  params:
    - name: state
      type: Map<Acct,int>
    - name: from
      type: Acct
    - name: to
      type: Acct
    - name: amt
      type: int
    - name: req_id
      type: UUID
  returnType: Map<Acct,int>
preconditions:
  - amt >= 0
  - from != to
  - state[from] >= amt
postconditions:
  - sum(result.values()) == sum(state.values())
invariants:
  - type: idempotent
  - type: conservation
faultModel:
  delivery: at_least_once
  reorder: true
  crash_restart: true
bounds:
  accts: 3
  retries: 2

Output: Verified TypeScript Code

function transfer_atomic(
  state: Map<string, number>,
  from: string,
  to: string,
  amt: number,
  req_id: string,
  processedRequests: Set<string>
): Map<string, number> {
  // Idempotency check
  if (processedRequests.has(req_id)) {
    return state; // Already processed, no-op
  }

  // Precondition checks
  if (amt < 0 || from === to || (state.get(from) ?? 0) < amt) {
    throw new Error('Precondition violated');
  }

  // Atomic state update
  const newState = new Map(state);
  newState.set(from, (newState.get(from) ?? 0) - amt);
  newState.set(to, (newState.get(to) ?? 0) + amt);

  // Mark as processed
  processedRequests.add(req_id);

  return newState;
}

Guarantees: βœ… Idempotent - duplicate messages have no effect βœ… Conservation - total balance preserved βœ… Atomic - no partial updates βœ… Formally verified by Z3 SMT solver


Documentation


Tech Stack

Component Technology
Frontend/Backend Next.js 15, React 19
Language TypeScript (100%)
Formal Verification Z3 SMT Solver
AI Code Generation OpenRouter (GPT-4)
Authentication Clerk
Database MongoDB Atlas
Testing Vitest
Styling Tailwind CSS

Project Structure

guardrails-atomic/
β”œβ”€β”€ app/                   # Next.js App Router
β”‚   β”œβ”€β”€ api/               # API routes
β”‚   β”‚   β”œβ”€β”€ verify/        # Main verification endpoint
β”‚   β”‚   β”œβ”€β”€ generate-spec/ # NL to YAML generator
β”‚   β”‚   └── ...
β”‚   β”œβ”€β”€ verify/            # Verification UI
β”‚   └── examples/          # Example specs
β”‚
β”œβ”€β”€ lib/                   # Core logic
β”‚   β”œβ”€β”€ core/              # CEGIS loop
β”‚   β”œβ”€β”€ verification/      # Z3 integration
β”‚   └── types/             # TypeScript types
β”‚
β”œβ”€β”€ components/            # React components
β”œβ”€β”€ docs/                  # Documentation
β”œβ”€β”€ tests/                 # Test suite
└── scripts/               # Build scripts

Testing

# Run all tests
pnpm test

# Watch mode
pnpm test --watch

# UI mode
pnpm test:ui

Building

# Development
pnpm dev

# Production build
pnpm build
pnpm start

# Linting
pnpm lint

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'feat: Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Future Plans

Planned Features

  • πŸ”‘ User-provided API keys (bring your own OpenRouter/OpenAI key)
  • πŸ’Ύ Caching of verified implementations
  • 🌍 Multi-language code generation (Python, Go, Rust)
  • 🧩 Custom invariants via user-defined predicates
  • 🀝 Real-time collaboration

Research Directions

  • Neural-guided synthesis (ML to predict good candidates)
  • Compositional verification (verify modules independently)
  • Automatic fault model inference from tests

License

MIT


Acknowledgments

  • Z3 Solver: Microsoft Research
  • OpenRouter: LLM API aggregation
  • Next.js & Vercel: Web framework and deployment
  • Clerk: Authentication
  • MongoDB: Database

Built during ALIHacks (2025) Modernized and production-ready (2025)

About

ALIHacks '25 Winner

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors