Browse documentation

Explanation

Effects, handlers and Septa

How Septa effects support deterministic tests, checked operations and durable execution, with a comparison to Unison and OCaml.

Septa adds a compiler-checked effect system to its supported Rust profile. It focuses effects on everyday application development: deterministic tests, explicit permissions and recoverable execution.

The compiler tracks which typed operations code may request. The runtime checks permission to run them, records the outcomes needed for recovery and resumes the work waiting for an answer.

For example, tests can replace live services with fixed answers or failures, then check the application’s result and the requests it made. The application logic stays the same.

Effects also let actors and workflows pause while waiting for other work. Concurrency, actors and async Rust explains how this relates to futures and .await.

Start with an ordinary function

This TypeScript function makes a decision from its arguments:

function canReserve(stock: number, quantity: number): boolean {
  return quantity > 0 && stock >= quantity;
}

It reads no database, changes no shared state and sends no messages. The same arguments produce the same result. This is a pure function.

Getting the stock level is different. It depends on something outside the calculation. Reading a database, asking another actor, reading the clock and sending a payment are all examples of effects. An effect can be a read; it need not change anything.

An ordinary Promise<number> or Rust Future<Output = i64> tells you about the eventual result. It does not list the database, clock or network operations the code may perform. Result<T, E> describes success and failure values, but does not list those operations either.

With dependency injection, you pass a StockRepository interface or Rust trait to the function and supply a real implementation or a test double. An effect system also tracks operations through the functions that call them and checks how they are used. Libraries can encode effect information in types too.

Effect checking and effect handling

These are separate features:

  • Effect checking tracks which operations a computation may request. A function that calls another effectful function may inherit its effects.
  • Effect handling implements those operations. A stock lookup could use a database, an in-memory map or a recorded answer.

A language can provide handlers without statically tracking all effects. OCaml is one example. Septa tracks effects while keeping their implementation at a runtime boundary.

An algebraic effect declares operations separately from the handlers that implement them. General algebraic handlers also give application code control over the suspended computation: the work waiting for an operation’s answer.

What Septa checks

In Septa, a capability interface declares typed operations. This example uses the current effectful imports:

use effectful::{capability, effectful};

#[capability(
    name = "stock",
    version = 1,
    class = Boundary,
    contract = RetrySafe,
    cancel = Cooperative,
    grants("read")
)]
pub trait Stock {
    fn quantity(&self, sku: i64) -> i64;
}

#[effectful]
pub fn stock_for(sku: i64, stock: StockCap<'_>) -> i64 {
    stock.quantity(sku)
}

The declaration generates the StockCap handle and types for requests and answers. stock_for requests the stock.quantity operation. #[effectful] marks a function that may perform effects; the compiler works out which operations it may request.

If another function calls stock_for, the compiler includes stock.quantity in that function’s effects too. A function required to be pure cannot hide an operation by calling a helper. This analysis lists possible operations; a particular call may use only some of them.

For example, this caller also has the stock.quantity effect:

#[effectful]
pub fn can_reserve(sku: i64, quantity: i64, stock: StockCap<'_>) -> bool {
    let available = stock_for(sku, stock);
    quantity > 0 && available >= quantity
}

The comparison is pure, but obtaining available is effectful. If can_reserve were required to be pure, Septa would reject the call to stock_for.

The attributes also declare the operation’s class, retry rules, cancellation behaviour and required permissions. RetrySafe must match what the implementation actually does. Adding the attribute does not make a retry safe. To run this example, you also need an implementation and runtime grants that allow the operation.

Here, grants("read") names a permission term used by quantity. It does not grant that permission, choose an HTTP method or restrict a URL. #[effectful] does not grant permission either.

A StockCap exposes the operations declared by Stock, not arbitrary I/O. Adding a managed HTTP call requires access to the HTTP capability, and that call becomes part of the inferred effects.

Septa’s compiler performs these checks; upstream rustc does not. The #[effectful] marker does not create a new standard Rust function type. Compiling the same source through Cargo does not, by itself, enforce Septa’s profile or runtime permission checks.

“First-class effects” means the compiler and runtime understand these operations directly. The profile still limits how capability handles can be passed, stored and constructed, and it does not give application code direct access to continuations. See the Rust profile.

What happens when an operation runs

