RFC-002: Ledger, effects & vault

One test kills the effect service at every step of opening a draft pull request on a stand-in forge. After 100 runs, the forge holds exactly 100 pull requests, and the forge's token never shows up in a response, a journal, or the raw SQLite files. Worlds fork and rewind; the outside world does not. This RFC specifies how Plurics keeps the two consistent: the ledger, the identity and lifecycle of an external effect, the Orphan Rule, who may release an effect, the egress door, and the vault.

Monotonicity#

A world can rewind. A pull request that the world already opened cannot. So the record of what crossed custody must live where no rewind reaches it. Law L4 states the contract: Worlds fork; the ledger does not.

The ledger lives outside every world, snapshot, and checkpoint. Rewinding a world forks a new line and leaves every ledger record, every consumed approval, and every counter where it was. Nothing leaves custody before its durable ledger record.

StateExamplesOn forkOn rewind
World stateFiles under State mounts, the staged outboxShared, O(1)The line moves back
Cachetarget/, node_modules/Shared, O(1)Kept, never in identity
MonotoneEffect records, consumed approvals, quota spendNot forkedNever
ExternalA row in a remote database, a sent messageOnly where the remote supports itCompensation, or an orphan

The ledger store#

The ledger is one SQLite file: every table STRICT, the journal in WAL mode, synchronous = FULL, and foreign keys on. The file holds world heads and lines, per-world journals, the op_log table, effects, approvals, the quota tables, and world_store, which keeps every world record and makes ledger.db the daemon's one durable store. Time enters only as an explicit now_ns argument.

  • Append-only. Triggers abort any UPDATE or DELETE on ledger_events, op_log, and the quota ledger, budget_ledger.
  • Hash-chained. Each ledger_events row stores the previous row's hash and its own. Its own hash covers that previous hash and the row's sequence number, kind, time, run, effect, bundle, and body. LedgerStore::verify() runs SQLite's integrity and foreign-key checks, then walks the chain: dense sequence numbers, each prev equal to its predecessor's hash, and each hash recomputed.
  • Journals. Each world has a journal of typed entries: Start, Intent, Outcome, Seal, Fork, Orphans, Adopt, ProvenanceRaise, and Verdict, among others. A Verdict binds a sealed value, pass or fail, the exit code, the hashes of the command, its environment, and its binds, the sealed tree, and the base image (RFC-001).
  • Quota. Every quota call writes balanced double-entry records against a system account, so the audit balances after every call (RFC-003).

Effect identity#

When the effect service crashes mid-request and restarts, it must recognize the request it was making. So Plurics computes an external effect's identity; no one chooses it. EffectId is B3("effect" ‖ run_root ‖ lineage ‖ u64_be(seq)): the run, the world's lineage, and the effect's position in its journal. A restarted service replays to the same position, computes the same identity, and attaches to the recorded effect instead of making a new one.

The idempotency key sent with an effect is IdemKey = B3("idem" ‖ EffectId). On the wire, it is pl1_ followed by the first 20 bytes in lowercase unpadded base32: 36 ASCII bytes.

in_history(e, b) decides whether an effect belongs to a world's history. A plain prefix test on lineages gets this wrong: an effect the parent issued after forking a child has a lineage that is a prefix of the child's, yet the child never saw it. in_history compares the effect's journal position with the fork point instead.

The effect lifecycle#

Every external write goes through four durable steps. Each step is a ledger record, written before the next action:

intend → attempt → observe → reconcile
RecordWritten
IntendBefore anything is dispatched: the classified intent, its arguments' hash, its resource keys
CleanupRegisterFor an E3 effect, before the first attempt: how to undo it
AttemptDurably, before the first byte is sent
ObserveWhen a response, a probe result, a timeout, or a reset arrives
ResolveWhen the effect's outcome is settled
Approve, ConsumeWhen a linear approval is minted, and when it is used
ReleaseBegin, HeadMoved, ReleaseEndAround the release of a bundle

After a crash, reconciliation settles everything in flight. It resumes begun releases, dispatches approved intents that never sent a byte, resolves attempts of unknown outcome by a probe or a retry under the same idempotency key, and finishes interrupted compensations. It never re-issues an effect under a new key.

Linear approvals. An approval is single-use authority. A person or a line policy mints it, and a Consume record spends it. A spent approval fails with ECONSUMED, and restoring a checkpoint does not bring it back: authority does not come back from a snapshot.

The Orphan Rule#

