Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Effects and deliveries

A Vishy program has no input or output of its own: no file, no clock it did not declare, no network. The world comes in and goes out through declared openings. An effect is something a flow asks of the world outside, for a fact the program cannot compute: the program declares it, and what performs it is outside the program. A delivery says where an emitted event goes once the flow has committed. An http effect is a call to a web API, declared rather than written. This chapter has one of each.

// whether an address is well formed is decided outside the program; the fixtures say what the verifier may assume
effect well_formed(addr: string(64)) -> bool
    fixtures { ("ada@example.com") => true; ("ada at example") => false; }
events { Subscribed(subscriber: id) }
row Subscriber { id: id, addr: string(64) }
unit List {
    caps storage, outbox;
    state subscribers: Subscriber[16];
    contract add(subscriber: id, addr: string(64), well_formed: bool) {
        case !well_formed => fail BadAddress;
        else => Subscribed: subscribers += [Subscriber { id: subscriber, addr }], emit Subscribed(subscriber);
    }
}
flow subscribe(subscriber: id, addr: string(64)) atomic {
    let ok = well_formed(addr);
    List.add(subscriber, addr, ok);
}
deliver Subscribed to webhook env "CRM_HOOK";
deliver Subscribed to mail "list@example.com";
scenario two_addresses {
    subscribe(1, "ada@example.com") => Subscribed;
    subscribe(2, "ada at example") => BadAddress;
}

An effect

effect well_formed(addr: string(64)) -> bool is declared like a function, with a typed header, and has no body. fixtures { … } are literal answers for literal arguments, used when the program is verified. That is all a program says about an effect: what it takes, what it answers, and what the verifier may assume of it.

What performs the effect is not in the program. A program holds no Rust: a function cannot have a Rust body, so every function in a program is one the verifier runs, and an effect cannot have one either. effect well_formed(…) -> bool impl { … } is refused where the block starts, and so is a line that names a crate, rust email_address = "0.2";; each refusal says what to do instead. Three things can stand behind an effect. A call to a web API is declared, not written, as the last sections of this chapter show. A computation is a sealed function, which is not an effect at all and which the verifier runs. Anything else, a Rust crate for one, is supplied where the program is served. The program sees (string(64)) -> bool. It never sees the address parser this chapter puts behind it, further down.

Flows call effects; contracts do not

subscribe calls the effect, binds its answer with let, and passes it to List.add as an ordinary argument. The contract decides what an unusable address means, fail BadAddress; the effect only reports a fact. A contract that asks the effect itself is refused:

effect well_formed(addr: string(64)) -> bool
    fixtures { ("ada@example.com") => true; }
row Subscriber { id: id, addr: string(64) }
unit List {
    state subscribers: Subscriber[16];
    contract add(subscriber: id, addr: string(64)) {
        case !well_formed(addr) => fail BadAddress;
        else => Subscribed: subscribers += [Subscriber { id: subscriber, addr }];
    }
}
book/refusals/effects-in-contract.vish:7:15: error: `well_formed` is an effect; an effect can be called only from a flow, as a step of its own: `let r = well_formed(…);` in a flow, then pass `r` to a contract
          case !well_formed(addr) => fail BadAddress;
                ^^^^^^^^^^^

The checker names the rule: an effect can be called only from a flow, as a step of its own. A contract reads its unit’s state and its arguments and nothing else, which is what lets the verifier call it from any state it likes. The first removal holds here too: nothing outside the unit can reach in, and a contract cannot reach out.

In verification the effect never runs

scenario two_addresses
  subscribe(1, "ada@example.com") => Subscribed
  subscribe(2, "ada at example") => BadAddress
  List = List { subscribers: [Subscriber { id: 1, addr: "ada@example.com" }], outbox: [Subscribed { subscriber: 1 }] }
2 step(s), all as expected
verify: 0 examples, 2 scenario steps and 2000 sampled checks passed