When a boundary operation such as stock.quantity runs:

  1. The computation pauses at the operation and saves its execution state.
  2. The runtime checks permission and sends the request according to its delivery contract.
  3. The handler returns an outcome or reports that the work is still pending.
  4. The runtime validates and records the answer before advancing execution.

The handler receives the command and the result of the permission check. Its interface does not expose the suspended continuation or the run’s state. The runtime records the answer and decides whether execution can continue.

The source of an answer can change without changing the code that requests it. Tests supply controlled answers; recorded replay uses saved answers.

Make and constrain an HTTP request

Stock.quantity declares a business operation. It does not specify where the stock level comes from or make an HTTP request by itself. In managed code, network I/O goes through supported capabilities. Native HTTP clients run outside that profile.

To put HTTP requests under Septa’s control, write the lookup using its built-in HTTP capability. This example uses the current generated HTTP types. inventory.example is a placeholder for your service:

use effectful::effectful;
use effectful::pkg::p_dd8077e1::{
    Body, Header, HttpClientCap, HttpError, HttpRequest, HttpResponse, Method, QueryPair,
};

pub fn no_headers() -> Vec<Header> {
    Vec::new()
}

#[effectful]
pub fn fetch_stock(
    http: HttpClientCap<'_>,
    sku: String,
) -> Result<HttpResponse, HttpError> {
    let request = HttpRequest {
        origin: String::from("https://inventory.example"),
        method: Method::Get,
        path: String::from("/v1/stock/"),
        query: vec![QueryPair {
            name: String::from("sku"),
            value: sku,
        }],
        headers: no_headers(),
        body: Body::Text(String::new()),
    };
    http.send(request)
}

For SKU 42, the request is GET https://inventory.example/v1/stock/?sku=42. The runtime performs the network call. The helper returns the HTTP response; application code must check its status and decode the stock quantity. An HTTP 404 or 500 is a response, so it still needs handling even when send returns Ok.

This helper requests effectful.http.client.send. Its callers inherit that effect. This example calls HTTP directly; it does not implement the earlier Stock trait. Declaring Stock does not automatically connect it to HttpClientCap.

Restrict the destination and request

In a configured application using the built-in HTTP runner, this application.toml fragment permits a limited set of requests:

[bindings]
"effectful.http.client" = { origins = ["https://inventory.example"] }

[[origin]]
origin = "https://inventory.example"
timeout_ms = 5000
max_response_bytes = 16384

[grants]
"effectful.http.client" = ["http.request:https://inventory.example:GET:/v1/stock/"]

The runtime checks the bound origin and the grant before opening a connection. With this configuration:

  • GET /v1/stock/?sku=42 at the configured origin is allowed.
  • POST /v1/stock/, GET /v1/orders/ or a request to another origin is refused.
  • Connection and socket I/O use a five-second timeout; response bodies are limited to 16 KiB. This is not a five-second deadline for the whole lookup, which may include retries.

The path rule is a prefix match. It also permits paths below /v1/stock/; it does not restrict the sku query value or establish permission to read a particular customer’s stock. Those rules need application or service authorization.

These are application-level HTTP grants, not an allowlist attached only to fetch_stock. The compiler tells you that a function may request HTTP. Runtime policy determines which requests the application may send. These fragments illustrate that relationship; they need a configured application and its entry points to run.

Inspect what happened

For the built-in HTTP application path, run verify from the application directory. After running the application, use status with its state directory (.state here):

effectful verify .
effectful status --state .state

verify lists checked operations, including uses effectful.http.client.send. That tells you the code may request HTTP; it does not mean a request ran.

status reads the node’s retained execution records. Its outbound entries show requests, attempt counts and how they concluded. An origin refusal can show attempts 0 concluded refused; a completed attempt can show attempts 1 concluded response. The response status still matters. These records describe retained activity, not every possible execution path.

The tests below let you assert the requested operation and arguments. HTTP tests can also supply taped responses without contacting the service. See effects and authority for the distinction between declared, permitted and observed operations.

Where native code changes the boundary

A native implementation could obtain the answer to stock.quantity by making its own HTTP request. Septa would track stock.quantity; it would not discover or apply the built-in HTTP policy to network calls hidden inside that native implementation. The native component needs its own network controls and instrumentation.

Use the built-in HTTP capability when you want Septa to constrain and record the HTTP operation itself. Custom native implementations need an explicit integration design; the Stock declaration alone is not a ready-made HTTP adapter or a general handler SDK. See native Rust integration.

