Type systems allow us to eliminate entire classes of bugs at compile time. They've become an almost indispensable tool in the era of agentic programming. However, this usually means verifying only basic properties, such as that a Person cannot be used where an Organization is expected, or that Money is a different concept from an attemptNumber: Int field.
We can do much better! Type systems can offer more than support for record types, sum types, newtypes, or type polymorphism, while retaining practicality. Rust is a good example that reached the mainstream: its type system additionally verifies memory & resource safety, enabled by ownership and lifetime annotations.
What about memory-managed languages, where memory safety doesn't need to be verified? Maybe we can spend the type system complexity budget to eliminate other classes of bugs? Especially now that it might be enough to point coding agents to the relevant docs and reap the benefits.
That's the space that Scala explores. The language has a history of adding type system features that go well beyond the basics, e.g., path-dependent, intersection and union types. All in a production-grade setting.
And Scala pushes forward: a new type-level feature, capture checking, is close to graduating from experimental status. Capture checking allows tracking how values of "interesting" types are retained in the object graph. If you know Rust, think of it as a generalized version of lifetime tracking.
Let's take a tour of how Scala enhances compile-time verification by gradually improving a function's signature. No prior Scala knowledge is required.
Structured concurrency
Our running example will be concurrency-related, an area which is notoriously hard to get right. Specifically, we'll use structured concurrency and verify that relevant abstractions are used properly—either by an agent or a human.
If you're not yet familiar with structured concurrency, I recommend this article to get up to speed. In short: the central concept is a structured concurrency scope, in which new threads of execution can be started, and which guarantees that however the scope ends, all threads started within will be terminated (successfully, with an error, or forcefully, using cancellation/interruption); threads cannot leak from a scope.
For a concrete implementation, we'll use Scala's Ox library, which will become capture-checked once capture checking becomes stable. Here we'll examine how this can be done for a single method, fork.
In Ox, a concurrency scope is created with supervised, accepting a code block in which new threads can be created using fork. In turn, fork accepts a code block which runs the thread's logic. For example:
The above code runs two code blocks in parallel and waits until both are done. (The same can be done in a more compact way, but using structured concurrency scopes as above offers the most flexibility and illustrates best what we'll be talking about.)
1. Forking can only happen within a scope
The first interesting property that is enforced by the compiler—available today, not leveraging capture checking—is that fork can only be invoked inside a supervised block. This is done with the help of context functions and implicit parameters:
Code blocks are passed as by-name parameters (evaluated lazily, like a zero-argument function). For example, def fork(t: => Unit) defines a method which accepts an arbitrary code block, the result of which is discarded. Similarly, def supervised[T](t: => T): T would define a method which accepts a code block, whose result becomes the result of the entire method.
There are some additional type annotations. First, we've got trait Ox: think of its instances as a "permission to fork". That permission is available only within a supervised scope: it's illegal to start forks (threads) outside of a scope, as that would break the structured concurrency guarantee.
The type Ox ?=> T is a context function whose Ox parameter is passed implicitly. This makes the "boilerplate-y" parameter more ergonomic to use: you don't have to mention it explicitly; it's automatically passed where it's required. Think of it as value inference, similar to type inference.
Such a signature requires that the code block passed to supervised has to be provided with an Ox instance. The scope has to mint a new permission and pass it to the t block of code, which may start threads.
The Ox implicit parameter then flows into fork, which requires a "permission to fork" instance through the using Ox constraint. In Scala, a method can have multiple parameter lists, and some of them can be passed automatically.
Try it! You can run the following example with scala-cli using a single command: scala-cli compile [file name.sc]. The //>using directive tells the runner which Scala version to use, and is unrelated to the using that's part of fork's parameter list. You should get a compile error:
On the other hand, this compiles just fine:
(It won't work when run because the implementations of supervised and fork are missing, but the code structure is correct.)
2. Forking cannot escape from scopes
The above design has some holes. For example, it's easy to leak the permission to fork outside of the concurrency scope. Below we do it by returning an anonymous function, which creates a fork when called:
When you call result(), the scope is already done, so you can't start new forks inside. This would cause a runtime exception. How can we prevent such leaks?
The core of the problem is that we have returned a value—an instance of the Function trait—that stores a reference to the Ox "permission to fork". The permission instance is added automatically by the compiler as a parameter to the fork invocation, so it's not even visible in the code.
Are implicit parameters the wrong tool here, making the mistake harder to spot? That's not where the problem lies: even with an explicit parameter, we'd have to rely on code review and discipline, not the compiler, to spot invalid programs.
Luckily, there's a better solution: Scala offers a way to verify at compile time that the value returned by supervised doesn't capture—that is, doesn't store a reference to—values that are marked as being of "special interest". In our case, the value that we are interested in tracking is Ox—the "permission to fork".
Such values are called capabilities, and are marked in code by suffixing the type with ^ (e.g., Ox^), or by making the type extend a capability marker trait (trait Ox extends SharedCapability). For a more precise description of what capabilities are and how capture checking works, refer to the Understanding capture checking article and Scala's documentation on the subject.
Using the type Ox^, or using SharedCapability (shared, as aliasing is unconstrained; this is in contrast to ExclusiveCapability, introduced later), means that the compiler will track whether any value captures (stores a reference to) its instances. With that modification, the code from the previous example is rejected. As capture checking is experimental, it needs to be enabled with an explicit compiler option:
The compile error is caused by the Ox capability escaping its scope: the instance only exists inside the invocation of the t block:
Above, contextual$1 is a compiler-generated name for the implicit (and unnamed) Ox parameter. What reasoning does the compiler use to reject this code?
The result of the supervised block is a function value (a lambda) that calls the fork method. Since fork needs the Ox capability, the lambda holds a reference to it. Hence, the type of the value returned from the scope represents a function that captures a capability.
The compiler then attempts to assign the same type to the result value. The type would have to express the fact that it's a function capturing the Ox instance. However, this is not possible, since the instance cannot be referenced (by name) from outside the supervised scope. That's why the compiler reports that the Ox instance leaks to the outside environment.
3. Fork instances cannot escape either
Our design is still not 100% foolproof. We can leak Fork instances:
That shouldn't be possible—at the moment we obtain the f value, the scope is already done, and by the definition of a concurrency scope, all forks are completed or interrupted.
The solution is to track Fork instances by making them capabilities and using capture checking. Through error messages, the compiler would guide us towards the best solution during development. This relies on an important rule: every value that captures a capability becomes a capability itself.
In the real implementation, instances of Ox are not only a "permission to fork" but also hold the state of the concurrency scope. Because of that, Fork instances need to hold references to Ox, as joining the fork requires interacting with the scope. Following the rule above, returned Fork instances become capabilities as well.
This fact requires us to suffix the type with ^, that is, use Fork^ (or to make Fork extend SharedCapability). But such a type is also very general; it means not only that the Fork instance is a capability, but also that it captures some unknown set of capabilities.
However, here we know precisely what capabilities are captured: the Ox instance. We can specify this in code by naming the implicit Ox parameter and writing the type as Fork^{ox}:
The compiler error is caused by the same problem as before: since Fork contains a reference to ox, returning it from the scope would cause the ox instance to outlive its scope.
We introduced some notation, but under the hood, every Scala type has some capture set. A value is a capability if its type has a non-empty capture set. ^ is only a shorthand:
4. Mixing early-return & concurrency scopes
Scala has a library function that uses scoping similar to what we see in Ox: boundary-break, which offers an early-return mechanism. For example, in this function, the break is used to return from the enclosing boundary, jumping out of the loop:
Internally, this is implemented with exceptions (which might be optimized away by the compiler), but the user should never see them. The mechanism is the same as with concurrency scopes. boundary corresponds to supervised, and provides a "permission to break" to the code block through an implicit Label instance (which corresponds to Ox).
That way, break can only be called if a Label was passed implicitly, that is, within a boundary. Crucially, Label is a capability, so the compiler tracks its retention.
There are legitimate cases where boundary-break can be combined with supervised-fork: e.g., creating a boundary entirely contained within a fork. But there are also problematic cases, e.g.:
While this is lexically valid, it's semantically wrong, since the call to break inside the fork doesn't really have an enclosing boundary. It will run on a separate thread—possibly long after the surrounding boundary is done—and the thrown exception is never caught by the boundary.
fork's parameter, t: => Unit, accepts any code block, including one that captures a Label. To restrict that, we need a more precise function type. In general, values of type A => B are functions that can capture anything. In fact, they are capabilities themselves, as their types have a non-empty capture set.
There are ways to relax this. A value of type A -> B (thin arrow) denotes a function which doesn't capture anything. In other words, it's a pure function. If we model all side effects through capabilities, seeing a pure function means we can be sure it has none.
There's also a middle ground: functions which capture some known set of capabilities. These are written down as A ->{ox, label} B. Such a function captures the ox and label instances, and nothing else. Hence we have the following equivalences:
Going back to our problem: to say that certain interleavings of fork and break are not correct, we need to restrict the code blocks that can be passed to fork. Only those that do not capture any "permissions to break" (Label instances) should be allowed.
This would rule out the code above: in our simplistic example, the code passed to fork is break(1), which captures the label through an implicit parameter—as the definition of break is def break[T](value: T)(using Label[T]).
We can say that a function cannot capture some capabilities, albeit a bit more broadly, by excluding an entire class of capabilities from the allowed capture set. Scala lets us classify capabilities by role using marker traits. One such classifier is Control, a trait for any control-flow-related capabilities, such as Label (which allows calling break—hence influencing the control flow). So the (simplified) definition of Label would be: trait Label extends Control, where Control extends both SharedCapability and Classifier.
The exclusions are specified using the .except modifier, which can be used in capture sets and accepts only capability classifiers.
Summing up, we have three ingredients:
any, which means "any arbitrary set of capabilities"control-flow capabilities classified using the
Controlclassifierexclusion using the
.exceptmodifier for a certain class of capabilities
Combining those, we get this signature of fork:
Which reads as: fork accepts code blocks that can capture anything, except control-flow capabilities. That is, capturing an instance of a hypothetical Network capability, classified otherwise, is fine. Capturing a Label is not. Try it yourself:
5. Dealing with mutability
There's one more way to create concurrent & buggy code that we can eliminate. This time, following Rust closely, we'll deal with mutability. Separation checking, which builds on capture checking, tracks mutable data usage. While capture checking is close to stable, separation checking is in an earlier development stage.
Let's consider the following:
The problem is accessing x from both the main thread & the fork: an instance of unsynchronized shared mutable state, perfect conditions for data races.
With separation checking, each mutable variable becomes a capability, represented using Var. Here, x is associated with a Var[Int] capability, which is used to track its usages.
Label is classified as a Control capability. Similarly, Var is classified as Unscoped (the name is quite technical and might change), and extends ExclusiveCapability. Exclusive capabilities have special handling when separation checking is turned on. In contrast to "shared", and as the "exclusive" name suggests, aliasing for such capabilities is tracked, and the compiler verifies that, e.g., mutating method calls are only allowed through a single alias.
Simply turning on separation checking isn't sufficient: Scala doesn't know (and cannot know) how and where the provided code blocks are run. Even if we separation-checked the underlying implementation, we still need to specify the behavior of the thread-starting primitives at some point.
How do we enhance the signature of fork to make sure that shared mutable state is only used safely? One way would be to exclude all Unscoped capabilities from being captured by the fork:
But that's too restrictive; the following code is fine, as x is not accessed by the main thread later:
So we need a way to say that the ownership of any exclusive capabilities captured by the fork's body is transferred to the fork. This is done with a new keyword introduced by separation checking, consume. As a result, x, an exclusive capability captured by the code block passed to a consume parameter, can't be used anymore after the method call. The mechanism is very similar to Rust's move.
The following now reports a compile-time error. Note that you'll need to save the file with a .scala extension, and we're using a nightly build of Scala 3.10, since this combination of features is under active development, with some rough edges only ironed out in the latest snapshots.
This approach to verifying concurrent code has its limits: it would be safe to access x in the main thread after joining the fork. However, separation checking is conservative here and rejects such code.
Evolution of fork
We've evolved the signature of our forking method from:
To:
Such a signature reveals a lot about the function:
it can only be run within a scope, which provides a "permission to fork" (an
Oxinstance)that permission is a tracked capability, which cannot leak outside of its scope
the
Forkinstance being returned is a tracked capability itself, capturing the current concurrency context (Ox)the body of the fork cannot use any control-flow capabilities
the body of the fork takes over ownership of any exclusive capabilities, such as mutable state used within
This significantly reduces the ways fork can be misused—increasing safety in the crucial area of concurrency. And yes, capture checking makes the type system more complex, and is still experimental. However, as it matures, human developers can benefit from richer information in method signatures, while agents can do the grunt work of figuring out the right type annotations and fixing the code where needed.
We've run initial experiments introducing capture checking to larger codebases, e.g., in Orca; pointing the LLMs to the user manual was enough for them to use the feature effectively. We'll cover this in detail in a future article. So our job might be to tell the agents to use capture checking to partially verify certain properties of our code—such as that shared mutable state cannot be used incorrectly, or that the structured concurrency rules are respected.
If we don't need to squeeze out the very last bit of performance & memory usage, using a memory-managed language frees up some complexity budget. Let's spend it on eliminating the less-trivial classes of bugs. Capture checking lays a solid foundation for doing just that.