The scenario’s two calls got their answers from the fixtures. In the sampled checks, where no fixture matches the argument, the verifier samples the effect’s answer by its type, so List.add is checked with both true and false for any address. Nothing that performs the effect is consulted: the verdict above was reached with nothing behind well_formed at all.

What the verifier trusts is the header and the fixtures. An effect that can answer anything its type allows has to be met by a contract that handles anything its type allows.

In the service, the owner’s Rust runs

vishy service --crate writes a Rust project that stores and serves the program (vishy service alone writes the application’s folder, which runs no Rust of the owner’s: there a call of an effect nobody supplied fails the request, as below). In its src/effects.rs the project has one function for each effect the program declares, and the generated code calls that function when a flow reaches the effect. As the compiler first writes it, the function fails and says which effect it is:

#![allow(unused)]
fn main() {
pub fn well_formed(addr: String) -> bool { panic!("effect `well_formed` is not supplied: write its body in src/effects.rs of this service") }
}

Built with cargo build --release and run from the service’s command line on 4 Oct 2026, before anything was supplied:

$ service e.db acme subscribe 1 ada@example.com
{"ts":1791149248788,"kind":"panic","error":"effect `well_formed` is not supplied: write its body in src/effects.rs of this service","at":"src/effects.rs:8"}
$ service e.db acme dump
World { list: List { subscribers: [], outbox: [] }, __now: 0, __ids: 0, __seed: 0, __caller: 0 }

The flow stopped at the effect, with exit status 101. Nothing was stored, and no answer was made up. Given a route, route POST "/subscribe" => subscribe(subscriber, addr);, and served, the same service answered each request with 500 {"error":"internal: effect `well_formed` is not supplied: write its body in src/effects.rs of this service","flow":"subscribe"}, served the next request, and afterwards dump showed no subscriber and outbox no event: a panic inside a flow writes nothing.

src/effects.rs is the owner’s file. Here the owner writes the function with a crate’s address parser, and names the crate on a line below the comment that ends the project’s Cargo.toml:

#![allow(unused)]
fn main() {
pub fn well_formed(addr: String) -> bool { email_address::EmailAddress::is_valid(&addr) }
}
email_address = "0.2"

Built again, the same program ran that Rust:

$ service e.db acme subscribe 1 ada@example.com
Subscribed
event Subscribed { subscriber: 1 }
$ service e.db acme subscribe 3 'ada@@example.com'
BadAddress

No fixture mentions ada@@example.com; the crate’s parser refused it, and the contract turned that into the program’s own failure (exit status 4 on the command line, 409 at a door). That is how a Rust crate serves a Vishy program: outside it, behind a header the program declares.

When the program changes, vishy service --crate is run again into the same folder. It writes every other file anew and leaves the owner’s part alone, saying src/effects.rs kept (the owner's file), and it carries the crate line into the new Cargo.toml; the service built from the second generation subscribed bob@example.com as before. A program that has gained an effect does not build until the owner adds a function for it: the compiler stops at the call and names it.

The development door, vishy serve, has no src/effects.rs. On the same day it answered an effect the way the verifier does: ada@example.com was subscribed and ada at example refused, as the fixtures say, and six addresses no fixture mentions got a sampled answer (false each time in that run, so BadAddress).

Deliveries

emit Subscribed(subscriber) puts an event in the unit’s outbox; caps outbox allows it. Where the event then goes is one line per destination:

  • deliver Event to webhook "https://…"; posts it to a URL,
  • deliver Event to webhook env "NAME"; reads the URL from an environment variable when it delivers,
  • deliver Event to mail "ops@example.com"; posts {to, subject, event} to the endpoint in VISHY_MAIL_HOOK,
  • deliver Event to effect name; calls a declared effect (body: string(n)) -> bool with the event as JSON.

Two more things a delivery line can say. A trailing only, deliver Coded to mail "ops@example.com" only;, delivers the event and nothing else: the door keeps it out of its answer, so a value meant for one person, such as a one-time code, never reaches whoever made the request, while the outbox, the verifier, ensures emitted([…]), scenarios and vishy run see it as any event. Every delivery of one event says only, or none does; a mix is refused. And an event declared in a slice of a larger program is delivered from inside the slice by its bare name, or from the root by its full name, deliver slice::Event to …;, with no import (the chapter on many files).

The program declares the destinations; the service does the delivering. When the flow commits, the service writes one outbox row per event and destination in the same transaction as the state change, so an event is never lost and never recorded without its cause. A drainer, run by serve every 500 ms or by deliver once, posts each row. From the same session:

$ service e.db acme outbox
1 Subscribed -> webhook-env:CRM_HOOK attempts 0 delivered_at - error -
2 Subscribed -> mail:list@example.com attempts 0 delivered_at - error -
$ service e.db acme deliver
… "attempt":1,"ok":false,"error":"no destination for `webhook-env:CRM_HOOK` (set the environment variable)","next_in_ms":1000}
… "attempt":1,"ok":false,"error":"no destination for `mail:list@example.com` (set the environment variable)","next_in_ms":1000}
delivered 0, failed 2 (retried later)
$ CRM_HOOK=http://127.0.0.1:18741/crm VISHY_MAIL_HOOK=http://127.0.0.1:18741/mail service e.db acme deliver
… "attempt":2,"ok":true}
… "attempt":2,"ok":true}
delivered 2, failed 0 (retried later)