Test effects without live services

Septa’s managed test runners can replace external responses with answers supplied by the test. You can test application logic without a live database or API, and repeat the test with the same inputs, starting state and answers.

For a configured graph application exposing stock_for above, this tests/stock.json case supplies a stock level of ten:

{
  "entry": "stock_for",
  "input": [["s64", "42"]],
  "answers": [["value", ["s64", "10"]]],
  "expect": {
    "result": ["s64", "10"],
    "trace": [["stock.quantity", [["s64", "42"]]]]
  }
}

The test checks that stock_for(42, stock) requests stock.quantity for SKU 42 and returns ten. s64 is the test format’s tag for a signed 64-bit integer. The runtime supplies the capability handle; it is not part of the case’s data inputs. This case needs a configured graph project, not just the Rust declaration above.

The same mechanism lets you test more than a successful response:

  • Supply business errors for operations that return Result, or supported runtime failures, to check error handling.
  • Assert the effect trace, including the requested operations, their arguments and their order. The graph runner fails a case if an answer is missing, an answer is left unused or the expected trace differs.
  • Set up an actor’s initial state, send messages and check its final state.
  • Add "restart": true to export the store while an effect is pending, load it into a fresh in-memory store and continue the test.

The graph runner above tests application-defined operations using ordered answer lists. Built-in clock and HTTP operations use a separate application test runner and case format. That runner supports a scripted clock and HTTP responses supplied by a test tape, matched by method and path including the query. These HTTP tests make no network requests and need no provider credentials.

Native Rust tests have another option: the generated StockOracle trait and StockCap::from_oracle let a test supply a Rust implementation of the operation. This runs the source through Cargo. It does not exercise the managed runtime’s scheduling, permissions or persistence.

Replacing effects makes the application tests repeatable when their inputs and responses are controlled. It does not test whether the real database, API or native adapter behaves as expected; those still need integration tests. Managed test results can also be cached when their relevant inputs are unchanged.

Unison and OCaml support the same testing idea through application-defined handlers. A Unison handler can implement a store with an in-memory map. An OCaml handler can supply test answers, and libraries such as Eio provide mock resources. Controlling an effect’s answer does not require application code to control the continuation. Septa’s test runner supplies the answer and lets the runtime resume the computation.

What is a continuation?

A continuation is the remaining computation, waiting for an operation’s result. Consider this pseudocode:

stock = perform Stock.quantity(42)
return canReserve(stock, 2)

While the lookup is pending, the rest of the work is “take the stock value and run canReserve(stock, 2).” In Unison or OCaml, a handler receives that remaining work as a continuation.

If we call the continuation resume, then resume(10) supplies the stock value and continues the calculation. A delimited continuation covers the remaining work within an enclosing handler’s scope.

Application code can choose a handler for a particular block of code. For example, a handler could use a local map for stock lookups and pass unrelated operations to an outer handler. Depending on the language, it can also save a continuation for later, change the block’s overall result or end it early.

Septa saves continuations so it can resume work after interruption. The Rust profile does not expose them to application code or provide these general handler constructs.

Comparing Septa, Unison and OCaml

All three can separate operations from their implementations and use that separation in tests. They differ in how code selects implementations, how effects are checked and who controls suspended work.

Application code and testing

This table includes the testing tools as well as the language features. Eio is an OCaml library; UCM is Unison’s development tool.

What you want to do Septa Unison OCaml 5.4
Define typed operations Capability interfaces Ability declarations Extensible effect declarations
Replace external operations in tests Scripted answers in managed tests; test oracles in native Rust Test implementations supplied by ability handlers Test effect handlers; libraries such as Eio also provide mock resources
Run repeatable tests Control inputs, starting state and effect answers in managed tests Pure unit tests with deterministic ability handlers Use deterministic handlers or mocks; Eio documents the scheduling conditions
See which operations code may request Concrete operation sets inferred through supported calls Ability requirements in function types Operations are typed, but ordinary function types do not track all effects
Reuse unchanged test results Cache cases when their relevant inputs match UCM caches regular unit tests by dependency hashes Depends on test/build tools; effect handlers alone do not provide caching

Unison’s testing guide explains deterministic unit tests, cached results and separate IO tests. Its ability-handler example implements a store with an in-memory map and can return the final map for assertions.

