RAII: The Guarantee That Ends at the Brace
RAII is a good mechanism. Deterministic cleanup, exception safety, no tracing collector deciding when your file closes — it earned its place. It is also the design every systems language converged on, which makes it worth auditing the way we audit everything else: not “is it bad” but “what exactly does it guarantee, and where does the guarantee stop?”
The answer is shorter than its reputation: RAII guarantees a destructor runs when a brace closes. That is a guarantee about scope. Everything past the brace — who owes the debt now, whether releasing was required or optional, which of two legal endings applied — is convention again.
What the brace actually buys you
In C++, Rust, Zig, Go, the shape repeats: a resource’s cleanup is bound to the lexical scope that holds it. The type provides a destructor; the closing brace invokes it. Uniform, unconditional, and — this is the part that made it win — impossible to forget.
But notice what the guarantee is about. The destructor is singular: one
cleanup, run the same way on every path. The type system cannot distinguish
“this handle is tracked but owes nothing” from “this handle must be settled.”
It cannot say that two different endings are both legal and the choice is yours.
And it cannot carry the debt anywhere: a resource that leaves its scope leaves
as a move, an act of ownership convention the checker does not verify as an
obligation. release(), detach(), std::optional<Guard> — the escape
hatches are silent by construction.
Koru’s phantom obligations start from a different binding. Acquiring a resource
mints a debt on the value’s type — string<held!> — and the only tors that
can settle it consume <!held> by name. The ! is a phantom state: the
compiler tracks it, nothing at runtime can see it.
The brace is incidental, not the mechanism
From the outside, Koru looks like it does RAII: leave an obligation undischarged inside a function and the compiler inserts the release at scope exit, unwinding LIFO — the same order destructors use, for the same reason.
The mechanism is inverted, though. Auto-discharge fires only when the
obligation provably does not escape the tor’s interface. Contained
obligations happen to end where the brace ends — 100% of the time — but no pass
consults the brace. The obligation is tracked program-wide, bound to the value,
and scope exit is just where a contained obligation’s tracking domain happens
to terminate.
And it only auto-fires for the unambiguous case. The stated conditions, from the inserter itself: an obligation, no discharge by the author, exactly one void disposer. Everything else is your decision:
- One void discharger, undischarged → the compiler inserts it at scope exit. This is the RAII-lookalike, and it is pinned:
One discharger that returns a value → no insertion is possible — there is no flow position at scope exit to thread a return into. Measured live this week: a sole
-> stringdischarger left undischarged produceserror[KORU030]: Resource 'm' obligation <held!> was not discharged. Call: unlock-ret. The wall doesn’t just refuse — it names the settlement you declined to write.Two dischargers → the compiler refuses to pick. Measured:
error[KORU030]: Resource 'm' <held!> has multiple discharge options: release-a, release-b. Discharge explicitly.Rust’sDropgives you exactly one discharger it calls for you, unconditionally. Koru gives you a debt with named settlements — and when the choice is semantic, the language declines to make it for you.
The thing RAII cannot say at all
Here is the claim that has no destructor-shaped answer: the same obligation can have different fates on different outcome branches. One continuation escapes the debt to the caller; a sibling discharges it on the spot. The compiler verifies each fate separately.
import std/io
pub tor lock { name: string } -> string<held!>
lock -> name
pub tor unlock { name: string<!held> }
unlock = std/io:print.ln("unlock {{ name:s }}")
// gate: one obligation, two legal endings, decided per branch.
// settled — discharged inside, plain string out
// onward — escapes to the caller still carrying <held!>
pub tor gate { mode: string }
| onward string<held!>
| settled string
gate = if(mode == "settle")
| then |> lock(name: "m"): h |> unlock(name: h) => settled "done"
| else |> lock(name: "m"): h => onward h The caller inherits the escaped debt as a typed obligation and settles it by name — or, with auto-discharge disabled, watches the wall fire:
error[KORU030]: Resource 'h2' carries obligation <held!> was not discharged.
Call: unlock Escape is not a leak. It is a tracked transfer: the -> T<found!> signature
carries the debt across the tor boundary, and the caller’s own discharge
machinery — explicit or auto — owns it from there. And the tracking itself
costs nothing at runtime: the ! is phantom, a compile-time fact erased
before emission, so an obligation leaving its scope is a type-level transfer,
not a reference-count increment or a GC root. No runtime bookkeeping stands
between the mint and the settlement — the only work that executes is the
discharge call itself, written by you or inserted by the compiler. Rust’s
move is equally free, but a move carries ownership, not a checked debt. The suite pins the same
shape at production scale: a CAS lease mints | applied string<lease!> on a
win and | rejected — a branch with no token in it — on a loss.
Custody is also graduated, which RAII has no spelling for. -> T<found> mints
a taint: tracked and typed, owes nothing, released silently at session end. -> T<found!> mints an obligation: must be spent through a <!found> consumer or the sweep fires its discharge — and a stranded obligation panics
the close while a stranded taint does not. Same underlying type, different
debt, distinguished at dispatch.
The transaction is the proof
A database transaction is the case where “cleanup” was never the point — the ending is a decision. Koru’s shootout module states it directly: acquiring a resource creates an obligation to use it meaningfully; automatic cleanup does not satisfy that.
pub tor tx.begin { conn: *Connection<!connected|!active> } -> *Transaction<started!>
pub tor tx.exec { tx: *Transaction<!started|!active>, sql: string } -> *Transaction<active!>
pub tor tx.commit { tx: *Transaction<!active> } -> *Connection<active!>
pub tor tx.rollback { tx: *Transaction<!active> } -> *Connection<active!> exec re-mints the obligation on every call — the debt threads through the
chain. commit and rollback both settle <!active>, and both return the
connection: non-void, plural settlements. Auto-discharge cannot fire — there
is no single void disposer to insert — and even if there were, choosing between
commit and rollback is semantics, not cleanup. The language structurally
incapable of silently ending your transaction is not a discipline you can
forget; it is a shape you cannot write.
For store columns the same rule is a hard wall: an owned column’s type must
expose exactly one void discharger, or the store refuses until you bolt a ! discharge arm onto the declaration that names the pick.
The cost the brace hides
RAII’s per-iteration bill is real and invisible. A guard in a hot loop pays
acquire and release every pass — heap churn, a syscall, a lock handoff — and
nothing at the call site says so: std::string s does not advertise that it
allocates, and the destructor’s work is buried in the type. You find out in a
profiler.
Koru declares the debt where the value is produced — -> string<allocated!> puts “a free is owed” in the signature — and the discharge is a named call
you can count. When the compiler does insert cleanup for you, it inserts a
named call inspectable in the emitted code. And where the boundary is
ambiguous — an obligation minted outside a loop — the compiler refuses to
guess: KORU032 (cannot auto-discharge outer-scope resource inside loop)
makes you name which side of the iteration the settlement belongs to.
The debt must be used, not just paid
RAII’s elegance is symmetry: the destructor is the constructor’s mirror image, fired at the mirrored boundary — acquire and release as inverses, scope entry and exit as the pair. It is a beautiful assumption, and it only holds for symmetric lifecycles. A transaction is not one: there is a mandatory middle (the work) and a chosen ending (commit or rollback), and neither has a mirror. And Koru does not merely tolerate that asymmetry — it is designed against the symmetry. There is no happy path to mirror: outcomes are named branches and all are peers. Custody is graduated — a taint and an obligation are different debts on the same type. Ambiguity is refused, not defaulted. Where RAII reaches for the symmetric answer, Koru insists the asymmetric one be written.
Rust’s ownership is affine: a value may be used at most once, and Drop runs
when it goes out of scope whether or not the resource was ever touched. Open a
connection and drop it unused — nothing objects. Affine types police how many
times a value moves; they cannot police what the moves meant.
Koru’s obligations are not linear — they are a state machine, and the
transitions are the meaning. connect yields Connection<connected!>; begin consumes it and starts a transaction; exec re-mints active!; commit or rollback returns Connection<active!>; and only then is close callable, because it demands <!active>. Try to close a fresh connection and
the compiler answers Phantom state mismatch — pinned as a MUST_ERROR test.
You cannot settle a debt you never incurred meaningfully: the lifecycle is
forced to be asymmetric, and “acquire then immediately release” is not a
program the type system can express.
In Rust the meaningless version still compiles: open a file, never read it,
let Drop close it. And depending on where the resource is bound,
“meaningless” shades into “leak.” Hold it in an outer scope while a message
pump runs the application, and the memory sits allocated for the process’s
whole life doing nothing — functionally what a leak is, Drop’s exit-time
cleanup notwithstanding. Open a database connection and never use it, and
depending on the driver the server holds the socket and the pool slot
regardless — a resource leak in the strictest sense. In a hot loop the same
shape is syscall churn per iteration; at startup it is a close the
operating system would have performed for free at exit. Koru’s answer is
that the meaningless program is not expressible — connected! has no edge
to close, so “open it and put it down” fails to compile before it ever
runs.
There is no exceptional path
RAII and exceptions are co-designed: the unwinder is what makes scope-exit
cleanup reliable on the paths you did not write — every throw runs every
destructor on the way out. It is a real guarantee with real edges: a
destructor that throws during unwinding terminates the program, and noexcept exists largely to police that boundary.
Koru has no exceptional path to unwind. Every outcome is a named branch —
success-shaped and failure-shaped are peers — so custody is decided per
branch, including the ones that hurt, and a discharge that fails is just
another outcome rather than invisible control flow a destructor has to
survive. The ?! branches are the honest version of the same idea: a
declared crash-loud outcome in the signature, not an unwind nobody named.
The guarantee RAII buys from the unwinder, Koru gets from exhaustiveness —
every branch settles the debt, escapes it by name, or fails to compile.
The limits
Three, named plainly, because the caveats are where the credibility lives.
The debt is in the signature, not the call site. -> string<allocated!> declares the obligation where the value is produced; the consumer sees fmt.blk { ... }: f and has to know to look. Surfacing carried debt at the
point of use is unbuilt — a real gap, not a footnote.
Auto-discharge is invisible in source. The compiler inserts std/io:free and friends; the call site does not show them. The insertion is inspectable in
emitted code and walled by KORU030 when the pick isn’t provable — but “you can
see it if you go looking” is weaker than “it was written.”
The opt-outs exist and enforcement never does. ~[strict] opts a module
out of insertion; --auto-discharge=disable does it per compilation. Both keep
the obligation visible to the checker — a leak under either still fails to
compile. What they remove is the convenience, not the guarantee.
Where the brace ends
Errors-as-values was “getting the error isn’t handling it.” This is the same
shape one level down: scope exit isn’t settlement. RAII answers “did a
destructor run?” — uniformly, locally, once. Koru answers “what was owed, on
which outcome, settled by whom?” — per branch, across tor boundaries, with
ambiguity refused at compile time and escape carried as a typed debt.
The brace still gets its moment: contained obligations get the incidental scope-exit cleanup for free, LIFO, no ceremony. But it is a convenience the obligation tracker grants, not a boundary it respects. The debt decides. The brace just happens to be where a contained debt’s tracking domain ends.