The listener received {"event":"Subscribed","subscriber":1} with the header Idempotency-Key: acme-1, the tenant and the row, the same on every retry. A failure waits and tries again, doubling the wait from one second to a few minutes at most, for up to twenty attempts, and then stays listed by outbox for a person to read. Delivery is at least once; the key is how a receiver drops a repeat. An effect destination is delivered when it answers true and retried when it answers false or panics, which makes any crate a destination: a queue client, a broker, a mail library, with the Rust in the service’s src/effects.rs and the choice of destination one line of Vishy.

The verifier delivers nothing. What it can check is that the right events were emitted: the run above ends with outbox: [Subscribed { subscriber: 1 }], and a contract can say ensures emitted([…]).

Receiving signed webhooks

Deliveries go out; webhooks come in. Other services announce their events by posting to the application: a payment settled, a parcel moved, a message delivered. Each such request is signed with a key the two sides share, so the application can tell a real event from a forged one.

Checking that signature is the door’s work, not the program’s. It is a feature of the doors, optional, set up in a configuration file beside the program, and the language has no form for it: a program that receives no webhooks never meets it, and a program that does is written as any other. A flow takes the event as a row; a POST route leads to the flow:

// A payment service posts its events to /hooks/payments; the door's configuration guards the route.
row Payment { id: string(255), type: string(64), amount: int(0, 100000000) }
unit Payments {
    caps storage;
    state settled: int = 0;
    contract heard(e: Payment) {
        case e.type != "payment.settled" => stop Ignored;
        else => Counted: settled += 1;
        examples {
            {} (Payment { id: "evt_1", type: "payment.settled", amount: 1200 }) => Counted { settled: 1 };
            {} (Payment { id: "evt_2", type: "payment.refunded", amount: 1200 }) => Ignored;
        }
    }
}
flow on_payment(e: Payment) atomic { Payments.heard(e); }
view settled() = Payments.settled;
route POST "/hooks/payments" => on_payment(e);
route GET "/settled" => settled();

The event’s kind is a field named type, as many services name it. That is a keyword in Rust, which the compiler writes the program in; a row’s field may still be named so, and the compiler writes it as a raw identifier.

The door’s configuration says which route is guarded, by which sender, how the sender signs, and which environment variable holds the key. This entry is for a service that signs the way Stripe does, a time and a hex signature in one header:

{"senders": [{
  "name": "payments",
  "scheme": "hmac",
  "hash": "sha256",
  "key": {"env": "PAY_HOOK_KEY", "read": "as-written"},
  "signs": ["timestamp", {"text": "."}, "body"],
  "signature": {"header": "Pay-Signature", "part": "v1", "encoding": "hex", "several": true},
  "timestamp": {"header": "Pay-Signature", "part": "t", "unit": "seconds", "tolerance_s": 300},
  "id": {"body": "id"},
  "routes": [{"method": "POST", "path": "/hooks/payments"}]
}]}

Both doors take it: vishy serve payments.vish --senders senders.json, and vishy service payments.vish out --senders senders.json, which puts the file into the application’s folder so that the application is never served without it. Either door reads the key from PAY_HOOK_KEY when it starts and refuses to start, naming the variable, while it is not set. It also refuses to start while another route of the program, such as route PUT "/hooks/payments" => on_payment(e);, reaches the guarded flow, since that route would run it unsigned. Before any flow runs, and before the request is even decoded, the door checks the request’s signature over its raw bytes, its time against the door’s clock, and that it carries no query string. Only then is the body read into e, whole, by the same rules a web call’s reply is read by. Each delivery runs the flow once: the store records the event’s id in the same transaction as the flow, so the same request sent again, a retry the sender signs again, or a copy someone captured and replays, answers that it is a duplicate and runs nothing. On 3 Oct 2026, with python3 signing the requests (tests/check_senders.sh serves this program):

POST /hooks/payments, signed            200 {"ok":true,"outcome":"Counted"}
POST /hooks/payments, the same again    200 {"duplicate":true,"ok":true}
POST /hooks/payments, one byte changed  401 {"error":"unauthorized: the signature does not verify"}
GET /settled                            200 {"ok":true,"value":1}

The answer names the outcome and nothing else, since the sender is a third party; a refusal names the class of the reason, and no key, signature or byte of the body appears in a log line. The same configuration can also sign the program’s own deliveries, so that another program, Vishy or not, can tell them from forged ones. docs/senders.md has the whole configuration, a tested entry for each of several services, and every check and answer.

A web call, declared

The effect above is performed by Rust that the service’s owner wrote. The most common reason a program reaches out, though, is to ask another service something over the web: look a record up, create a payment, send a message. For that a program writes no Rust. It declares the call, and the compiler writes the code. Any program can call any web API this way; the language knows no particular service.

// A shelf takes a book only after a catalogue, reached over the web, says what the book is.
enum WebError { none, timeout, transport, status, decode }
row Book { title: string(120), pages: option<int(1, 5000)> }
row BookReply { ok: bool, status: int(0, 599), error: WebError, body: option<Book> }
row Entry { id: id, isbn: string(13), title: string(120) }

// the call, declared: method, path, where it goes, how long it may take, and what the answer must fit
http effect find_book(isbn: string(13)) -> BookReply
    GET "/isbn/{isbn}"
    base env "CATALOG_URL"
    timeout 3000 ms
    fixtures {
        ("9780441013593") => BookReply { ok: true, status: 200, error: WebError.none, body: some(Book { title: "Dune", pages: some(604) }) };
        ("0000000000000") => BookReply { ok: false, status: 404, error: WebError.status, body: none };
    };

unit Shelf {
    caps storage;
    state books: Entry[8];
    // the reply decides: no answer, no such book, any other refusal, or a book
    contract add(id: id, isbn: string(13), r: BookReply) -> string(120) {
        case r.error == WebError.timeout || r.error == WebError.transport => fail Unreachable;
        case r.status == 404 => fail NoSuchBook;
        case !r.ok => fail Refused;
        else => let t = match r.body { some b => b.title, none => "" }; Shelved(t): books += [Entry { id, isbn, title: t }];
        examples {
            {} (1, "9780441013593", BookReply { ok: true, status: 200, error: WebError.none, body: some(Book { title: "Dune", pages: none }) })
                => Shelved("Dune") { books: [Entry { id: 1, isbn: "9780441013593", title: "Dune" }] };
            {} (2, "0000000000000", BookReply { ok: false, status: 404, error: WebError.status, body: none }) => NoSuchBook;
        }
    }
}