Suppose a world opens a pull request and then rewinds to a point before it. The pull request still exists on the forge, but the rewound world's state no longer shows that it was sent. If the re-planned world sends it again, the forge now has two. An external effect that a rewind abandons after it happened, or may have happened, is an orphan of the world's line. The Orphan Rule keeps a re-planned world from doing the same thing twice:

  1. A new effect of class E3 or above whose resource keys overlap an unresolved orphan of its branch does not dispatch; it fails with EORPHAN.
  2. An orphan leaves that set only through a journaled resolution, an OrphanResolve record.
  3. An unsettled effect anywhere in the run that holds an overlapping key also blocks dispatch, with EUNRESOLVED.
  4. An identical re-issued request, with the same adapter, operation, and argument hash, adopts the orphan instead of sending again.
  5. A consumed linear approval stays consumed after any rewind.

RewindWorld reports the orphans it creates. The ledger records them and never re-executes them.

Effect classes#

Not every effect needs the same care. A read can run live; an irreversible write cannot. Every outbound operation falls into one of six EffectClasses. A protocol sets a floor, and a caller's or remote's annotation may only raise it.

ClassNameExecutesUndo
E0PureReadPure readLiveNothing to undo
E1WorldLocalWorld-local mutationLive, inside the calling worldDiscard the world
E2ExternalReadExternal readLive, never staged; the request itself is disclosed to the remoteNothing to undo
E3ShadowCompensableShadow or compensable writeLive, with cleanup registered firstCompensation
E4StagedOutboxStaged writeWhen its bundle is releasedNever sent if the world is discarded
E5GatedIrreversibleIrreversible writeOnly through a gate: a grant or an approvalNone

Deferred values. A staged effect's result is a Deferred<T>. Later intents may refer to it, as a whole value or inside a text template, without forcing it:

{"$promise": "<effect hex>", "path": ["number"]}
{"$template": ["Fixes #", {"$promise": "<effect hex>", "path": ["number"]}]}

Staging records a dependency edge for every promise, and a promise may name only an intent already in the graph, so the graph is acyclic by construction. An intent holds at most 16 promises, paths are at most 8 deep, and a filled text slot is at most 2,048 bytes. Release fills every slot only from a recorded outcome. Forcing a value releases exactly its unresolved upstream closure, in dependency order.

Bundles. An EffectBundle is the canonical, hashed set of staged intents that a world releases together. A linear approval signs its ApprovalDigest. Before release, check_saga requires every connected component, in dispatch order, to have the shape compensable* → pivot? → retriable*. Release then runs in three steps:

  1. One ledger transaction consumes the approval, moves the line head by compare-and-swap, and writes ReleaseBegin.
  2. The intents dispatch in order. A failure before the pivot compensates; a failure at or after it escalates.
  3. ReleaseEnd closes the release.

If a crash leaves a ReleaseBegin without its ReleaseEnd, reconciliation resumes the release and skips intents already settled.

The outbox in pluricsd. A program inside a world stages calls through its port, and nothing leaves custody while it does:

plsh effect stage job POST https://api.example.com/issues --cred 3 --body '{"title":"x"}'
plsh effect bundle job                      # the staged calls and their approval digest
plsh effect release job --digest <hex>      # the host, or a clean reviewer above job

EffectStage needs effect_invoke, and vault_use as well when it names a credential. EffectDrop removes a staged intent and its dependents, EffectBundle shows the bundle and its approval digest, and OutboxList lists what is staged. Inside a world, EffectStage and EffectDrop act on the caller's own outbox only: an intent a world put in a descendant's outbox would pass for the descendant's.

Who releases#

EffectRelease needs the effect_release grant and the approval_digest that EffectBundle showed the reviewer. Two kinds of caller hold it:

  • The host control socket may release any outbox. The release mints a linear approval of kind Human, in the person's name, and the reply carries each upstream status and the scrubbed response body.
  • A reviewer world whose port carries effect_release may release only the outbox of a strict descendant, never its own. Every intent in the bundle must have been staged strictly below the reviewer, and the reviewer, the target world, and the bundle must all be Clean. The release mints a linear approval of kind Policy, and the reply carries each upstream status with body: null: a response body is external data, and the reviewer stays clean for its next review.

Anything else waits for the host. A port that carries effect_release alone can still call OutboxList and EffectBundle, so a reviewer reads what it reviews without the right to stage into it.

Either way, the release dispatches outside the daemon's operation lock. It moves the world's own line, outbox/<world>, so one world's release never contends with another's. Requests go out over TlsHttpTransport, which trusts the webpki-roots certificates plus $PLURICS_EGRESS_CA, injects the vault credential on the wire only, and strips Set-Cookie from a credentialed response. EffectReconcile, served on the host control socket only, settles releases that a crash or a lost reply left open; the daemon also runs it at boot when the ledger holds one.

