When an AI agent writes code to rebalance a portfolio or execute a trade, traditional safeguards happen too late. Runtime checks catch errors after deployment. Unit tests miss logical flaws that only surface under market stress. Sandboxes contain damage but don’t prevent it.
Bend 2 takes a different approach: it forces agents to prove correctness at compile time. Before any code runs, the compiler verifies that business rules hold mathematically. This shifts the security boundary from runtime containment to compile-time prevention.
The Laws-as-Code Contract Layer
Bend introduces a LAWS.bend file where you declare invariants your system must never violate. These aren’t runtime assertions. They’re type-level constraints the compiler enforces through proof obligations.
For a financial agent, a law might state:
- Position size never exceeds account equity multiplied by leverage limit
- Order execution always decrements available balance
- Withdrawal requests cannot leave negative balances
The compiler translates these rules into dependent types. When an agent generates or modifies code, it must satisfy the proof obligation or compilation fails.
Example law structure:
law PositionLimit:
forall (account: Account) (position: Position).
position.size <= account.equity * account.max_leverage
law NoDoubleSpend:
forall (balance: Balance) (tx1 tx2: Transaction).
linear(balance) => (tx1.id != tx2.id)
The linear keyword enforces that balance state can only be consumed once, preventing double-spend bugs at the type level.
Proof Obligations in the Agent Loop
When an AI agent edits code, Bend’s workflow looks like this:
- Agent generates a function (e.g.,
execute_trade) - Compiler extracts proof obligations from applicable laws
- Agent must provide a proof term or the build fails
- Checker verifies the proof in under 1 second
- Only proven-correct code compiles to an executable
The agent doesn’t need to be a theorem prover. It generates code in Bend’s syntax, and the compiler identifies which laws apply. If the agent’s logic violates a law, the compiler returns a specific error pointing to the broken invariant.
Proof generation options:
- Agent synthesizes proof terms directly (requires training on formal methods)
- Separate verifier agent specializes in proof construction
- Human operator provides proof for high-risk changes
- Proof search tactics auto-generate simple proofs
Bend’s checker benchmarks show proof verification in under 1 second for files that take minutes in Lean, Agda, or Rocq. This speed matters for agent iteration loops where rapid feedback prevents wasted compute on invalid paths.
Linear Types and Financial State Machines
Linear types ensure a value is used exactly once. For financial workflows, this prevents entire classes of bugs:
- Double-spend prevention: A balance token can only fund one transaction
- Order lifecycle tracking: An order moves through states (pending, filled, cancelled) without duplication
- Position accounting: Opening a position consumes margin exactly once
Traditional runtime checks for these conditions add latency and still allow race conditions. Linear types enforce correctness at compile time with zero runtime overhead.
Trade-off table:
| Approach | Prevention Timing | Performance Cost | Coverage |
|---|---|---|---|
| Runtime assertions | Post-execution | 5-15% overhead per check | Partial (tested paths) |
| Sandboxing | During execution | 20-40% overhead | Containment only |
| Linear types | Compile-time | Zero runtime cost | Complete (all paths) |
| Proof obligations | Compile-time | Zero runtime cost | Formal guarantee |
The performance advantage compounds in high-frequency scenarios. A trading agent making 10,000 decisions per second pays no penalty for correctness guarantees.
GPU Execution for Stateful Workflows
Bend compiles to GPU-native code with automatic parallelization. The compiler analyzes pure functions and spreads work across available cores without explicit kernel code.
For financial agents, this enables:
- Parallel order book updates: Split order matching across thousands of price levels
- Portfolio optimization: Evaluate allocation scenarios simultaneously
- Risk calculation: Compute VaR across correlated positions in parallel
The challenge with GPU execution is maintaining sequential consistency for stateful operations. Bend’s purity requirements and linear types solve this. State transitions become pure functions over immutable data structures, allowing safe parallelization.
Execution model:
// Automatically parallelizes across GPU cores
def rebalance(portfolio: Portfolio, targets: List<Target>): Portfolio =
targets.map(target =>
adjust_position(portfolio, target)
).fold(merge_adjustments)
The pow2(20) benchmark shows Bend splitting work across 4,096 GPU cores and folding results back. For a portfolio with 1,000 positions, this means sub-millisecond rebalancing versus sequential processing.
Failure Modes and Compilation Boundaries
When agent-generated code violates a law, compilation fails with a proof obligation error. The agent receives:
- Which law was violated
- The specific function or expression causing the violation
- The expected proof term structure
Common failure scenarios:
- Incomplete proofs: Agent generates logic but omits proof terms
- Type mismatches: Function signature doesn’t align with law constraints
- Unreachable proofs: Agent attempts logic that cannot satisfy the law (correctly rejected)
The third case is the most valuable. If an agent tries to implement a strategy that mathematically cannot satisfy position limits, the compiler blocks it before deployment. This prevents entire categories of logic errors that unit tests would miss.
Repair strategies:
- Agent retries with adjusted logic
- Fallback to conservative implementation with trivial proof
- Human review for complex proof obligations
- Law relaxation (requires explicit approval)
Observability and Proof Audit Trails
Every successful compilation produces:
- Executable binary
- Proof certificate linking code to satisfied laws
- Dependency graph showing which proofs rely on which axioms
For financial compliance, the proof certificate becomes an audit artifact. Regulators can verify that deployed code provably satisfies risk limits without reading the implementation.
Audit trail structure:
- Timestamp of compilation
- Git commit hash of source and laws
- Proof checker version
- List of satisfied laws with proof terms
- Any axioms assumed (e.g., exchange API correctness)
This creates a formal chain of custody from business rule to deployed behavior.
Deployment Shape and Integration Points
Bend compiles to standalone executables. For agent infrastructure, this means:
- No runtime interpreter: Agents deploy native binaries
- No JIT overhead: First execution is full speed
- Deterministic performance: No GC pauses or dynamic optimization
Integration with existing agent orchestration:
- Agent generates Bend code in response to market conditions
- CI pipeline compiles with proof checking enabled
- Successful compilation triggers deployment to execution environment
- Monitoring tracks actual behavior against proven properties
The compile step becomes a formal gate. If proofs don’t check, code doesn’t ship.
When Proof Checking Becomes Overhead
Bend’s approach has clear boundaries:
Use when:
- Mistakes have monetary consequences (trading, payments, underwriting)
- Business rules are formalizable (position limits, balance constraints)
- Agent autonomy requires high confidence (unsupervised execution)
- Performance matters (high-frequency decisions, parallel workloads)
Avoid when:
- Exploratory prototyping where requirements are unclear
- Business rules change faster than laws can be formalized
- Team lacks formal methods expertise for complex proofs
- Runtime flexibility is more valuable than compile-time guarantees
The proof obligation workflow adds friction to the agent iteration loop. For research agents exploring strategies, this friction outweighs the safety benefit. For production agents managing real capital, the friction prevents expensive mistakes.
Technical Verdict
Bend 2 is infrastructure for financial agents where correctness is non-negotiable. The compile-time proof model prevents entire classes of errors that runtime checks and sandboxes cannot catch. Linear types eliminate double-spend bugs. Laws-as-code create formal contracts between agent intent and execution.
The GPU execution model and sub-second proof checking make this practical for high-frequency scenarios. An agent can iterate on strategies while maintaining formal correctness guarantees.
The trade-off is upfront complexity. Formalizing business rules as laws requires precision. Training agents to generate proof terms or integrating separate verifier agents adds orchestration overhead. Teams need enough formal methods literacy to debug proof failures.
For supervised agents or low-stakes automation, traditional testing and runtime checks are sufficient. For autonomous financial agents, Bend’s proof-checked execution model is the only approach that blocks mistakes before they cost money.
Use Bend when agent mistakes have immediate monetary impact and your team can invest in formalizing invariants. Avoid it when iteration speed matters more than formal correctness or when business rules are too fluid to encode as laws.
Source Links
- Primary source: Bend 2 on GitHub
- Installation:
curl -fsSL https://bend-lang.com/install.sh | sh