flow shelve(id: id, isbn: string(13)) atomic { let r = find_book(isbn); Shelf.add(id, isbn, r); }

scenario two_books {
    shelve(1, "9780441013593") => Shelved("Dune");
    shelve(2, "0000000000000") => NoSuchBook;
}

http effect find_book(isbn: string(13)) -> BookReply is a header like an effect’s. The method and the path follow, GET "/isbn/{isbn}", and {isbn} is filled in from the parameter of that name. The clauses after the path say the rest. base env "CATALOG_URL" reads the service’s address from an environment variable, so the same program talks to a test server on a laptop and to the real service in production. timeout 3000 ms is the longest the call may take. Other clauses add a credential read from the environment (auth bearer env "KEY"), query values, and a row sent as a JSON or form body; the reference, section 18, lists them. The compiler builds the request, makes the call and reads the answer.

The reply is a value

A call over the web can go wrong in more ways than a function call can. The catalogue may answer with the book. It may answer with something that is not the book the program declared, or with an error status, such as 404 for an ISBN it does not know. It may take longer than the timeout, or not answer at all because nothing is listening. Each of these is a value, not an exception. BookReply is the row every answer becomes, and its shape is fixed: ok, the HTTP status (0 when no answer came), an error saying which of the five things happened, and the body, the answer read into a Book when the call succeeded. Reading is strict: a title longer than 120 bytes is not cut to fit, it makes the answer a decode error. A body may also hold many values, a page of results as a list of rows (items: Book[100] ordered) or a map with an entry bound, and an answer past either bound is a decode error too.

Who decides what each of the five means? Not the flow, which cannot branch. It binds the reply and passes it to a contract, and Shelf.add reads it in order: no answer is Unreachable, a 404 is NoSuchBook, any other failure is Refused, and only a book is shelved. A flow that makes the call and does not hand the reply to a contract is refused:

// The shelf counts a book without asking what the catalogue answered: the reply goes nowhere.
enum WebError { none, timeout, transport, status, decode }
row Book { title: string(120), pages: option<int(1, 5000)> }
row BookReply { ok: bool, status: int(0, 599), error: WebError, body: option<Book> }

http effect find_book(isbn: string(13)) -> BookReply GET "/isbn/{isbn}" base env "CATALOG_URL";

unit Shelf {
    state count: int = 0;
    contract add(isbn: string(13)) => Counted: count += 1;
}

flow shelve(isbn: string(13)) atomic { let r = find_book(isbn); Shelf.add(isbn); }
book/refusals/effects-http-undecided.vish:13:44: error: the reply `r` of http effect `find_book` is not passed to a contract; a contract decides what a reply means: `Unit.contract(…, r)`
  flow shelve(isbn: string(13)) atomic { let r = find_book(isbn); Shelf.add(isbn); }
                                             ^

That shelf would count a book whether the catalogue knew it, refused it, or never answered. The checker asks for the place where that is decided.

In verification, no call is made

scenario two_books
  shelve(1, "9780441013593") => Shelved("Dune")
  shelve(2, "0000000000000") => NoSuchBook
  Shelf = Shelf { books: [Entry { id: 1, isbn: "9780441013593", title: "Dune" }] }
2 step(s), all as expected
verify: 2 examples, 2 scenario steps and 2000 sampled checks passed; web replies: 27510 sampled (5540 success, 5435 timeout, 5491 transport, 5636 error status, 5408 decode), 2 from fixtures

The scenario’s two calls matched the two fixtures. Every other call got a sampled reply: one of the five kinds, with fields that agree with it (a sampled book for a success, status 0 for a timeout). The verify line ends with the count of each. The network is never touched.