OCaml’s Eio mock library provides mock flows, networks and clocks, including simulated failures. Eio’s determinism guide explains when deterministic mocks and scheduling produce repeatable tests. Effects do not make uncontrolled I/O deterministic in any of these systems.

Handler programming

These features let application code choose local implementations and let libraries build custom control flow, such as schedulers or search. They are separate from supplying test answers.

Feature Septa Unison OCaml 5.4
Choose a handler around a block of application code Implementations are selected at supported runtime or test boundaries; no general handler scopes in the profile Application-defined handler scopes Application-defined handler scopes
Control a suspended computation Runtime owns the continuation and resumes it from an answer Handler receives a continuation Handler receives a one-shot continuation
Effect polymorphism No open effect parameters in the current profile Polymorphic ability requirements No built-in effect rows in function types
Resume the same captured continuation more than once No application-controlled multi-shot resumption Supported One-shot

Septa’s application-focused design puts effect checking, test substitution, scoped permissions and durable execution in the same compiler and runtime workflow. Application code uses direct calls without managing continuations. Unison and OCaml expose more control for building custom handlers, schedulers and control-flow libraries. These are useful capabilities; Septa leaves that control with its runtime. Crash recovery and access control require additional design and implementation beyond the handler mechanism itself.

Coming from Unison

In Unison, Input ->{Store} Output means the function requires the Store ability. Its caller must supply a handler or pass the requirement on to its own caller. A handler that fully handles Store can remove that requirement from the enclosed computation. Any effects used by the handler still need to be handled. Unison’s language reference describes the checking rules.

Effect polymorphism means a function can work with computations whose effects vary. A wrapper can handle Store while preserving whatever other abilities its argument requires. These open sets are often called effect rows. Unison’s handler guide shows this with a polymorphic ability variable.

Septa computes a concrete set of operations for each function, such as stock.quantity. It has no equivalent way to handle one effect locally and express the remaining effects as a variable in the function’s type.

Unison handlers can also resume a continuation several times. Septa does not provide an equivalent application API, so handler-based code cannot be translated directly between the two.

Coming from OCaml

OCaml checks the types of effect operations and their answers, but its compiler does not guarantee that every performed effect has a handler. An unmatched operation raises Effect.Unhandled at runtime. Typed operations alone do not provide static effect safety: a compile-time guarantee that effects are handled. OCaml’s Effect API documents the runtime exceptions.

OCaml provides both deep handlers, which remain installed when a captured continuation resumes, and shallow handlers, which require a handler to be supplied on resumption. Its continuations are one-shot: attempting to resume one twice raises an exception. They still support user-defined scheduling and other control flow. OCaml’s effect-handler manual explains these models.

Septa’s profile has no deep or shallow handler constructs. A runtime adapter supplies outcomes, and the runtime controls when suspended work resumes.

What general handlers would add

General handlers would let application code:

  • Choose an implementation for one block of code.
  • Nest handlers, handling selected operations and passing others to an outer handler.
  • Implement an operation using other effects in a local handler.
  • Control when and how a suspended computation continues.

These features are outside the first-release scope. Adding them would require Septa to check effects across handler scopes and define how handlers interact with permissions and persistence. General handlers are not inherently unsafe; they allow more control than Septa currently exposes.

Multi-shot resumption means resuming the same captured continuation more than once, perhaps with different answers to explore a search. Algebraic handlers do not have to support it: OCaml’s continuations are one-shot. Septa accepts only one next revision for each saved run revision. Forking creates a new run identity.

Effects, authority and durability

An effect requirement says that code may request an operation. Permission to use it is a separate check. Holding a typed handle grants no permission by itself. Septa checks each request against scoped grants before allowing it to proceed. Read effects and authority for details.

Durability also needs more than a continuation in memory. The runtime must save enough state and record answers to recover after a crash. Septa provides this for supported operations; effect handlers alone do not guarantee it.

Recorded replay recomputes from saved answers without issuing new external requests. A step can be evaluated again even though Septa accepts only one next revision. This does not give application code multi-shot continuations, or guarantee exactly-once payments and other external side effects. Those depend on delivery contracts.

For application design, put decisions in the deterministic core, describe interactions through typed operations, and use native Rust integration for code outside the profile.

Search concepts, guides and reference.