Skip to content

10. Effects and handlers

An algebraic effect is an operation that a computation requests without saying how it is carried out, and a handler is the code that answers the request and resumes the computation (Plotkin and Power, 2003; Plotkin and Pretnar, 2009; Bauer and Pretnar, 2015). Pyro builds its inference on the same separation: one model, run under different handlers, draws a fresh value, conditions on an observation, or replays a recorded value (Pyro's effect handlers) (Pyro Developers, n.d.-d). Declare an operation shrink, which asks for an adjusted value, and give it an interpretation with a handler.

When a computation runs perform robust.shrink(8.0), it pauses. The rest of the computation, waiting for the answer, is the continuation. A handler that answers resume(4.0) passes 4.0 to the continuation as the result of perform. QVR uses three notions:

  • An effect (interface) lists operations and their types.
  • An effect instance is one named occurrence of an effect, so two instances of one interface can be handled differently.
  • An effect row lists the instances a computation may still perform. Handling an instance completely removes it from the row.

1. Declare the request

effect Robust
    shrink : Real -> Real

instance robust : Robust

define robust_request(x : Real) : Real !{robust | rho lacks robust} =
    let adjusted <- perform robust.shrink(x)
    return adjusted

Robust is the effect and robust an instance of it. The row !{robust | rho lacks robust} says that robust_request performs robust and passes through whatever other instances the caller's row rho holds. A row with such a variable tail is open, and abstracting over the tail is row polymorphism (Leijen, 2014). The constraint lacks robust keeps rho from naming robust a second time.

2. Write an authored handler

effect Robust
    shrink : Real -> Real

instance robust : Robust

handler half_weight for Robust : Real -> Real [coverage=total, forwards=none, implementation=authored]
    return x =>
        return x
    shrink(x : Real) resumes 1 =>
        resume(0.5 * x)

define robustify(x : Real) : Real !{} =
    handle robust with half_weight in
        let adjusted <- perform robust.shrink(x)
        return adjusted

The handler's options say that it has a clause for every operation of Robust (coverage=total), that it passes no request on to an outer handler (forwards=none), and that its clauses are written in QVR (implementation=authored). The return clause passes the final value through unchanged. The clause for shrink resumes the continuation with half its argument, and resumes 1 declares that it resumes exactly once. Since the handler covers robust completely, the row of robustify is empty (!{}), and the computation continues under the same handler after each resume, as a deep handler does (Kammar et al., 2013). The handler options list the alternatives.

3. Check the row

The complete source is authored-handler.qvr. Ask the REPL for the rows of both computations:

$ qvr repl docs/tutorials/qvr/source/authored-handler.qvr
qvr> :effects robust_request
qvr> :effects robustify

The row of robust_request keeps robust, and that of robustify is empty. qvr run can thus run robustify on the reference machine, the library's interpreter for the core language, the Quivers Indexed Effect Core (QIEC) (chapter 9), with no handler from outside:

qvr run docs/tutorials/qvr/source/authored-handler.qvr robustify 8.0 --trace

From Python, with the trace of the run:

from quivers.dsl import load

effects = load("docs/tutorials/qvr/source/authored-handler.qvr")
run = effects.run("robustify", 8.0)
assert run.value == 4.0

events = [event.event for event in run.result.trace]
assert "operation.requested" in events
assert "operation.handled" in events
assert "resumption.invoked" in events
print(run.value, events)
4.0 ['run.started', 'runtime.attached', 'argument.validated', 'handler.entered', 'operation.requested', 'operation.handled', 'clause.entered', 'resumption.invoked', 'handler.returned', 'clause.answered', 'run.completed']

The trace records the request, the dispatch to the handler, the entry into the clause, the resumption, and the final answer. Each event also carries the source location and the identifiers of the declarations involved.

4. Choose a resumption grade

A resumption grade states how many times a clause may resume its continuation. The grades are the usage annotations of substructural type systems and quantitative type theory (Atkey, 2018):

Grade Resumptions Typical use
0 never aborting, or replacing the rest of the computation
aff (affine) at most once a clause that may discard the continuation
1 (linear) exactly once answering a request, as half_weight does, or a state update
omega (unrestricted) any number search that resumes once for each alternative

Grades 0, aff, and 1 make the continuation one-shot. omega makes it multi-shot. Declare the most restrictive grade that the policy allows. The reference machine counts resumptions at run time, so a clause declared 1 that resumes twice fails. A multi-shot resumption also needs a context that can be copied, and an accumulator such as the weight collector of a generated parser (chapter 11) is copied for each resumption.

5. Decide between authored and foreign handlers

An authored handler has its clause bodies written in QVR, so it can be inspected, serialized, and emitted to a transpile target that supports its operations. A foreign handler declares only its type, and a provider, an object registered with the runtime, gives its behavior when the module runs. This is the role of a foreign function interface. Use a foreign handler for a sampler, a PyTorch module, a database, or another resource that lives only in the running Python process. Write [implementation=foreign] and omit the clause bodies. Omitting them without that option is an error.

A process that loads the serialized module must install a provider for each foreign handler. The runtime configuration selects the provider by name, and the Python callables themselves are never serialized (foreign handlers and providers).

6. Carry state in the handler

A handler's parameters carry values from one request to the next (Leijen, 2017). They are typed binders written after the answer type. handle gives their first values, every clause reads them, and resume(v) with (e) gives the values they have while the continuation runs. The module below is a small model of discourse reference in the style of effect-driven semantics. A sentence may introduce a referent (introduce), a definite description reads the latest one (latest), and a description whose referent is not positive has no value (undefined):

from quivers.dsl import loads

DISCOURSE = """
effect Store
    latest : Unit -> Real
    introduce : Real -> Unit

effect Failure
    undefined : Unit -> Real

instance referents : Store
instance presupposition : Failure

handler remembering for Store : Real -> Real with (r : Real) [coverage=total, forwards=none, implementation=authored]
    return x =>
        return x
    latest resumes 1 =>
        resume(r)
    introduce(v : Real) resumes 1 =>
        resume() with (v)

handler floored for Failure : Real -> Real with (floor : Real) [coverage=total, forwards=none, implementation=authored]
    return x =>
        return x
    undefined resumes 0 =>
        return floor

define definite() : Real !{presupposition, referents} =
    let x <- perform referents.latest()
    let checked <- positive(x)
    return checked

define positive(x : Real) : Real !{presupposition} =
    if x > 0.0 then
        return x
    else
        let y <- perform presupposition.undefined()
        return y

define discourse(a : Real) : Real !{presupposition, referents} =
    perform referents.introduce(2.0 * a)
    let d <- definite()
    return d + a

define judged(a : Real) : Real !{} =
    handle presupposition with floored(0.0 - 1.0) in
        handle referents with remembering(0.0) in
            let m <- discourse(a)
            return m

object Trial : FinSet 4

program judgments : Trial -> Trial
    let a <- sample Normal(loc=0.0, scale=1.0)
    let m <- judged(a)
    observe y : Trial <- Normal(loc=m, scale=1.0)
    return y

export judgments
"""
model = loads(DISCOURSE)
assert model.run("judged", 0.5).value == 1.5
assert model.run("judged", -0.5).value == -1.0

remembering starts with the referent 0.0, and its clause for introduce resumes with the new one in its place. floored discards the rest of the computation when a description has no value and answers its parameter floor in place of it. So judged(0.5) introduces 1.0, reads it back, and returns 1.5, while judged(-0.5) returns the floor.

7. Fit a program whose meaning is stated with effects

The program judgments calls judged, which installs handlers, and the compiled runtime and Stan run none. Both read judged with its handlers discharged: each request is replaced by the answer of its clause, and the request under the if by a choice between the rest of the computation and the floor. The program thus has gradients, and it transpiles to Stan with no handler in it:

import torch
from quivers.dsl.parser import parse
from quivers.inference import MCMC, NUTSKernel
from quivers.transpile import transpile

y = torch.tensor([1.4, 0.9, 1.8, 1.1])
fit = MCMC(NUTSKernel(max_tree_depth=4), num_warmup=50, num_samples=50, seed=0).run(
    model.morphism, torch.zeros(1, 1), {"y": y}
)
assert fit.samples["a"].isfinite().all()

stan = transpile(parse(DISCOURSE), target="stan").decode()
assert "?" in stan and "handle" not in stan

The order of the handlers is part of the analysis, since each request is answered by the innermost handler of its instance and a clause runs outside its own handler. Which calls are fit lists the calls that are discharged and the ones that are refused.

Next

Chapter 11 uses multi-shot handlers to search over parses. The effect reference lists the built-in effects, rows, options, and failure modes.

Cited sources

Gordon Plotkin and John Power. Algebraic Operations and Generic Effects. Applied Categorical Structures, 11:69–94, 2003. URL: https://link.springer.com/article/10.1023/A:1023064908962, doi:10.1023/A:1023064908962.

Gordon Plotkin and Matija Pretnar. Handlers of Algebraic Effects. In Programming Languages and Systems, volume 5502 of Lecture Notes in Computer Science, 80–94. Springer, 2009. URL: https://link.springer.com/chapter/10.1007/978-3-642-00590-9_7, doi:10.1007/978-3-642-00590-9_7.

Andrej Bauer and Matija Pretnar. Programming with Algebraic Effects and Handlers. Journal of Logical and Algebraic Methods in Programming, 84(1):108–123, 2015. URL: https://www.sciencedirect.com/science/article/pii/S2352220814000194, doi:10.1016/j.jlamp.2014.02.001.

Pyro Developers. Poutine: a guide to programming with effect handlers in Pyro. Pyro Tutorials, version 1.9.1, n.d.-d. URL: https://pyro.ai/examples/effect_handlers.html (visited on 2026-11-06).

Daan Leijen. Koka: Programming with Row Polymorphic Effect Types. In Proceedings of the 5th Workshop on Mathematically Structured Functional Programming (MSFP), volume 153 of Electronic Proceedings in Theoretical Computer Science, 100–126. 2014. doi:10.4204/EPTCS.153.8.

Ohad Kammar, Sam Lindley, and Nicolas Oury. Handlers in Action. In Proceedings of the 18th ACM SIGPLAN International Conference on Functional Programming (ICFP), 145–158. 2013. doi:10.1145/2500365.2500590.

Robert Atkey. Syntax and Semantics of Quantitative Type Theory. In Proceedings of the 33rd Annual ACM/IEEE Symposium on Logic in Computer Science (LICS), 56–65. 2018. doi:10.1145/3209108.3209189.

Daan Leijen. Type Directed Compilation of Row-Typed Algebraic Effects. In Proceedings of the 44th ACM SIGPLAN Symposium on Principles of Programming Languages (POPL), 486–499. 2017. doi:10.1145/3009837.3009872.