The five counts are close to even. Each call a flow makes in a walk draws its reply afresh, so a reply Shelf.add refuses, such as a timeout, does not hide the other kinds from the flows that come after it. That holds for a call whose ISBN matches no fixture. A call whose ISBN equals a fixture’s gets that fixture’s reply every time, in every walk, and no other; a flow that only ever asked for the fixtures’ ISBNs would be checked against the fixtures’ replies alone, a timeout never among them. In the run above only the scenario’s two calls matched a fixture (the 2 from fixtures); the walks drew other ISBNs, so every call they made was sampled and the flows met every kind. The contract is also checked on its own with any BookReply its type allows, including combinations no real call produces. The two examples in Shelf.add are there for a reason of their own: a sampled error status is anywhere from 300 to 599, so a guard on exactly 404 is rarely met, and without the second example vishy verify fails, saying that NoSuchBook is never produced.

At the door, the call is real

vishy serve, the development door, makes the call for real, and so does the service vishy service generates, with the same request and the same reading of the answer. With one line added to the program, route POST "/shelve" => shelve(id, isbn);, and a small catalogue server on the same machine, on 1 Oct 2026 (each request is a curl POST with a JSON body; the line after it is the answer and its status):

$ CATALOG_URL=http://127.0.0.1:18740 vishy serve shelf.vish 127.0.0.1:18741
serving on http://127.0.0.1:18741
POST /shelve {"id":1,"isbn":"9780441013593"}
{"events":[],"ok":true,"outcome":"Shelved","value":"Dune"} 200
POST /shelve {"id":2,"isbn":"0000000000000"}
{"events":[],"ok":false,"outcome":"NoSuchBook"} 409
POST /shelve {"id":3,"isbn":"9780000000002"}
{"events":[],"ok":false,"outcome":"Refused"} 409
POST /shelve {"id":4,"isbn":"9780000000003"}
{"events":[],"ok":false,"outcome":"Unreachable"} 409

The catalogue answered the first with {"title": "Dune", "pages": 604, "publishers": ["Ace"]}, and the key the row does not declare was ignored. The second got a 404. The third got a title of 130 characters, which does not fit string(120), so the reply was a decode error and the contract refused it. The catalogue held the fourth for four seconds, past the timeout. Pointed at a port where nothing listens, the same request also answered Unreachable, with the error transport. The door logs one line per call, with the path as declared and never the address, a header or a value:

… "kind":"call","effect":"find_book","method":"GET","path":"/isbn/{isbn}","status":404,"error":"status","ms":10}
… "kind":"call","effect":"find_book","method":"GET","path":"/isbn/{isbn}","status":0,"error":"timeout","ms":3001}

Without CATALOG_URL the door does not start, and says why: http effect `find_book` reads the environment variable `CATALOG_URL`, which is not set or is empty.

One thing the transaction cannot do is take a call back. The call runs inside the flow’s transaction, so when a later step fails, the flow’s own writes roll back; but the other service has already answered, and a service that was asked to create something has created it. A reply is a fact about the world outside. For the calls that change something (POST, PUT, PATCH, DELETE), the door and the service send an Idempotency-Key that is the same when a request is retried, so a service that honors keys acts once. The key comes from the flow, its arguments, the caller and the step, so it is also the same for two separate requests with the same arguments from the same caller: a service that honors keys answers the second with the first one’s result and does nothing new. A request that means a new call with the same arguments sends its own Idempotency-Key header, and the key changes with it.

The door and the service follow no redirect. A 301, 302 or 303 reaches the contract as an error status, like a 404, because following it would send the call’s credentials and its key to whatever address the answer names. And a path value that is empty, . or .. is never sent: it would name a different path on the other service, so the reply is transport and no request is made.

Try

Change the fixture ("ada at example") => false to => true. The scenario’s second step now gets Subscribed, and vishy verify fails naming that step and the world it reached. The fixtures are what the verifier believes about the world, so a wrong fixture is a wrong belief, found where it matters.

In the shelf program, change title: string(120) in Book to title: string. The checker refuses the declaration: http effect `find_book`: field `title` of row `Book` is string, which has no bound; a reply decodes only into bounded values (`string(n)`, `T[n]`, `map<K, V>[n]`). An answer is read only into values with a bound, so another service can never hand the program more than it declared.