The egress door#

A world's network namespace has only lo. An execution started with an egress policy gets one more socket, bound at /run/plurics/egress.sock, and runs under plurics-relay. The relay binds an ephemeral port on 127.0.0.1 and relays each TCP connection to the socket. It sets PLURICS_EGRESS_URL, HTTP_PROXY, and HTTPS_PROXY, runs the real program, and exits with its status. No other route leads out.

The host end is the egress gateway in pluricsd. Each connection carries one HTTP/1.1 request, in one of two forms:

  • Reverse proxy, /r/<route>/<path>. The route names an upstream origin, http(s)://host[:port], and optionally a vault credential. The gateway strips the client's Authorization header, has the vault build the real header for exactly this target, and sends the request over TLS 1.2 or 1.3 (rustls) or plain TCP. The response streams back through the vault's streaming scrubber and the route's meter.
  • Forward CONNECT host:port. The gateway allows it only for a host on the policy's allowlist: host for port 443, host:port, or host:*, where host may be *.suffix for proper subdomains. It splices bytes both ways and counts them.

The gateway answers at the boundary, before or instead of touching the upstream:

StatusWhen
403CONNECT to a host not on the allowlist; the host is never contacted
402The world's quota node is frozen or cannot cover the request's hold
502A response head the vault cannot scrub

Framing is strict. The gateway refuses a bare CR, a repeated or conflicting Content-Length or Transfer-Encoding, a target with a fragment, and a chunk over 16 MiB. On a credentialed route, no Set-Cookie reaches the world. Once the upstream answers, and before any of its bytes reach the world, the world's provenance rises to ExternalIngress; the daemon journals the rise as ProvenanceRaise and stores the world's new mark in ledger.db. Every exchange takes a quota hold first and settles egress_bytes and units when it ends (RFC-003).

The vault#

A program that holds an API key can leak it: into a log, a commit, or a response it echoes. The vault keeps credentials in the style of Plan 9's factotum: a world holds a use-only CredHandle, never the secret. The vault has no clock, threads, sockets, or entropy of its own.

  • No read. VaultApi stores, describes, materializes a header, captures minted secrets, and scrubs. Nothing returns a secret to a caller. Storing needs the setup token, which pluricsd holds and uses only to serve VaultStore on the host control socket, the call plsh vault add makes. Materializing needs the egress token, which only the gateway holds. Token comparisons run in constant time.
  • Redacted bytes. SecretBytes prints as [REDACTED:CRED] in every format and is zeroed on drop. The vault refuses secrets shorter than 8 bytes.
  • Named injection. Each credential is bound to a scheme, host, header, and prefix, such as Authorization: Bearer. A request outside the binding fails closed. The kinds are Bearer, Basic, an API-key header, and a cookie.
  • Signing. A signing credential computes HMAC-SHA256 inside the vault, over a canonical request (method, host, path, timestamp, and the SHA-256 of the body), under the domain PLURICS-HMAC-SHA256, within five minutes of clock skew. A signing key is never injected as a header, and a header secret never signs.
  • Mint capture. A rule names a host and a response header or JSON pointer. When a secret is minted there, such as a new token, the vault stores it and replaces it with a handle before the response reaches the world.
  • Reflection scrubbing. A secret's scrub set is its raw bytes plus standard and URL-safe base64 at every alignment, percent-encoding, and JSON string escaping. The scrubber replaces the union of all match intervals, one marker per run. StreamScrubber holds back any suffix that could still grow into a match across a read boundary, reruns its passes as a cascade, and fails closed if a last pass would still redact.
  • Durable store. pluricsd keeps vault.key and vault.sealed, both mode 0600. A sealed snapshot is PLVAULT1 ‖ nonce ‖ ciphertext ‖ tag: a BLAKE3 keystream and a keyed BLAKE3 MAC under independently derived keys. The vault checks the tag in constant time before it decrypts a byte, and no plaintext secret reaches disk.

Crash safety#

The test from the opening exercises every piece above at once. A stand-in forge honors idempotency keys and echoes the Authorization header back, and the test kills the effect service at every step of creating a draft pull request. Across 100 runs, it takes 199 boots, 99 crashes at the nine ledger and effect crash points, and 42 network cuts before and after the forge commits. The result is 100 pull requests with no duplicates, a verified hash chain, and no occurrence of the token in responses, journals, ledger records, or the raw SQLite files (RFC-004).