Manuscript Offprint
arXiv:2608.27798Cambria: Resource Abstraction for Parametrized Algebraic Effects and Handlers
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
JACK LIELL-COCK, University of Oxford, United Kingdom
SAM STATON, University of Oxford, United Kingdom
The algebraic effects and handlers paradigm separates the concerns of the interface and implementation of computational effects in programming languages. We present CAMBRIA, a language that extends this framework to the parametrized setting. Effect signatures may use abstract parameter types that are instantiated by the handler along with the operation implementations. Parameters abstract over resources, such as memory locations or thread IDs, permitting algebraic effects to encode dynamic allocation. They are first-class in the type system but erased at runtime, requiring no coercions or type-directed reduction.
We prove parametricity via a step-indexed logical relation, formalizing the abstraction guarantee provided by parametrized handlers. We also establish type safety and classify the annotations needed for completeness of the type inference algorithm. We demonstrate CAMBRIA's practicality with a working implementation and provide examples including local state, Pólya's urn, and concurrent thread management. The last is a parametrized effect whose abstract thread IDs are shared between concurrent computations, going beyond standard instances. CAMBRIA is the first calculus with user-defined resource-allocating effects that guarantees, via parametricity, that client code cannot depend on how a handler represents its resources.
CCS Concepts: • Theory of computation → Control primitives; Type theory; Abstraction; Operational semantics; • Software and its engineering → Functional languages.
Additional Key Words and Phrases: algebraic effects, handlers, parametricity, logical relations, resource abstraction, type inference
1 Introduction
Algebraic effects and handlers [31] provide a principled approach to programming with side effects. A computation performs abstract operations such as reading state or spawning a thread, and a handler gives these operations meaning by supplying an implementation. This separation of interface from implementation has made algebraic effects an increasingly popular foundation for effect systems in both research and practice [4, 17, 22, 25, 36].
An effect’s interface often mentions types that the client uses but should never inspect. The underlying representation is the handler’s choice alone. Local state is the classic example. Client code may allocate memory locations, and read and write through them, but it should never need to know how a location is represented. For example, a location could be an index in a list, a unique name in a map, or an opaque token from the runtime. Committing the client to a concrete representation up front buys it nothing and forces unnecessary bookkeeping. Moreover, by keeping the locations abstract, the client cannot forge new ones, inspect them for equality, or perform arithmetic on them, except through the operations the interface provides. Thus, abstraction also provides a safety guarantee.
We present CAMBRIA, a language that extends algebraic effects and handlers to the parametrized setting. Formally, parametrized handlers are derived from the theory of parametrized algebraic theories (PATs) [37, 38], which extend classic algebraic theories with the ability of operators to bind and use abstract parameters in their arguments, denoting resource allocation and usage. Then a model of the theory, or a handler, instantiates the parameter as a type, as well as interpreting the operations. This generalization was introduced to handle the problem of instances of effects, where a computational effect may dynamically allocate resources at runtime, such as new memory
Authors' Contact Information: Jack Liell-Cock, University of Oxford, Oxford, United Kingdom, jack.liell-cock@cs.ox.ac.uk; Sam Staton, University of Oxford, Oxford, United Kingdom, sam.staton@cs.ox.ac.uk.
1:2
Jack Liell-Cock and Sam Staton
locations in local state. Instances of effects are a leading case for parametrized handlers, but a parameter is more generally any abstract type that an operation introduces and a handler instantiates. We demonstrate that parametrized handlers, as the operationalization of PATs, enable idiomatic implementations of diverse effects and parameters ( ).
One approach to instances is to represent each as a concrete object in the program. Eff originally provided first-class instances in this way [4], but later removed them, and subsequent calculi recovered instances as dynamically allocated labels [7, 12], first-class names [45], or capabilities [8]. The drawback of these approaches is that either the resources are not first-class, or the representation is fixed and imposed on the client. CAMBRIA’s alternative approach to this problem separates the concerns of dispatch and instances. That is, a single handler handles all instances of the same effect, with the operators encoding an interface to multiple instances. For example, with local state, rather than having multiple copies of the !get and !set operators, we have an additional !ref operator that creates a new memory location that becomes an argument to !get and !set.
Effects such as dynamically threaded concurrency [18] and code jumps [15] go beyond independent instances. Parameters are shared and used to coordinate different sub-computations. This motivates a single handler interpreting all instances, rather than a witness distinguishing each one, and CAMBRIA provides this while keeping the parameters abstract. In the concurrency example, the effect operations encode POSIX-like fork and wait. Forking dynamically spawns a thread, the reference to which is an abstract thread ID that other processes can wait on. The ability to instantiate the abstract thread ID in the parametrized handler means that each scheduler implementation remains self-contained and simple. In §2.3, we demonstrate this with three different handlers implementing child-biased scheduling, parent-biased scheduling, and dependency diagnostics.
The key method underlying CAMBRIA is that parametrized handlers decompose into classic handlers and existential types. This lets the surface language stay ergonomic while the metatheory reduces to standard, modular pieces. The main result, parametricity, then gives representation independence for effects with dynamic resources without keeping track of allocation. The decomposition also eases adoption since a language that already provides effect handlers and existential types, such as OCaml 5 [36], can support parametrized handlers with little new core machinery. The addition is moreover backwards compatible since a handler with no parameters is exactly a classic handler.
In particular, we make the following contributions:
(1) Language design. We present CAMBRIA, a core calculus combining algebraic effect handlers, parameter variables, let-polymorphism, and general recursion, and establish type safety ( ).
(2) Parametricity. We prove a parametricity theorem via a step-indexed logical relation ( ). This rests on an elaboration result ( ) that shows parametrized handlers decompose into classic handlers and existential types.
(3) Type inference. We establish an annotation completeness result ( ) that states that it suffices to annotate only operations with arities mentioning abstract parameter types. All other types, including polymorphic ones, are inferred.
(4) Expressiveness. We demonstrate that CAMBRIA can express parametrized effects with abstraction guarantees that prior work cannot, including concurrent thread management from recent work on dynamic threads [18]. We provide an implementation with runnable examples ( ).
All results novel to CAMBRIA are mechanized in the Rocq prover, relying only on functional extensionality.
1:3
2.1 Local State and Fresh Name Generation
The canonical example of a dynamic effect is local state, where we have an additional operation !ref that allocates a reference given an initial value, along with the standard operations !get and !set that read from and write to memory locations of type $loc, where the leading dollar sign marks an abstract parameter type. The following program uses this effect to allocate two reference cells and manipulate data between them before returning the value at one of the locations.
effect !ref : Int loc Int. effect !set : \sim\leftarrow\leftarrow!ref 3 in do _ \leftarrow$ !set (a, !get b) in !get a
Note that here the effect declarations serve merely to specify the operation arities, and in particular which types are abstract parameter types (5). The effect declaration allocates nothing in itself; all generative behaviour is up to the handler of an operation such as !ref, as we see next. (See §6 for further comparison with other systems.)
The parametrized handle construct has an additional parameter substitution clause , allowing the abstract parameter types in a computation c to be instantiated before being handled by a (classic) handler h.
with h handle c
Multiple parameter instantiations are separated by commas, and the instantiation clause can be dropped when there are none, recovering the classic handle construct. In the examples that follow, we show each handler with the instantiation it is applied under, writing handler for the handler and substitution pair used in with h handle c.
We may handle the local state effect using the classic parameter passing trick for stateful effects. Rather than a global value, we choose the state to be a function from the names of our memory locations to the values that they store. The function encoding is for self-containment; any associative data structure would work equally well. The convenience of parametrized effect handlers is that we need not worry about the implementation of the memory location name, and equality checking !eq : name ~ Bool. Then, we can use another handler to implement this interface at a later stage.
[ name ] handler { return x → return (fun _ → return x), get a k → return (fun s → k (s a) s), set (a, x) k → return (fun s → k () (fun b → if !eq (a, b) then return x else s b)), ref x k → do a ← !fresh () in return (fun s → k a (fun b → if !eq (a, b) then return x else s b)), finally s → s (fun _ → return 0) }
1:4
Jack Liell-Cock and Sam Staton
}
This function encoding necessitates a default value for initialization (in this case 0), but parametricity (§4) guarantees that only locations initialized with !ref can be accessed, making this default value observationally meaningless. A genuine drawback of the encoding is that it has no means of deallocating a reference that has gone out of scope. We argue in §4.5.2 that client-transparent liveness analysis for reachability-based garbage collection would violate parametricity, and discuss alternatives.
The fresh name effect could be handled by parameter passing and incrementing an integer, concretizing the name types to integers.
[$name → Int] handler { return x → return (fun _ → return x), fresh _ k → return (fun n → k n (n+1)), eq (a,b) k → k (a == b), finally f → f 0 }
Despite the concretization, the following code handled in the same way would not type-check, because a is parametric from the perspective of the client code.
do a ← !ref 2 in !set (a+1, 3)
The following sections demonstrate that the programmer’s freedom to choose the interpretation of parameters on top of the operations leads to modular and expressive language constructs.
2.1.1 Polymorphism Meets Abstraction. Parametrized handlers support statically unbounded creation of effect instances. The number of memory locations can vary based on runtime data. Consider the following CAMBRIA program that uses a polymorphic map to allocate a memory location for each integer in a list, then uses the same function to access each location. The primitives [] and (::) are the constructors for the empty list and element prepending, while uncons : List a → Unit + a * List a unrolls the list constructor once.
effect !ref : Int ~ loc ~ Int. effect !set : $loc * Int ~ Unit. do map ← return (rec map f xs → case uncons xs of { inl _ → return [], inr (x, xs') → f x :: map f xs' }) in do vals ← return (10 :: 20 :: 30 :: []) in do refs ← map (fun n → !ref n) vals in map (fun r → !get r == 20) refs
Unbounded creation is the property that separates CAMBRIA from the lexically scoped handler calculi of [7]. This program also uses parameters under let-polymorphism, applying the polymorphic map to parameter-typed references. CAMBRIA is the first calculus in which this dynamic creation idiom enjoys a parametricity guarantee. The body cannot distinguish handler implementations that differ in how $loc is instantiated.
1:5
2.2 Two Implementations of Probabilistic Urns
Parametrized handlers allow for different implementations of the same effect interface, while preventing client code from inspecting the representation. Pólya’s urn is a probabilistic process where an urn starts by containing a red ball and a blue ball. After each sample from the urn, an additional ball of the sampled colour is placed back in the urn. That is, in the following code, the value of b2 is more likely to match b1.
do urn ← !newurn () in do b1 ← !sample urn in do b2 ← !sample urn in return (b1, b2)
In the probabilistic setting, CAMBRIA has built-in effects !bernoulli : Double ~ Bool, which returns true with probability given by the input clamped to [0, 1], and !uniform : Unit ~ Double, which samples from the uniform distribution over [0, 1]. The former command can be used to handle the urn effect via the local state effect, storing pairs of integers which track the number of red and blue balls.
[loc] handler { newurn _ k → k (!ref (1, 1)), sample urn k → do (red, blue) ← !get urn in do isRed ← !bernoulli (red / (red + blue)) in do _ ← if isRed then !set (urn, (red + 1, blue)) else !set (urn, (red, blue + 1)) in k isRed }
The parameter is instantiated to another parameter (loc) rather than a concrete type, composing the urn abstraction with the local state abstraction.
Pólya showed that sampling from this urn admits a simple equivalent process [40]: draw a single bias p uniformly from [0, 1] and then draw each sample independently from a Bernoulli distribution with that bias. Hence, we can bypass local state to produce an implementation of Pólya’s urn by instantiating $urn as a Double. This direct version is more efficient because it keeps no per-sample state and draws the bias once.
[$urn → Double] handler { newurn _ k → k (!uniform (), sample p k → k (!bernoulli p) }
Both handlers induce the same joint distribution on the returned pair. The state-based handler gives , while the direct handler gives . This is larger than the 1/4 probability of independent, fair draws. The client only sees and the operations !newurn and !sample. By parametricity, it cannot inspect their implementation. So, modulo a probabilistic lifting of the logical relation (see §4.5.1), the implementations are indistinguishable by Pólya's identity.
2.3 Dynamically Threaded Concurrency
All of the previous examples treat each parameter as an independent effect instance. Our final example of concurrent thread management [18] does not. The !fork operation uses multi-shot
1:6
Jack Liell-Cock and Sam Staton

Fig. 1. An N-shaped dependency between four actions, encoded by the dynamic thread management effect.
continuations to run both child and parent threads, and the thread IDs pass between these processes while remaining abstract. The parameter therefore coordinates distinct sub-computations rather than indexing an independent instance, warranting a single handler to interpret all of them. Another such effect is code jumps [15], which appears as an example in the implementation.
A concurrent program has four operations:
-
!fork : Unit duplicates the current process. The parent thread receives the thread ID of the child process. The child receives the unit value.
-
!wait : $tid ~ Unit stalls the current thread until the process of the provided thread ID finishes.
-
!stop : Unit Void terminates the current thread.
-
!act : Str Unit performs a labelled observable action.
The thread IDs $tid are abstract, so cannot be forged, compared, or inspected. The following program constructs an N-shaped dependency between four actions, as visualized in Figure 1.
effect !fork : Unit effect !wait : effect !stop : Unit Void. effect !act : Str Unit. case !fork () of { inl a1 case !fork () of { inl a2 case !fork () of { inl a3 !wait a2 ; !act "Action 4" ; !stop (), inr _ !wait a1 ; !wait a2 ; !act "Action 3" ; !stop () }, inr _ !act "Action 2" ; !stop () }, inr _ !act "Action 1" ; !stop () }
We illustrate the expressiveness of parametrized handlers by handling this program in three different ways. The first biases the child threads to run first, running the parent process once they are completed. The second executes the parent process first, deferring each child process until it is waited on or the parent terminates. The third handler is for diagnostics. It dispatches the concurrent operations to a secondary algebraic effect that encodes the action dependencies as a DAG.
In the child-biased implementation, the parent process only receives the child's thread ID after the child has terminated, so any subsequent !wait on that process is trivially satisfied. Therefore, the !wait operation becomes a no-op, and the thread IDs can be instantiated to Unit. The result of a returned thread is discarded, so the handler treats returning and stopping identically. When handling the program above, the actions are executed in the order 1, 2, 3, 4.
[$tid → Unit] handler {
1:7
return _ → return (), act s k → !print s ; k (), wait _ k → k (), stop _ k → return (), fork _ k → k (inr()); k (inl()) }
The parent-biased handler does not have the liberty of making !wait a no-op. It must run the child process if it hasn’t already been executed. An effective solution instantiates the thread ID as a thunk of the deferred child, Unit → Unit ! {...}, where {...} is shorthand for an effect signature left to be inferred. The thunk is guarded by a local boolean reference ensuring the child runs at most once. This instantiation may appear circular, because the captured continuation k, which may invoke the concurrency operations, is called within the thunk. But the continuation is resumed under the same handler, so those operations are caught, and the inferred effect signature only contains !print and the local-state effects !ref, !set, and !get. The latter can be handled similarly to those previously in §2.1, illustrating how parametrized handlers compose.
[$tid → Unit → Unit ! {...}] handler { return _ → return (), act s k → !print s ; k (), wait t k → t () ; k (), stop _ k → return (), fork _ k → do hasRun ← !ref false in do thunk ← return (fun _ → if !get hasRun then return () else (!set (hasRun, true) ; k (inr()) ) in ( k (inl thunk) ; thunk () ) }
The wait clause now runs its thunk before resuming, forcing the child if it hasn’t already run. At the end of the fork clause, the child thunk is forced one last time to ensure it runs even if nothing has waited on it. Returning and stopping are treated identically as before.
Applied to the same concurrent program above, the handler executes the actions in the order 2, 4, 1, 3. This is different to the child-biased handler, but still consistent with the dependency diagram in Figure 1. This second implementation relies on instantiating the thread ID type differently per handler.
If instead of running the program, we want a visual display of the action dependencies, we can implement a handler that converts the program into a DAG in Graphviz format. We handle the concurrency effect into an intermediate pomset effect [18] that is parametrized by a type of nodes. The only operation in this effect is !node : List node, which adds an extra node to the DAG. The first input is the list of dependencies of the node and the second is the node's label. The result type is the newly created node's identifier. The handler is implemented by parameter passing the list of current dependencies through the computation. Informally, each operation is implemented as follows: act calls the node command with the current dependencies and provided label and passes on the newly created node, wait extends the current dependencies with the provided dependencies, return and stop forward the dependencies, and fork runs both the parent and child thread with the current dependencies, passing the thread ID of the child to the parent.
[node] handler {
1:8
Jack Liell-Cock and Sam Staton
return _ → return (fun ds → return ds), act s k → return (fun ds → do a ← !node (ds, s) in k () (a :: [])), wait ds' k → return (fun ds → k () (concat ds ds'), stop _ k → return (fun ds → return ds), fork _ k → return (fun ds → do a ← k (inr()) ds in k (inl a) ds), finally f → f [] }
The node effect can be handled by printing the DAG represented by the node operations in Graphviz format. Rather than using a user-defined implementation of the fresh effect, we use CAMBRIA's built-in one, which generates fresh instances of the Name type. The built-in primitive hash converts each unique name to a string. The result is exactly the dependency visualization in Figure 1.
[$node → Name] handler { return _ → return (fun _ → return ()), node (ds, s) k → return (fun _ → do a ← !fresh () in ( !print (hash a ++ "[label="" ++ s ++ ""]"); map (fun d → !print (hash d ++ " → " ++ hash a)) ds ; k a ())), finally f → !print "digraph {"; f () ; !print "}" } }
Each of these three handlers instantiates the thread ID type to track completely different information.
3 The Calculus
The calculus we present for CAMBRIA includes only the constructs strictly necessary to expose the metatheory of parametrized handlers (parameters, parameter substitutions, and the parametrized handle form) along with general recursion and let-polymorphism. The implementation of CAMBRIA extends this calculus with standard data types and several surface conveniences, as discussed in §3.2. The examples of §2 make free use of these extensions.
3.1 Types and Syntax
The types of the language are inductively generated by the following grammar.
Value types A, B ::= Computation types Effect signatures Type variable context Parameter context Term context
There are three contexts: for type variables, for parameter variables, and for term variables. The only extension to the type system beyond a standard handler calculus is the parameter variables . Parameter variables can be thought of as existential type variables, because they represent an implementation detail of the effect interface. We do not allow universal quantification in operation arities, which prevents effects like heterogeneous state. This scope permits the annotation completeness result for type inference ( ), which would not hold in the polymorphic arity setting. We foresee no issues extending the type-safety and parametricity results to polymorphic arities.
1:9
The syntax of values and computations is the following.
Values
Handlers
Computations
Parameter subst.
We write fun as shorthand for rec when , where are the free variables in . Similarly, we write handler as shorthand for the handler syntax where . The key novelty is the parameter substitution in the handle term, which bridges the abstract types in the body to their concrete representations in the handler. We write for the parameter variables bound by , for the types they map to, and for the free parameter variables in .
3.2 Surface Syntax
The CAMBRIA surface language, used for the examples of §2, departs from the above calculus in a few places. These are primarily conveniences for the programmer, being more readable in practice. Each maps directly onto a calculus term, so the metatheory is unaffected.
Finally clauses. The surface admits an optional finally clause that runs after the handler returns. A handler with a finally clause desugars at handle-time: with handle becomes do (with handle ) in , where is without the finally clause. The result is a handle within a bind, so the metatheory carries through.
Operation syntax and effect declarations. The calculus writes an operation invocation as op(v; x.c), packaging the continuation x.c syntactically. The surface uses the generic effect [30] !op v, which desugars to op(v; x.return x). Hence, the calculus form op(v; x.c) is equivalent to
The surface additionally supports a local arity declaration effect !op : A B. c used only by type inference and discussed in §5.
Surface conveniences. The remaining surface forms are sugar over the calculus. These extensions are orthogonal to the metatheory, with parametricity (Theorem 4.2), type safety (Theorem 3.3), and inference (Theorem 5.5) transferring unchanged.
• Pattern matching. Irrefutable patterns are admitted in do-bindings, function arguments, and operation clauses. Pair patterns desugar to projections.
- Multi-argument functions. fun and rec desugar to nested unary abstractions.
• Sequencing. ; desugars to do in .
• Infix operators. Arithmetic (+, -, *, /), equality (==), string concatenation (++), and cons (::) desugar to applications of named primitives.
-
Implicit do. A computation in a value position is hoisted into a fresh do-binding around its enclosing computation. These are hoisted in left-to-right order. For example, elaborates to do in (do in ).
-
Default return clause. A handler with no explicit return clause uses the identity return return x.
• Built-in types and operations. The implementation provides Bool, Int, Double, Str, Name, Void, products, sums, lists, and maps, along with a small library of primitive operations including !fresh, !print, !bernoulli, and !uniform.
1:10
Jack Liell-Cock and Sam Staton
Type judgements.
Value judgements.
Computation judgements.
Fig. 2. Typing rules for CAMBRIA.
3.3 Typing Rules
The typing rules for CAMBRIA are given in Figure 2. A type judgement states that the type is well-formed in type variable context and parameter context . Value judgements are of the form and computation judgements are of the form . Both implicitly enforce that and , and the computation judgement additionally enforces that . In particular, no appears free in or in the GEN rule. This permits let-polymorphism without any value restriction [20]. Moreover, parameters are never generalized
1:11
and remain rigid within the body of a handler so that the handler can instantiate them consistently. Otherwise the abstraction boundary would break. In the HANDLER rule, handled operations do not need to cover the full set of operations in the computation effect signature. The remaining operations are forwarded, which is indicated by in the premise. The continuation captured by an operation is bound as an ordinary variable, so an operation clause may resume it any number of times, permitting multi-shot continuations.
The only non-standard type judgement is the PARHANDLE rule. The rule mirrors a classic handle rule, but the handler’s input type matches the body’s type only after the parameter substitution is applied to it. When the parameter substitution is empty ( ), the rule becomes classic handler application. When non-empty, the parameters introduced by remain confined to the handled body. That is, for , , since and are implicitly well-formed in ; . An operation whose arity mentions may still be forwarded, but it is then exposed at its instantiated arity, so does not escape. Our examples always handle such operations, but the metatheory does not require it.
3.4 Operational Semantics and Type Safety
Evaluation contexts identify where the next reduction step occurs.
Single-step reduction is defined below, closed under the congruence rule: if then .
For handler reduction, let . Then handle terms reduce as follows.
with handle return
with handle op( )
with handle op( ) op( with handle )
Reduction is deterministic because reducible computations decompose uniquely into an evaluation context and a redex. The continuation supplied to the operation clause reinstates the handler, giving deep handling [19]. In reinstated continuations, we discard the parameter substitution because it plays no role in reduction. This is the formal sense in which parameter variables are erased at runtime. There is no dynamic dispatch, no coercions, and no type-directed reduction. The parameter annotations are only used for type checking.
PROPOSITION 3.1 (PARAMETER ERASURE). Define a parameter erasure map as
and structural identity otherwise. Then is reducible if and only if is reducible. Moreover, if then .
PROOF. No rule inspects , so erasing the parameter substitutions gives a valid reduction by the same rule, establishing both results.
Type safety of a language states that well-typed terms do not get stuck. In the context of effect systems, this means a well-typed computation has reduced to a value, is control-stuck on an unhandled operation in its effect signature, or can take a reduction step. This result rests on a
1:12
Jack Liell-Cock and Sam Staton
preservation lemma that usually says reduction preserves a program’s type. In CAMBRIA, to keep reduction type-agnostic, PARHANDLE reductions discard the parameter substitution. This gives a weaker notion of preservation, but still enforces type safety.
THEOREM 3.2 (PROGRESS AND PRESERVATION). If ; ; , then either:
(1)
(2) for some op :
(3) and there is some ; ; such that .
PROOF. We first show progress by induction over the computation derivations, with canonical forms forcing the reduction steps if not a value or control-stuck operation. For preservation, we prove type substitution, parameter substitution, and variable substitution lemmas by structural induction:
• If and , then .
• If and , then .
• If and , then .
Then, for non-handler reduction, preservation follows from instantiated to d. For handler reductions, the witness reinstates the parameter substitution the reduction discarded.
• For , we take .
• For , we take .
• For , we take .
Then, since and , and erasure commutes with substitution, in all cases. By the substitution lemmas and PARHANDLE rule, these witnesses are well-typed at ; ; .
In particular, if ; ; , then case (2) is vacuous and the result reduces to the computation being a value or taking a step.
COROLLARY 3.3 (TYPE SAFETY). If ; ; and , then is a value, control-stuck on an operation in , or reducible.
PROOF. By induction on the reduction length, maintaining the invariant that every reduct carries a well-typed witness at erasing to it. The base case is , and Theorem 3.2 supplies the witness for each successor. Theorem 3.1 and determinism force the actual reduct and the witness to share a parameter-erased successor, and Theorem 3.2 applied to the witness of provides the trichotomy.
4 Parametricity
This section formalizes the abstraction guarantee that parametrized handlers provide to client code. We prove a parametricity result using a step-indexed binary logical relation (Theorem 4.2). Parametrized handlers decompose into classic handlers and existential types. Thus, the logical relation reduces to a standard combination of handlers, universal types, existential types, and recursion, with each type constructor contributing an independent clause. Since parameters are erased and their abstraction is captured by a single relation, the construction is direct, needing neither a biorthogonal definition of the computation relation [5], nor Kripke worlds which are required for a full mutable heap [2].
We formalize the decomposition as an elaboration into a core calculus ( ) and prove the parametricity theorem on the core. Adequacy transports the result back to CAMBRIA.
1:13
4.1 The Core Language
Parametrized handlers can intuitively be thought of as first packing the concrete parameter instantiation into an existential type, and then handling the abstract computation. That is, a handle with a single parameter substitution elaborates along the following lines.
with , v handle c unpack pack( , A, v) as in (with x handle c)
This decomposition is formalized in §4.3. Before proceeding, we introduce the syntax of the core language, the target language of the elaboration. We update the handle syntax and extend the value types, values and computations with the following constructs in place of the parametrized handle term (with , v handle c) in §3.1.
Value types
Values
Computations
Parameter substitutions are no longer part of the syntax in the core language. Core judgements, denoted with , have a new typing derivation for existential types and, in place of the PARHANDLE rule, we have a plain handle rule, as well as existential introduction and elimination rules.
In the UNPACK rule, because and implicitly hold in the conclusion.
The operational semantics replaces parametrized handler reduction with classic handler reduction and adds a new reduction rule for existential terms, inheriting the remaining rules. Let , then the core language reductions on the new constructs are as follows.
with handle return
with handle op(; ) ()
with handle op(; ) op(; . with handle ) ()
unpack pack(, , ) as in
A classic handle evaluation frame replaces the parametrized one.
Core language reduction is written , distinguishing it from CAMBRIA reduction . We further annotate core reductions with for principal steps and for administrative steps. The only administrative step is the existential elimination, which has no runtime content. In CAMBRIA, this distinction collapses into the single parametrized handle reduction, as formalized in Theorem 4.6.
4.2 Step-Indexed Logical Relation and Fundamental Theorem
A logical relation builds a model of a calculus to capture an explicit property. Each type is interpreted as a relation between pairs of closed terms, capturing when two terms are indistinguishable at that type. We build a step-indexed logical relation [1, 3] over the core language to show that contextual equivalence is parametric over the type variables and parameters. The formal result is the fundamental theorem (Theorem 4.2), which states that every well-typed term is related to itself.
1:14
Jack Liell-Cock and Sam Staton
uniformly across all admissible interpretations of its free variables. Thus, the parameters cannot be inspected or used outside of the interfaces to the effects.
As parametrized handlers decompose into well-known constructs, the clauses of the step-indexed logical relation are standard. While we only introduce the relation on the core syntax, it extends to empty, product, sum, and list types, and all of the features in the current version of CAMBRIA. This includes row polymorphism [21, 23], which is already utilized for effect inference in the current type system. Instantiating row variables to closed signatures gives the present relation, and row generalization is handled exactly like type generalization. Since parameters and row variables are disjoint with independent substitution, the two features compose. For features not yet supported in the implementation, such as recursive types [1] and universal quantification in operation arities [34], we expect the parametricity result to generalize given the separation of concerns between parameters, type variables, and step-indexing. We leave this to future work.
The step-indexing is necessary for general recursion, and integrates well with handlers. Each operation observation strictly decreases the index, making the self-reference well-founded without resorting to induction over the size of the computation trees. Since captured continuations are bound as ordinary variables and the relation is downward-closed in the step index, each resumption is related, and multi-shot continuations need no special treatment. The step index tracks whether two terms can be discerned within that number of computation steps, so the relation is refined as the step index grows.
Definition 4.1. An admissible relation is a step-indexed relation on closed value terms , an element of which we write , that is downward-closed: if and , then . We write for the set of all admissible relations.
Given a type context and parameter context , a relational interpretation assigns an admissible relation to each type variable and parameter. The logical relation assigns to each typing judgement a mapping from relational interpretations to an admissible relation, written as . When the type variable and parameter contexts are closed , the interpretation is the unique map on the empty domain, so we drop the subscript. The logical relation is defined inductively over the typing judgements and step index.
(with handle , with handle )
Two closed computations are related at step index if they remain observationally equivalent after reduction steps. That is, if for all :
• If return , then there is such that return and
• If for , then there are and such that and:
Cambria: Resource Abstraction for Parametrized Algebraic Effects and Handlers 1:15 – ∀𝑗 < 𝑛−𝑖. ∀(𝑤1,𝑤2)𝑗 ∈ J𝐵opK𝜌 . (𝑑1 [𝑤1/𝑦], 𝑑2 [𝑤2/𝑦])𝑗 ∈ J𝐴 ! ΣK𝜌 The step index tracks reductions on the left, giving an asymmetric approximating relation. The self-reference of J𝐴 ! ΣK𝜌 is well-founded because the index strictly reduces. As in the value case, computations are related at a universally quantified return type if they are related for every relational interpretation of the bound variables. J∀®𝛼.𝐴 ! ΣK𝜌 = {(𝑐1, 𝑐2)𝑛 | ∀𝜌 ′ ∈ Rel𝛼® . (𝑐1, 𝑐2)𝑛 ∈ J𝐴 ! ΣK𝜌 [𝜌 ′ ] } The fundamental theorem states that this relation holds for every well-typed term. Theorem 4.2 (Fundamental Theorem). If Θ; Ψ; Γ ⊢c 𝑡 : 𝑋, then for all 𝜌 : Θ ∪ Ψ → Rel, 𝑛 ∈ N, and (𝛾1,𝛾2)𝑛 ∈ JΓK𝜌 , (𝑡[𝛾1], 𝑡[𝛾2])𝑛 ∈ J𝑋K𝜌 . Proof. The proof rests on three lemmas. For each, let 𝜌 : Θ ∪ Ψ → Rel be a relational interpretation for type contexts Θ; Ψ. • Monotonicity: For all Θ; Ψ ⊢c 𝑋, if (𝑥1, 𝑥2)𝑛 ∈ J𝑋K𝜌 and 𝑛 ′ ≤ 𝑛, then (𝑥1, 𝑥2)𝑛 ′ ∈ J𝑋K𝜌 . This is proved by induction over the definition of the logical relation J−K𝜌 . • Anti-reduction: For all Θ; Ψ ⊢c 𝐶, if 𝑐1 ⇝𝑖 𝑐 ′ 1 , 𝑐2 ⇝∗ 𝑐 ′ 2 , and (𝑐 ′ 1 , 𝑐′ 2 )𝑛 ∈ J𝐶K𝜌 , then (𝑐1, 𝑐2)𝑛+𝑖 ∈ J𝐶K𝜌 . This holds because reduction is deterministic. • Substitution: For Θ, 𝛼; Ψ ⊢c 𝑋 and Θ; Ψ ⊢c 𝐴, J𝑋 [𝐴/𝛼]K𝜌 = J𝑋K𝜌 [𝛼↦→J𝐴K𝜌 ] . Equivalently for substitution of parameter variables. This is also proved by induction over the definition of the logical relation. Then the fundamental theorem is proved by induction over the value and computation typing judgements. The insight that parametrized handlers decompose into classic handlers and existential types makes all of these cases standard. Nevertheless, we highlight the key ones. Rec and Handler: By inner induction on 𝑛 with the same pattern. The inner IH gives the recursive occurrences related at 𝑛−1, the structural IH relates the bodies after a step, and antireduction lifts this back to 𝑛. For the handler, the return case is straightforward. For an operation op : 𝐴op → 𝐵op ∈ Σ, the handle term reduces either to its operation clause applied to the deep continuation (fun 𝑦 ↦→ with ℎ handle 𝑐) if handled, or to op(𝑣; 𝑦.with ℎ handle 𝑐) if forwarded. In both cases the inner IH relates the continuations one step index lower. Do: Via the bind lemma (Theorem 4.3). Gen: For any 𝜌 ′ ∈ Rel𝛼® , using 𝛼® ∉ fv(Γ, Σ), we can weaken to (𝛾1,𝛾2)𝑛 ∈ JΓK𝜌 [𝜌 ′ ] . Then we use the IH to conclude the computations are in J𝐴 ! ΣK𝜌 [𝜌 ′ ] . Pack: The IH gives (𝑣[𝛾1], 𝑣[𝛾2])𝑛 ∈ J𝐵[𝐴/𝜓]K𝜌 . Taking 𝑅 = J𝐴K𝜌 as the existential witness, admissible by monotonicity, the packed values are related at J∃𝜓 .𝐵K𝜌 by the substitution lemma. Unpack: The IH on 𝑣 yields packed witnesses pack(𝜓, 𝐵𝑘,𝑤𝑘 ) (for 𝑘 ∈ {1, 2}), together with some 𝑅 ∈ Rel relating 𝑤1,𝑤2 at J𝐴K𝜌 [𝜓↦→𝑅] . The IH on 𝑐 at the extended contexts puts the bodies in J𝐶K𝜌 [𝜓↦→𝑅] = J𝐶K𝜌 (using 𝜓 ∉ fpv(𝐶)), and anti-reduction lifts this to the unpack terms. □ Lemma 4.3 (Bind Lemma). If (𝑐1, 𝑐2)𝑛 ∈ J∀®𝛼.𝐴 ! ΣK𝜌 and for all 𝑖 ≤ 𝑛 and (𝑣1, 𝑣2)𝑖 ∈ J∀®𝛼.𝐴K𝜌 we have (𝑑1 [𝑣1/𝑥], 𝑑2 [𝑣2/𝑥])𝑖 ∈ J𝐵 ! ΣK𝜌 , then (do 𝑥 ← 𝑐1 in 𝑑1, do 𝑥 ← 𝑐2 in 𝑑2)𝑛 ∈ J𝐵 ! ΣK𝜌 . Proof. We prove the lemma via strong induction on 𝑛. If 𝑐1 ⇝𝑖 return 𝑣1 for some 𝑖 < 𝑛, then the bind reduces to 𝑑1 [𝑣1/𝑥] after 𝑖+1 steps. Then 𝑐2 ⇝∗ return 𝑣2 with (𝑣1, 𝑣2)𝑛−𝑖 ∈ J∀®𝛼.𝐴K𝜌 , the lemma premise gives (𝑑1 [𝑣1/𝑥], 𝑑2 [𝑣2/𝑥])𝑛−𝑖−1 ∈ J𝐵 ! ΣK𝜌 , and anti-reduction and monotonicity lift this back to 𝑛. If instead 𝑐1 ⇝𝑖 op(𝑣1; 𝑦.𝑐′ 1 ) for some 𝑖 < 𝑛, the bind reduces to op(𝑣1; 𝑦.do 𝑥 ← 𝑐 ′ 1 in 𝑑1) after 𝑖+1 steps. Then 𝑐2 ⇝∗ op(𝑣2; 𝑦.𝑐′ 2 ) with (𝑣1, 𝑣2)𝑛−𝑖 ∈ J𝐴opK𝜌 and continuations
1:16
Jack Liell-Cock and Sam Staton
related for . The inner IH applies to (do in , do in ) at this strictly lower index, and anti-reduction again lifts this back to .
4.3 Elaboration from CAMBRIA and Operational Correspondence
The fundamental theorem applies to the core language. To transfer parametricity to CAMBRIA, we need to connect the two calculi via an elaboration. We define such an elaboration and show that it is faithful. Hence, the fundamental theorem is reflected by CAMBRIA, and the abstract interfaces of the parametrized handlers are formally guaranteed.
Definition 4.4. The elaboration translation from CAMBRIA’s syntax to the core syntax is given by structural identity on all terms, apart from the parametrized handle clause, where it is defined inductively over the size of the parameter substitution.
(with , handle ) = unpack pack( , , ) as ( , ) in (with , handle )
This elaboration preserves typing judgements, and is thus well-defined.
PROPOSITION 4.5 (TYPE PRESERVATION). If , then .
PROOF. The only non-trivial case is the PARHANDLE elaboration. This is proved by inner induction on the parameter substitution. When , the rule is exactly the classic handler rule. When , unwinding the typing derivation gives:
After invoking the structural IH, as , we can derive
and weakening , gives,
Then, combining (1) and (2) we can derive
where we invoked the IH on (with handle .
This elaboration is sound up to administrative reduction. A step in CAMBRIA forces a step by its elaboration, modulo the existential unpackings which carry no runtime content. That is, each step is matched by some administrative steps from each elaboration, with a final principal step to close the gap.
PROPOSITION 4.6 (OPERATIONAL CORRESPONDENCE). Define a simulation relation when the elaborations and share a common reduct , with and . Then implies .
PROOF. We first show by induction that (with handle (with handle ). For , this is immediate after zero reductions. For ,
(with , handle as in (with handle
(with handle
with handle
(IH)
1:17
For the reduction rules, the only non-trivial cases are handler reductions. Elaboration is structural identity on all other terms, so principal steps correspond exactly to CAMBRIA steps, and witnesses . For handle where is a terminal form,
c^{\dagger}\leadsto_{a}^{*}\mathrm{w i t h}h^{\dagger}\mathrm{h a n d l e}c_{t}^{\dagger}\leadsto_{p}c^{\prime}^{\dagger}because parametrized handling reinstates and elaboration commutes with substitution. So witnesses .
Finally, we show that implies by induction on the evaluation context. The base case is immediate, and the do context follows directly from the IH because elaboration is again structural identity. For handle , assume witnessed by . Then,
So (with handle ) witnesses .
Since the elaboration produces only classic handlers and existential types, and reduces to a classic handler when , a language offering these two features needs no new core constructs to extend support to parametrized handlers.
4.4 Contextual Equivalence and Adequacy of the Logical Relation
The operational correspondence allows us to state the logical relation over CAMBRIA terms via their elaborations. To reason with it, we connect the logical relation to the standard notion of program equivalence in CAMBRIA, contextual equivalence. We define two programs to be contextually equivalent when no context can distinguish their behaviour. In the presence of general recursion, it is enough to observe termination, since any behavioural difference can be converted to divergence on one side. Hence, two programs are contextually equivalent when, in any context, one terminates if and only if the other does.
Definition 4.7. In CAMBRIA, a computation context is a computation with a hole in it.
Given a well-typed computation , a closing context for is a computation context such that . Given two well-typed computations , they are contextually equivalent, written , if for all closing contexts ,
Adequacy states that the logical relation captures this notion of contextual equivalence in CAMBRIA. In particular, if any two elaborated, well-typed CAMBRIA terms are in the logical relation for any relational interpretation, step index, and environment substitutions, then they are contextually equivalent. This is achieved via a plugging lemma which propagates the logical relation through any computation context, bridging the fundamental theorem to contextual equivalence.
LEMMA 4.8 (PLUGGING LEMMA). If for all , and , we have
then for any computation context , where , we have for all , and ,
1:18
Jack Liell-Cock and Sam Staton
PROOF. The proof is by structural induction on the computation context. In each case, the fundamental theorem (Theorem 4.2) relates non-hole subterms to themselves, and the IH relates the subcontext. The only non-standard case is (with , v handle ), which uses inner induction on . The base case proceeds with the same pattern (relating non-hole terms via Theorem 4.2 and subcontexts via the IH). The inductive case elaborates as
(with , v handle ) = unpack pack( , , ) as ( , ) in (with , handle ) ,
which reduces back to (with handle ) , and we use the inner IH to relate the two terms after environment substitutions.
The logical relation is asymmetric because the step index tracks reductions on one side, capturing step-bounded approximate behaviour. The approximation becomes a full bidirectional equivalence for a relational interpretation when for all , and , where is the relational interpretation inverted pointwise. In this case we write .
THEOREM 4.9 (ADEQUACY). Let . Suppose for all relational interpretations and related environments , we have . Then .
PROOF. Let be any context where . By Theorem 4.8 applied in both directions,
Hence, by definition of the logical relation, terminates at return () if and only if does, because the operation signature is empty and the only elements of are . Next, we show for ,
The forward direction is given by repeated application of Theorem 4.6 using that core reductions are deterministic. In the reverse direction, each CAMBRIA step induces at least one core step (Theorem 4.6), so the finite deterministic core trace implies a finite CAMBRIA trace. By Theorem 3.3, the CAMBRIA reduction terminates at return (), the only terminal form of type Unit ! 0. Thus from (3) and (4), .
4.5 Applications of Parametricity
Beyond the standard free theorems [42] provided by parametricity results, two consequences are key in the parametrized handler setting: representation independence between parametrized handler implementations and the ability to reason equationally within the parametrized effect theories. We present each as an implication of Theorem 4.2, illustrating them with the examples from §2.1.
4.5.1 Representation Independence for Parametrized Handlers. Two implementations of the same parametrized effect should be indistinguishable to client code that only interacts through its abstract interface. Parametricity guarantees this. If any two handlers agree up to an admissible relation on the parameter, the handled computations are observationally equivalent.
COROLLARY 4.10. Let and be two well-typed parameter substitutions, and let
1:19
Suppose that for every relational interpretation and related environment , there exists an admissible relation such that
Then (with handle c) (with handle c).
Proof. Let and . By Theorem 4.9, we require
Let be the witness for (5). Since , . By Theorem 4.2 applied in both directions, with the inverse relational interpretation for the reverse,
The handler clause of the logical relation gives
(with handle , with handle )
as . Finally,
(with handle as in (with handle )
(with handle ).
So by anti-reduction, (6) holds.
This result extends to substitutions of multiple parameters by induction on . The elaboration unfolds into nested unpack-pack layers, each contributing one step. The proof is otherwise unchanged.
Example 4.11. We sketch a use case of Theorem 4.10 for two implementations of the fresh effect. Take to be the fresh effect handler from §2.1 with and take to be a string-counter variant with :
handler { return x return (fun _ return x), fresh _ k return (fun s k s ("x" + s)), eq (a,b) k k (a == b), finally f f "" }
producing the sequence of strings "", "x", "xx", ... for the names.
We choose the admissible relation , where "x"i is the string of i copies of x. The clauses of the handlers satisfy this choice of R and its inverse because:
-
return each produces a function ignoring the parameter, so the results are related.
-
fresh applied to related i and "x"i invokes the continuation on this pair, and the resulting function is applied to related i+1 and "x"i+1.
-
eq applied to related arguments and gives related booleans because is injective in both directions.
So the two implementations agree up to R, satisfying the premise of Theorem 4.10. Hence, any body that uses the fresh effect is observationally equivalent under and .
1:20
Jack Liell-Cock and Sam Staton
The relation may do work beyond bijective encodings. The two implementations of Pólya’s urn from §2.2 are such an example. The first stores the urn’s state as a pair of integers in a memory location while the other uses a single double, with the witnessing a coupling between a cell holding state and a draw from the Beta distribution . The deterministic logical relation already accounts for half of the equivalence, where the abstraction over ensures that no client can observe which representation a handler uses. But it does not establish that the two handlers satisfy because !uniform and !bernoulli are not part of the core calculus (§3). The handlers sample differently, only agreeing in distribution by conjugacy of the Beta prior to Bernoulli observations [40]. That is, matches the predictive probability of red, and conditioning on a draw updates it to or , matching the urn update. So, parametricity reduces the proof obligation to the conjugacy coupling and the implementation of the probabilistic primitives. Making this formal requires lifting the logical relation along a probability monad, replacing membership in an admissible relation with a coupling lifting [16] and re-establishing anti-reduction and compositionality for the lifted relation (e.g. via entropy-passing semantics [9, 43]), which we leave to future work.
In contrast, the three dynamic thread handlers from §2.3 are not representation independent of one another because they differ in their scheduling strategies. The child-biased and parent-biased handlers choose different orderings for the threads, so while each is a sound interpretation of the operations, they are not observationally equivalent. Theorem 4.10 can still be used to relate handlers with the same scheduling strategy differing in the representation of tid → Int] is observationally equivalent to the child-biased handler of §2.3 that uses Unit, since the client cannot inspect the thread ID.
[$tid → Int] handler { ... fork _ k → k (inr()); k (inl 57) }
4.5.2 Equational Properties of Parametrized Handlers. A standard use of effect handlers is to verify implementations against the equational laws of the effect theory. With local state, initializing a reference then immediately overwriting it should be equivalent to initializing it to the latter value.
Under a function-based handler, both sides reduce to a function with a pointing to w, and the equivalence follows.
Equations where a different number of resources are allocated on each side are subtler. The garbage collection law states that allocating a reference and never using it is equivalent to having never allocated it.
(a \notin \mathrm{fv}(c))
Under the function-based handler, the two sides produce functions that differ at a. A proof would have to show that this entry is unobservable, and parametricity provides exactly this argument. We demonstrate the law for the fresh effect.
Example 4.12. Let , where , , and . Then
with
where is the integer parameter passing fresh effect handler from §2.1.
1:21
PROOF. Elaborating each side, the existential layer reduces to a plain handle, and the finally clause of feeds the handler's output to the application 0. On the right, the fresh command is handled, incrementing the counter by one. As , each side respectively reduces to
where is the handler without the finally clause, typed at with . So the problem reduces to showing .
We let and choose the admissible relation . This choice of maintains the relatedness of the handlers much like in Theorem 4.11. The return clause produces a function constant in the parameter argument, fresh maps the related pair to the related pair , and eq is invariant because +1 is injective in both directions. So .
Let , since . By the fundamental theorem (Theorem 4.2) applied in both directions (inverting for the reverse),
Since at every step index, the function relation and bind lemma (Theorem 4.3) give
since . Then anti-reduction lifts this to the original computations, and adequacy to contextual equivalence in CAMBRIA.
Parametricity and Reachability Analysis. Theorem 4.12 states that allocating an unused reference is observationally undetectable. However, the function-based handler of §2.1 retains the entry for that reference forever, since nothing signals when a reference has gone out of scope. While observationally harmless, it is a form of memory leak because the value persists throughout the entire body of the handle. This behaviour is unavoidable. A standard free theorem implies that naive liveness detection and parametricity are incompatible.
COROLLARY 4.13 (VACUOUSNESS [42]). Any closed CAMBRIA function of type where is not free in A is extensionally constant. It returns the same value (or diverges) for every input.
Any garbage-collection scheme that determines liveness from references occurring in the captured continuation requires a primitive that accepts the continuation as an arbitrary value (to work uniformly across handler instantiations), and produces an output with type independent of the polymorphic input. For example, the following are the type signatures for the primitives isReachable, which computes whether a reference Ref is still reachable in a continuation, liveRefs, which finds the live references in a continuation, and onUnreachable, which registers a finalizer to fire when a reference becomes unreachable.
isReachable : Va. a → (Ref → Bool ! {} ) ! {}
liveRefs : Va. a → List Ref ! {}
onUnreachable : Va. a → (Ref * (Unit → Unit ! {} ) → Unit ! {} ) ! {}
By Theorem 4.13, such primitives cannot perform non-trivial liveness analysis.
Reachability-based garbage collection for parametric local state is thus beyond the scope of this paper. Substructural typing, regions, and built-in reference effects remain possible alternatives, which we discuss in §7.
1:22
Jack Liell-Cock and Sam Staton
5 Type Inference
So far we have established CAMBRIA’s type safety and parametricity. We now show that parametrized handlers are also practical, introducing only a minimal annotation burden. Since parameters abstract concrete types within the body of a handle, annotations are necessary to indicate which types are intended to be abstracted. The main result of this section, Theorem 5.5, is that it suffices to annotate only the operation arities that introduce new parameters. The type checker can infer everything else.
Inference for CAMBRIA follows Algorithm W for Hindley–Milner type systems [10, 27], extended to effects [32]. The inference algorithm uses row variables [21, 23], which may appear at the end of effect signatures and are required to encode operations not yet observed at that program point. The algorithm traverses the syntax tree, unifying value types and effect rows eagerly, and generalizing at each Do binding. There is no value restriction at generalization, which is sound in this setting [20], because only variables not free in the environment or effect row are generalized, and recursive functions are monomorphic. An operation invocation !op v adds op to the effect row with fresh arity, unifying the input with the type of v and the output with the type of !op v. Using an effect declaration (§3.2) unifies the declared arity with the operation in the effect row, if it exists. Handler clauses are checked as in the declarative HANDLER rule, with the shared answer type and output row found by unification. The forwarding side condition is discharged by unifying the output row with the input row variable and unhandled operations, rather than a separate subset test.
The only construct that departs from established inference is PARHANDLE. Parameters only enter the body through type or effect declarations. Unification, denoted , treats each parameter as an additional rigid constant, distinguishing them from unification variables. That is, a parameter only unifies with itself and fails against any other type, including a distinct parameter. At a handle term, the algorithm applies to the inferred body type and unifies the result against the handler's input type. The no-escape condition of PARHANDLE is an additional side condition ensuring no parameter has leaked into the context or result type via unification. We write to indicate the algorithm infers for .
PARHANDLE
This is the new machinery in total. The remaining inference is ordinary Algorithm W with the parameters treated as constants. The algorithm is syntax-directed and terminating, hence decidable, and unifying value types and effect rows has principal solutions, being first-order unification [10] and row unification [21, 23] with parameters as constants.
We establish principality of CAMBRIA by showing soundness and completeness of the inference algorithm. Soundness states that every type inferred by the algorithm is derivable in the declarative system. Hence, the algorithm accepts only well-typed programs that have the type-safety and parametricity guarantees. Completeness, treated next, characterizes the annotations for which the algorithm infers the most general derivable type for a computation.
THEOREM 5.1 (SOUNDNESS). If , then .
PROOF. CAMBRIA type inference differs from Hindley–Milner with effect handlers only in the handle rule generalized to the PARHANDLE rule. Since parameters are rigid, unification remains sound, and all remaining cases follow from established proofs [10, 20, 32].
For PARHANDLE (with , handle ), the IH on gives a derivable handler type . The IH on gives a derivable body type , with dom( ) rigid in . Unifying against the handler's input
1:23
restricts them to be equal, where the types in are well-formed. For the no-escape condition, the algorithm explicitly checks that , so with handle is derivable.
We write when arises from by substituting value types for its type variables and closed signatures for its row variables. Closing the row variables recovers the closed-row typing of §3. We develop completeness in three stages. The first states that any term that does not introduce a parameter is inferable without any annotations because inference is exactly Algorithm W with effect handlers.
LEMMA 5.2 (GROUND COMPLETENESS). Let every handle expression in have . If , then with .
PROOF. Inference over this fragment is identical to Algorithm W with effects, for which completeness has been established [10, 32].
In the full parametrized system, an annotated term is one in which every handle expression carries an explicit type annotation on the body.
with handle
LEMMA 5.3 (PARAMETRIZED COMPLETENESS). Let be an annotated term. If , then with .
PROOF. By structural induction on the typing derivation. All cases apart from PARHANDLE follow the Hindley–Milner argument for algebraic effects [10, 32]. Since parameters are rigid and never generalized, unification and generalization arguments are unaffected. In particular, gen-admissibility [10] still holds, so Do is unchanged.
The only interesting case is PARHANDLE: with handle . By the IH, the algorithm infers a handler type such that . The body is then checked against the annotation with rigid in , and the algorithm unifies . Since unification returns the most general solution, the final inferred output type satisfies .
The annotation in Theorem 5.3 uses the full type of the body. We strengthen this to a relevant annotation consisting only of the operations that mention the introduced parameters. This result relies on operation arities being monomorphic ( ). Additional annotations would be required for universally quantified arities, and we leave the interplay of polymorphic and parameter annotations to future work.
Definition 5.4. Given a parameter substitution , the -relevant operations of are
A relevantly annotated term is one in which each handle expression carries an annotation listing only the -relevant operations, with handle . The return type and all other operations are omitted. Note that this partial annotation is possible via effect declarations ( ).
THEOREM 5.5 (RELEVANT COMPLETENESS). Let be a relevantly annotated term. If , then with .
PROOF. We extend the proof of Theorem 5.3, strengthening the PARHANDLE case to show that from the relevant annotations, the algorithm infers a type at least as general as the body’s declarative type. The handle introduces into as rigid constants, and the operations split into two kinds:
1:24
Jack Liell-Cock and Sam Staton
(1) -relevant. These arities are supplied by the annotation, so they are typed exactly as in Theorem 5.3.
(2) -free. For any such op : , we have , so is the identity on the arity, and the op is inferred as in the unparametrized system with no annotation.
Return type. A value or type mentioning can enter the body only through a -relevant operation. Hence, once the -relevant operations are annotated, every is fixed wherever it flows. The return type of the body is then inferred with the parameters acting as fixed base types.
Thus, the annotation burden is minimal. The local-state example of §2.1 is annotated only with the three -relevant arities !get : , !set : , and !ref : Int , which is enough to infer the type of the whole program. Moreover, the relevant annotation is a term-independent sufficient condition. Operations in may be omitted from annotations when propagates to their arity via term-level flow. For example, annotating only !set in
effect !set : $loc * Int ~ Unit.
do x ← !ref 3 in !set (x, 4)
permits the algorithm to infer the arity of !ref is Int . For this reason, CAMBRIA enforces no constraints on which operations need to be annotated, letting the programmer manage the interface with individual effect declarations.
6 Related Work
Algebraic effects and handlers. Algebraic effects were introduced by Plotkin and Power [30] and equipped with handlers by Plotkin and Pretnar [31]. They are now incorporated in numerous languages, such as Eff [4], Koka [22], Frank [25], Links [17], and OCaml 5 [36]. Handlers in OCaml 5 are widely deployed, but the language does not track effect use in its type system; the focus is rather on handlers as a control mechanism. CAMBRIA is closest in spirit to the fine-grained call-by-value calculus of Kammar et al. [20], whose type-safety results we extend to the parametrized setting.
Parametrized algebraic theories. CAMBRIA is inspired by parametrized algebraic theories [37, 38] (PATs), where operations may bind and use abstract parameters, giving an algebraic account of effects that allocate resources. PATs have been used to axiomatize a range of effects, including local state [38], code jumps [15], the Beta-Bernoulli process [40], quantum measurement [39], and scoped effects [24]. CAMBRIA complements this line of work by realizing it in the algebraic effects and handlers framework, with parametricity enforcing the abstraction layer. Concretely, an operation returning a parameter, such as !fresh : Unit , is the generic effect [30] of a PAT operation that binds that parameter in its continuation. Another recent realization, Paella [35], is an Idris 2 library that models dynamically allocated resources through a Kripke possible-world semantics, where types are indexed by the resources currently allocated. CAMBRIA addresses the same setting as a stand-alone calculus where parameters are abstract types erased at runtime, and it establishes parametricity rather than providing a semantic framework.
Effect instances and named handlers. The problem of instances, where effects dynamically allocate resources, has motivated a substantial line of work. Eff originally had first-class effect instances [4], but removed them because the dynamic correspondence between operations and handlers complicated reasoning. Subsequent calculi recovered instances by a range of methods, including dynamically allocated labels [7, 12] and capability passing [8]. As a practical language, Koka [21] uses named handlers [44, 45], which expose each instance as a first-class name passed as evidence at runtime. This can model dynamically allocated heaps with first-class references, and
1:25
rank-2 polymorphism scopes the instances to prevent leakage. In each of the approaches above, the instance is a concrete object in the program. CAMBRIA takes a different approach, separating dispatch from instances. A handler interprets all instances of an effect, and the resource is exposed only as an abstract parameter that the handler instantiates. Thus, CAMBRIA guarantees representation independence over the user-defined resource. Moreover, there is no type-directed reduction, and since a parameter is a genuine type rather than a witness bound to an instance, a single handler can coordinate distinct instances, as in the dynamic threads ( ) and jump [15] effects.
Parametricity and logical relations. Parametricity [33] is the source of CAMBRIA’s abstraction guarantees, stemming from reading parameters as existential types [29] and data abstraction as representation independence [28]. We establish this through a step-indexed logical relation [3], which was extended to recursive and quantified types by Ahmed [1], and which we adapt to handlers. This has been done biorthogonally [5] by coupling the computation relation to the evaluation contexts, and abstraction over effect signatures has separately been obtained through a type discipline [6]. We move the abstraction to resource identifiers and take the direct approach, where each type contributes an independent clause and new features are local.
Reasoning about dynamic allocation. Relational models with dynamic allocation often require Kripke logical relations indexed by possible worlds, such as in generative, state-dependent ADTs [2], or fresh-name generation in the v-calculus [47]. CAMBRIA has similar guarantees for local state and fresh-name effects ( ) without appealing to possible worlds. The relational interpretation of the parameter type plays the role that worlds play for a primitive full mutable heap. Complementary to our type-based guarantees are program logics for handlers, such as the Hazel separation logic [11] and its relational counterpart Blaze [13], which, on a per-program basis, verify properties of handler programs over real mutable state and, for Blaze, concurrency.
Concurrent effects. Kammar et al. [18] develop an equational theory for dynamic threads as an algebraic effect, using concrete thread IDs without type abstraction. CAMBRIA’s parameter variables make thread IDs abstract, giving parametricity guarantees and idiomatic handlers ( ) for concurrent programs.
7 Conclusion
We have presented CAMBRIA, a calculus that extends algebraic effects and handlers with parameters to provide type abstraction for resource-allocating effects. Parameter variables are first-class in the type system but play no role at runtime. A step-indexed logical relation establishes parametricity, where client code cannot inspect the concrete representation of the parameter outside of the effect interfaces. The decomposition of parametrized handlers into ordinary handlers and existential types means that the surface language stays ergonomic while the metatheory reduces to standard, modular pieces.
We have demonstrated CAMBRIA’s expressiveness with examples including local state, Pólya’s urn, and concurrent thread management. The calculus is type safe and backwards compatible, and type inference stays practical, as demonstrated in the implementation, with only effect arities mentioning parameters needing annotations. These results are backed by a mechanization in the Rocq prover. In the dynamic threads example, the thread IDs go beyond standard instances by coordinating concurrent processes. Yet they remain abstract, providing a representation-independence guarantee.
Future work. Natural extensions include substructural parameters to incorporate quantum effects [39] and scoped effects [24]. Such parameters could also address the reachability limitation of §4.5.2, alongside built-in references and region-based memory management [26, 41]. A probabilistic semantics would also allow internalization of de Finetti-style representation equivalences like
1:26
Jack Liell-Cock and Sam Staton
the one between the two Pólya urn handlers (§2.2). We are also interested in whether parameter abstraction offers an alternative to tunnelling [46], preventing effect-polymorphic code from accidentally handling effects it is unaware of. Other directions include refining the type system to be bidirectional [14, 25], and a denotational semantics to establish the categorical structure of parametrized handlers.
References
[1] Amal Ahmed. 2006. Step-Indexed Syntactic Logical Relations for Recursive and Quantified Types. In Proc. ESOP '06. https://doi.org/10.1007/11693024_6
[2] Amal Ahmed, Derek Dreyer, and Andreas Rossberg. 2009. State-Dependent Representation Independence. In Proc. POPL '09. https://doi.org/10.1145/1480881.1480925
[3] Andrew Appel and David McAllester. 2001. An Indexed Model of Recursive Types for Foundational Proof-Carrying Code. TOPLAS (2001). https://doi.org/10.1145/504709.504712
[4] Andrej Bauer and Matija Pretnar. 2015. Programming with Algebraic Effects and Handlers. J. Log. Algebra. Methods Program. (2015). https://doi.org/10.1016/j.jlamp.2014.02.001
[5] Dariusz Biernacki, Maciej Piróg, Piotr Polesiuk, and Filip Sieczkowski. 2018. Handle with Care: Relational Interpretation of Algebraic Effects and Handlers. In Proc. POPL '18. https://doi.org/10.1145/3158096
[6] Dariusz Biernacki, Maciej Piróg, Piotr Polesiuk, and Filip Sieczkowski. 2019. Abstracting Algebraic Effects. In Proc. POPL '19. https://doi.org/10.1145/3290319
[7] Dariusz Biernacki, Maciej Piróg, Piotr Polesiuk, and Filip Sieczkowski. 2020. Binders by Day, Labels by Night: Effect Instances via Lexically Scoped Handlers. In Proc. POPL '20. https://doi.org/10.1145/3371116
[8] Jonathan Immanuel Brachthäuser, Philipp Schuster, and Klaus Ostermann. 2020. Effects as Capabilities: Effect Handlers and Lightweight Effect Polymorphism. In Proc. OOPSLA '20. https://doi.org/10.1145/3428194
[9] Ryan Culpepper and Andrew Cobb. 2017. Contextual Equivalence for Probabilistic Programs with Continuous Random Variables and Scoring. In Proc. ESOP '17. https://doi.org/10.1007/978-3-662-54434-1_14
[10] Luís Damas and Robin Milner. 1982. Principal Type-Schemes for Functional Programs. In Proc. POPL '82. https://doi.org/10.1145/582153.582176
[11] Paulo Emilio de Vilhena and François Pottier. 2021. A Separation Logic for Effect Handlers. In Proc. POPL '21. https://doi.org/10.1145/3434314
[12] Paulo Emilio de Vilhena and François Pottier. 2023. A Type System for Effect Handlers and Dynamic Labels. In Proc. ESOP '23. https://doi.org/10.1007/978-3-031-30044-8_9
[13] Paulo Emilio de Vilhena, Simcha van Collem, Ines Wright, and Robbert Krebbers. 2026. A Relational Separation Logic for Effect Handlers. In Proc. POPL '26. https://doi.org/10.1145/3776676
[14] Jana Dunfield and Neel Krishnaswami. 2021. Bidirectional Typing. CSUR (2021). https://doi.org/10.1145/3450952
[15] Marcelo Fiore and Sam Staton. 2014. Substitution, jumps, and algebraic effects. In Proc. LICS '14. https://doi.org/10.1145/2603088.2603163
[16] Simon Oddershede Gregersen, Alejandro Aguirre, Philipp G. Haselwarter, Joseph Tassarotti, and Lars Birkedal. 2024. Asynchronous Probabilistic Couplings in Higher-Order Separation Logic. In Proc. POPL '24. https://doi.org/10.1145/3632868
[17] Daniel Hillerström and Sam Lindley. 2016. Liberating Effects with Rows and Handlers. In Proc. TyDe '16. https://doi.org/10.1145/2976022.2976033
[18] Ohad Kammar, Jack Liell-Cock, Sam Lindley, Cristina Matache, and Sam Staton. 2026. An equational axiomatization of dynamic threads via algebraic effects. In Proc. POPL '26. https://doi.org/10.1145/3776706
[19] Ohad Kammar, Sam Lindley, and Nicolas Oury. 2013. Handlers in Action. In Proc. ICFP '13. https://doi.org/10.1145/2500365.2500590
[20] Ohad Kammar and Matija Pretnar. 2017. No Value Restriction is Needed for Algebraic Effects and Handlers. J. Funct. Program. (2017). https://doi.org/10.1017/S0956796816000320
[21] Daan Leijen. 2014. Koka: Programming with Row Polymorphic Effect Types. In Proc. MSFP '14. https://doi.org/10.4204/EPTCS.153.8
[22] Daan Leijen. 2017. Type Directed Compilation of Row-Typed Algebraic Effects. In Proc. POPL '17. https://doi.org/10.1145/3009837.3009872
[23] Sam Lindley and James Cheney. 2012. Row-based effect types for database integration. In Proc. TLDI '12. https://doi.org/10.1145/2103786.2103798
[24] Sam Lindley, Cristina Matache, Sean Moss, Sam Staton, Nicolas Wu, and Zhixuan Yang. 2024. Scoped Effects as Parameterized Algebraic Theories. In Proc. ESOP '24. https://doi.org/10.1007/978-3-031-57262-3_1
1:27
[25] Sam Lindley, Conor McBride, and Craig McLaughlin. 2017. Do be do be do. In Proc. POPL '17. https://doi.org/10.1145/3009837.3009897
[26] Anton Lorenzen, Leo White, Stephen Dolan, Richard A. Eisenberg, and Sam Lindley. 2024. Oxidizing OCaml with Modal Memory Management. In Proc. ICFP '24. https://doi.org/10.1145/3674642
[27] Robin Milner. 1978. A Theory of Type Polymorphism in Programming. J. Comput. Syst. Sci. 17, 3 (1978). https://doi.org/10.1016/0022-0000(78)90014-4
[28] John C. Mitchell. 1986. Representation Independence and Data Abstraction. In Proc. POPL '86. https://doi.org/10.1145/512644.512669
[29] John C. Mitchell and Gordon Plotkin. 1988. Abstract Types Have Existential Type. TOPLAS (1988). https://doi.org/10.1145/44501.45065
[30] Gordon Plotkin and John Power. 2003. Algebraic Operations and Generic Effects. Appl. Categ. Struct. (2003). https://doi.org/10.1023/A:1023064908962
[31] Gordon Plotkin and Matija Pretnar. 2009. Handlers of Algebraic Effects. In Proc. ESOP '09. https://doi.org/10.1007/978-3-642-00590-9_7
[32] Matija Pretnar. 2014. Inferring Algebraic Effects. Log. Methods Comput. Sci. (2014). https://doi.org/10.2168/LMCS-10(3:21)2014
[33] John Reynolds. 1983. Types, Abstraction and Parametric Polymorphism. In Proc. IFIP Congress '83.
[34] Taro Sekiyama and Atsushi Igarashi. 2019. Handling Polymorphic Algebraic Effects. In Proc. ESOP '19. https://doi.org/10.1007/978-3-030-17184-1_13
[35] Jesse Sigal, Ohad Kammar, Cristina Matache, and Conor McBride. 2024. Paella: Algebraic Effects with Parameters and their Handlers. In Proc. HOPE '24 Workshop at ICFP. Slides available on author's webpage..
[36] K. C. Sivaramakrishnan, Stephen Dolan, Leo White, Tom Kelly, Sadiq Jaffer, and Anil Madhavapeddy. 2021. Retrofitting effect handlers onto OCaml. In Proc. PLDI '21. https://doi.org/10.1145/3453483.3454039
[37] Sam Staton. 2013. An Algebraic Presentation of Predicate Logic (Extended Abstract). In Proc. FoSSaCS '13. https://doi.org/10.1007/978-3-642-37075-5_26
[38] Sam Staton. 2013. Instances of Computational Effects: An Algebraic Perspective. In Proc. LICS '13. https://doi.org/10.1109/LICS.2013.58
[39] Sam Staton. 2015. Algebraic Effects, Linearity, and Quantum Programming Languages. In Proc. POPL '15. https://doi.org/10.1145/2676726.2676999
[40] Sam Staton, Dario Stein, Hongseok Yang, Nathanael Ackerman, Cameron Freer, and Daniel Roy. 2018. The Beta-Bernoulli process and algebraic effects. In Proc. ICALP '18. https://doi.org/10.4230/LIPIcs.ICALP.2018.141
[41] Mads Tofte and Jean-Pierre Talpin. 1997. Region-Based Memory Management. Inf. Comput. (1997). https://doi.org/10.1006/inco.1996.2613
[42] Philip Wadler. 1989. Theorems for free!. In Proc. FPCA '89. https://doi.org/10.1145/99370.99404
[43] Mitchell Wand, Ryan Culpepper, Theophilos Giannakopoulos, and Andrew Cobb. 2018. Contextual Equivalence for a Probabilistic Language with Continuous Random Variables and Recursion. In Proc. ICFP '18. https://doi.org/10.1145/3236782
[44] Ningning Xie, Jonathan Immanuel Brachthäuser, Daniel Hillerström, Philipp Schuster, and Daan Leijen. 2020. Effect Handlers, Evidently. In Proc. ICFP '20. https://doi.org/10.1145/3408981
[45] Ningning Xie, Youyou Cong, Kazuki Ikemori, and Daan Leijen. 2022. First-Class Names for Effect Handlers. In Proc. OOPSLA '22. https://doi.org/10.1145/3563289
[46] Yizhou Zhang and Andrew C. Myers. 2019. Abstraction-Safe Effect Handlers via Tunneling. In Proc. POPL '19. https://doi.org/10.1145/3290318
[47] Yu Zhang and David Nowak. 2003. Logical Relations for Dynamic Name Creation. In Proc. CSL '03. https://doi.org/10.1007/978-3-540-45220-1_48