Zero-Cost POSIX Compliance: Encoding the Socket State Machine in Lean's Types

Bug-proof sockets without slowdown? Fans cheer, skeptics say 'just use types'

TLDR: A Lean 4 demo encodes socket steps into types so you can’t call the wrong function and still run at C speed. Commenters spar over whether that needs a proof system, how it survives real OS weirdness like EINPROGRESS, and even roast the post as “AI slop.”

A new post shows how Lean 4 can make “wrong-order” socket calls impossible by encoding states (fresh → bound → listening → connected → closed) right into the type of the socket. Translation for non-nerds: it tries to make network mistakes illegal before the program even runs, while keeping the speed of plain C. The community? Oh, they brought the popcorn.

On one side, true believers are hyped about “zero-cost safety.” On the other, skeptics ask if this really needs a proof-heavy language: one top comment basically says, “couldn’t regular types do this?” Another fires a warning flare about ownership and resource discipline, noting Lean lacks special rules to force you to hand over the old handle; without that, you could keep a stale socket and still cause chaos. And the realism police show up: what about messy OS quirks like EINPROGRESS when a connection is in limbo? “Your neat diagram meets real-world mayhem,” snarks one commenter.

Then it gets spicy. A pedant corrects the post: calling socket ops wrong in C isn’t “undefined behavior,” it’s just an error — the kernel spits back an errno. Another commenter plugs a new typestate language. And the biggest clapback? “Boo AI slop,” accusing the author of using AI without editing. The memes write themselves: “Type police vs socket chaos,” “No runtime checks? No mercy,” and a lot of “prove it” energy around whether the elegance survives real networks.

Key Points

  • The POSIX socket protocol is modeled as a five-state, seven-transition state machine in Lean 4.
  • Socket state is a phantom type parameter erased at runtime, yielding zero overhead versus raw C.
  • Each API function encodes required input state and resulting output state, enforced by the Lean kernel at compile time.
  • Double-close is prevented by requiring a proof that the socket is not already closed; this proof is auto-discharged except for the closed case, which fails to type-check.
  • Proofs are erased during compilation, so no runtime checks or branches are emitted in the generated code.

Hottest takes

"Couldn't you do that in a more conventional type/class system?" — yjftsjthsd-h
"boo AI slop. If you’re going to use AI... please edit" — wk_end
"Does this work in the face of state changing out from under the socket?" — diowldxiks
Made with <3 by @siedrix and @shesho from CDMX. Powered by Forge&Hive.