# AI Formal Verification Went Mainstream for Me

> Source: <https://notibuddy.app/blog/using-ai-to-ship-formally-verified-software>
> Published: 2026-11-29 00:00:00+00:00

**Recommendation:** Write Dafny specs for small pure policy models and generate production code from them, then have CI fail on both proof failures and codegen drift; Dafny exits with code 4 and names the unproven obligation.
More in the playbook "Verifying model output": <https://wpnews.pro/playbooks/output-verification>

[← All blog posts](https://notibuddy.app/blog)

# AI Formal Verification Went Mainstream for Me

Formal verification isn't enough on its own, yet Dafny still paid off in an AI-written codebase. Here is what held up.

Over the past several weeks I shipped [NotiBuddy](https://notibuddy.app/), a native iPhone, iPad, and Apple Watch app paired with a Cloudflare Workers relay and a local CLI and MCP client. It is Apple-only for now. The multi-platform codebase spans roughly 440,000 lines of product and test code across well over a thousand commits, and I built all of it exclusively with AI coding agents.

Working that way changes where the bottleneck is. Writing code gets cheap almost immediately; trusting what was written is the hard part. An agent can generate a clean, well-typed state machine and a suite of passing unit tests in a couple of minutes while leaving a subtle transition bug buried inside. Maybe a late reply reopens an expired request, or a retry collides with a cancellation. Everything looks reasonable in the diff until it breaks in production.

In December 2025, Martin Kleppmann [predicted](https://martin.kleppmann.com/2025/12/08/ai-formal-verification.html) that AI would bring formal verification into the mainstream. While building NotiBuddy, I decided to test that idea on real policy logic using Dafny. Where formal models fit, they gave me a level of confidence in AI-generated code that unit tests alone never could. Across most of the codebase, though, they either did not apply or got in the way.

## Why Dafny fits an AI-only workflow

I had never used formal verification on a shipping product before. Proof engineering by hand is slow, finicky work, and spending an afternoon hunting for the one intermediate assertion that convinces an SMT solver to accept a sequence slice rarely makes sense on a small team.

Pairing Dafny with a coding agent changed the economics of that work. Searching for intermediate lemmas and adjusting proof hints is mostly repetitive trial and error, which an agent can grind through quickly. It could revise a proof and rerun `dafny verify` until every obligation discharged, leaving me to check that the specification itself stayed intact. When verification fails, Dafny returns exit code `4` and points to the obligation it could not establish, whether that is a postcondition, precondition, assertion, invariant, termination check, or well-formedness check. That line is not always where the underlying bug lives, and because counterexample extraction in Dafny is opt-in and only a diagnostic hint that can be invalid, you do not automatically get a runnable failing trace. Even so, knowing which obligation failed is usually enough to keep an agent moving toward a fix.

The bigger payoff was shrinking what I had to review by hand. When you are not typing the implementation yourself, reading every branch of a large generated TypeScript handler turns into rubber-stamping faster than you would like to admit. I used Dafny to verify small, pure policy models for relay admission, replay, and billing rules, as well as screen admission for [Custom Native Screens](https://notibuddy.app/screens), where the content-blind relay validates stripped structural templates without reading plaintext. To keep production code from drifting from the spec, the Workers call generated TypeScript derived directly from those verified Dafny models instead of a separate handwritten copy, and CI checks both that the proofs pass and that the generated output stays in sync.

With codegen wired up, I could spend my review budget on the datatype definitions and the `requires` and `ensures` clauses. As long as those contracts capture the rules I want and the proof contains no unjustified assumptions, the solver checks every transition in the model for the stated properties. Liveness properties, I/O wrappers, and everything outside the model still have to be tested on their own, so I never reached for Dafny on SwiftUI views, SQLite persistence, or push delivery plumbing.

## A small example you can try yourself

A fair complaint about formal methods tutorials is that they often verify a single function where a type checker or two unit tests would have done the job. It starts paying its rent when you care about safety properties across every finite sequence of events: retries, clock ticks, cancellations, and duplicate replies arriving in orders you never thought to test.

The standalone model below is drawn from NotiBuddy’s public fail-closed approval behavior. You can toggle the preset mutations above the editor, edit any line directly and click **Verify** to run real Dafny 4.11.0 in a rate-limited browser sandbox, or copy `gate_trace.dfy` to run `dafny verify gate_trace.dfy` locally:

```
datatype GatePolicy = GatePolicy(requiresAuth: bool, deadlineMs: nat)

datatype SignedReply = SignedReply(
  receivedAtMs: nat,
  signatureValid: bool,
  userAccepted: bool,
  biometricVerified: bool
)

datatype Event =
  | Tick(nowMs: nat)
  | Reply(reply: SignedReply)
  | Cancel

datatype State =
  | Pending(policy: GatePolicy)
  | Approved(policy: GatePolicy, evidence: SignedReply)
  | Rejected
  | Expired

predicate Authorized(p: GatePolicy, r: SignedReply) {
  r.receivedAtMs <= p.deadlineMs &&
  r.signatureValid &&
  r.userAccepted &&
  (!p.requiresAuth || r.biometricVerified)
}

function Step(s: State, e: Event): State {
  match s {
    case Pending(p) =>
      match e {
        case Tick(now) => if now > p.deadlineMs then Expired else Pending(p)
        case Cancel => Rejected
        case Reply(r) =>
          if r.receivedAtMs > p.deadlineMs then Expired
          else if Authorized(p, r) then Approved(p, r)
          else Rejected
      }
    case Approved(_, _) => s
    case Rejected => Rejected
    case Expired => Expired
  }
}

function Run(s: State, trace: seq<Event>): State
  decreases |trace|
{
  if |trace| == 0 then s
  else Run(Step(s, trace[0]), trace[1..])
}

// 1. Once a request leaves Pending, no future event trace (retries,
//    replays, or late valid signatures) can flip the terminal outcome.
lemma TerminalStateNeverFlips(s: State, trace: seq<Event>)
  requires !s.Pending?
  ensures Run(s, trace) == s
  decreases |trace|
{
  if |trace| > 0 {
    TerminalStateNeverFlips(Step(s, trace[0]), trace[1..]);
  }
}

// 2. Across any arbitrary trace of ticks, cancels, and replies,
//    Approved is reachable only with verified evidence satisfying policy.
lemma ApprovedRequiresEvidence(p: GatePolicy, trace: seq<Event>)
  ensures var final := Run(Pending(p), trace);
          final.Approved? ==> final.policy == p && Authorized(p, final.evidence)
  decreases |trace|
{
  if |trace| > 0 {
    var next := Step(Pending(p), trace[0]);
    if next.Pending? {
      ApprovedRequiresEvidence(p, trace[1..]);
    } else {
      TerminalStateNeverFlips(next, trace[1..]);
    }
  }
}
```

Unit tests cover the specific traces you remembered to write down, whereas `TerminalStateNeverFlips` and `ApprovedRequiresEvidence` quantify over every finite trace. A cancellation followed by a valid reply cannot flip the outcome, and a tick past the deadline followed by a retried delivery stays expired. In an AI-written codebase, that safety net pays off most on later edits: if an agent refactors `Step` two weeks from now and slips in a bad transition, verification fails right away. Try it in the editor above by switching to **Skip auth check** (or changing `Authorized(p, r)` to `r.userAccepted` yourself and clicking **Verify**), or try **Cancel after approve** to watch Dafny reject the change on the spot.

What sits outside this proof is at least as important as what is inside it. `signatureValid`, `biometricVerified`, and `receivedAtMs` are plain inputs handed to the model. Nothing in the file verifies elliptic-curve cryptography, binds a reply to a specific request ID, checks clock accuracy, or establishes that production code conforms to the model. Even within the model itself, these two safety lemmas do not prove liveness properties like eventual expiration or that every eligible reply succeeds. As Alperen Keles recently [wrote](https://alperenkeles.com/posts/formal-verification-is-not-verifiable/), “formally verified” only means something once you inspect what was left outside the proof.

## How agents shortcut proofs

When an agent runs into a failing `dafny verify` check, it wants a green exit code by the shortest path available, and Dafny has several escape hatches that satisfy the verifier without proving what you intended.

```
// Trap 1: Unjustified assumption (verifies, but unsound when s is Approved)
lemma LateReplySafe(s: State, r: SignedReply)
  ensures !Step(s, Reply(r)).Approved?
{
  assume {:axiom} s.Expired?; // treats this condition as true without proving it
}

// Trap 2: Implementation-mirroring contract (pins code, not intent)
function CheckAuth(requiresAuth: bool, bio: bool): bool
  ensures CheckAuth(requiresAuth, bio) == (!requiresAuth || bio)
{
  !requiresAuth || bio
}
```

In `LateReplySafe`, the solver still runs, but it proves the postcondition only after assuming `s.Expired?` for free. The advertised lemma is false whenever `s` starts out `Approved`. Catching tricks like this takes more than scanning `.dfy` files for `assume`, `{:axiom}`, or `{:verify false}`. A reliable CI setup also has to check how Dafny is invoked so flags like `--no-verify` cannot slip into scripts, verify which declarations and dependencies are actually in scope, and run `dafny audit` to flag trusted constructs. One catch with `dafny audit` in Dafny 4.11 is that it can report findings while still exiting cleanly, so your script has to inspect its output rather than trusting the exit code.

`CheckAuth` is a subtler failure mode. Its postcondition still does a little work, since it pins the Boolean expression so a future edit to the body will break verification. What it cannot tell you is whether that expression matches the policy you actually wanted, because the contract simply repeats the implementation. A related move when an agent gets stuck on a failing lemma is to strengthen a `requires` clause, quietly ruling out the inconvenient case instead of fixing the transition logic.

Reviewing Dafny diffs ended up being the opposite of normal code review for me. I look at the datatype definitions and the `requires` and `ensures` changes first, before glancing at any proof body. If an agent strengthened a precondition or weakened a postcondition without being asked, I reject the diff immediately.

It also helps to break the transition logic on purpose every once in a while to test the spec itself. In `gate_trace.dfy` above, switching to **Skip auth check** leaves `Authorized` unchanged and replaces `Authorized(p, r)` in `Step` with `r.userAccepted` alone; Dafny 4.11.0 rejects it (`3 verified, 2 errors`), flagging both `r.signatureValid` and `(!p.requiresAuth || r.biometricVerified)`. Mutations that survive verification are worth reading closely too. Try the **Deadline `>` to `>=`** toggle above: changing `r.receivedAtMs > p.deadlineMs` to `r.receivedAtMs >= p.deadlineMs` still verifies cleanly (`4 verified, 0 errors`). With that edit, a reply arriving on the exact millisecond of the deadline expires the request, and neither lemma requires that reply to be approved. When a mutation survives, you have to decide whether it preserved the only property you care about or exposed a requirement you forgot to write down.

## Where formal methods didn’t help

For major new subsystems after v1.0, including Custom Native Screens and the relay’s admission and replay policies, I wrote the Dafny models before building the surrounding Worker and app code. Starting model-first worked well when I already knew the invariants I wanted, because the rest of the implementation had a fixed contract to build against. It got painful whenever product behavior was still changing rapidly. Rewriting formal specifications and repairing proofs while the design is still moving adds real drag to code that ought to stay cheap to throw away.

Even on settled code, a pure policy model only sees the typed values handed to it. If a client sends Unix seconds where the model expects milliseconds, or an edge router allows an unauthenticated HTTP request to create or write a Durable Object before the policy runs, `dafny verify` still reports zero errors. Guarding that boundary took ordinary engineering: strict runtime decoders, explicit unauthenticated storage guards, and a golden test suite pinning HTTP routing decisions so later agent refactors could not quietly alter a route.

Several of the hardest release bugs lived in behavior I had not represented in the Dafny models at all. During TestFlight builds, iOS suspended the app mid-transaction while it held shared SQLite locks across targets. You can model locking and suspension formally in principle, of course, but my small policy models did not include OS lifecycles, and fixing the bug meant protecting critical sections across background suspension.

Performance problems followed a similar pattern. After launch, the iOS inbox felt intermittently sluggish in a way that reading the code did not explain. Guessing at optimizations went nowhere, so I had the agents build an automated iOS Simulator A/B benchmark harness to test single-variable changes. Traces isolated the real cause: the foreground inbox poll was waiting on `notificationSettings` for more than half a minute before it even began fetching. Once that measurement was on screen, moving to push-invalidated stores and a foreground WebSocket delta stream let me delete the legacy polling loop altogether, cutting idle CPU and tap-to-queue latency by more than 90% and dropping thousands of redundant idle Keychain and SQLite reads down to a handful.

Cloud infrastructure behavior sat outside the policy models too. You can formalize resource bounds if you represent operations and costs explicitly, but my Dafny models did not cover Cloudflare Worker bundle size, cold-start latency, or billing dollars. Catching bundle bloat or extra Durable Object reads took deterministic local latency benchmarks and a CI cost-regression suite.

## Real-world gates and what I still review

Building a multi-platform product exclusively with AI coding agents worked for me only because I stopped relying on visual diff review alone and put concrete checks in front of each class of mistake. Dafny verified the small policy models and drove their generated TypeScript in CI, while golden tests locked down the HTTP routing boundary and simulator benchmarks plus local Worker cost harnesses caught latency and spend regressions that no static check could see.

None of that automation replaces reading the spec. Dafny shrank the amount of sensitive policy code I had to trace by hand, which made shipping AI-written code feel much less reckless, but I still had to review every specification change myself, keep the runtime code outside the models tested, and put real human approval in front of irreversible operational changes. Living in NotiBuddy every day throughout development to receive build alerts and approve long-running agent tasks caught rough edges and workflow friction long before another user would have hit them. And as that surviving deadline mutation shows, a passing proof can verify every transition in your model and still leave a real product decision wide open.
