RFC-001: Worlds, values & ports

A shell script running inside a Plurics world named job can fork two children of job, try a different change in each, keep one, and discard the other, all without leaving job. This RFC specifies what makes that possible and safe: identifiers and classes, port grants, the world store, base images, closed-world execution, and the protocol.

$ plsh exec job --grant fork,exec,seal,diff,commit,discard --mount-plsh -- sh -c '
  plsh world fork a && plsh world fork b
  plsh exec a -- sh -c "echo v=a > app.conf"
  plsh exec b -- sh -c "echo v=b > app.conf"
  plsh world seal a && plsh world merge a && plsh world discard b'
forked a from self (id f25638fcf260)
forked b from self (id 480747abacdc)
sealed a at seq 6: value 85c005a5c952
fast-forwarded job to a: value 85c005a5c952
discarded b
$ plsh file read job app.conf
v=a

A world is a closed environment in which unmodified programs run. It forks cheaply, in O(1) on btrfs, seals into a value, and reaches the outside only through ports. In the session above, --grant gives the script's port six verbs, and --mount-plsh puts the plsh binary inside job. Everything else follows from the rules below.

Identifiers#

f25638fcf260 above is the first 12 hex digits of a 16-byte WorldId. Every byte identifier prints and parses as lowercase hex, and plsh shows its first 12 digits. Counter identifiers wrap a u64. Every hash is BLAKE3-256.

IdentifierFormNames
WorldId16 bytesA world
ValueId32 bytesA sealed world state, a commit, a base image
EffectId32 bytes, B3("effect" ‖ run_root ‖ lineage ‖ u64_be(seq))An external effect in the ledger
IdemKey32 bytes, B3("idem" ‖ EffectId)The idempotency key sent with an effect, as pl1_… on the wire
RunRoot32 bytesThe root hash binding a run's harness and base world
PortId, QuotaNodeId, ReservationId, BrokerEpoch, PrincipalIdu64A port, a quota node, a hold, a quota broker epoch, a principal
ContentHash[u8; 32]File contents and trees

Classes#

Not every path in a world should fork, seal, and merge the same way. Source files belong in a world's identity; target/ does not. A path's mount class decides how it forks, seals, and merges. The world store first assigns each path one of six storage classes. It reads .plurics/classes.toml, then conventions such as target/ and node_modules/, and otherwise uses tracked. The storage classes map onto four mount classes:

MountClassStorage classesBehavior
Statetracked, db, streamDiffed, sealed into values, and merged
Cachederived, such as target/ and node_modules/Shared copy-on-write across forks, excluded from identity, never merged
EphemeralscratchWorld-private scratch, dropped on seal and fork
MirrormirrorA read-only restatement of an external source, never in identity

A binding's persistence class decides what happens to it when its world forks, restores, or restarts:

PersistenceClassMeaning
DurableNames a persistent world, service, or quota identity. Rebound automatically.
SessionA live session that a broker can re-establish
EphemeralBound to one live instance. Dropped on restore or fork.
LinearSingle-use authority, stored by reference to its ledger record
LeaseA time-bounded exclusive right with a fencing epoch
TemporalA timer or deadline

A ProvenanceMark records where a write's data came from, at world grain. Marks form a join semilattice, Clean ⊑ Custom(name) ⊑ ExternalIngress, and two custom marks join to their sorted union. A world's mark is the join of its writes' marks. The ledger stores a 32-byte digest, all zeros for Clean.

A DeterminismSpec fixes a world's clock (Host or Virtual(ns)), entropy (Host or Seeded(seed)), and network (Closed or LocalOnly). DeterminismSpec::deterministic(seed) is a virtual clock at zero, seeded entropy, and a closed network. No network mode has a route out: egress always crosses a port.

Ports and grants#

A port carries a PortGrants value: a bit set over the PortGrants below, each of which allows one verb. Doc comments are abridged here:

#[repr(u32)]
pub enum PortGrant {
    WorldFork = 1 << 0,      // world.fork
    WorldExec = 1 << 1,      // world.exec; also writes files
    WorldSeal = 1 << 2,      // world.seal
    WorldDiff = 1 << 3,      // world.diff; also lists and reads
    WorldCommit = 1 << 4,    // world.commit: merge into a target
    WorldDiscard = 1 << 5,   // world.discard; also rewinds
    EffectInvoke = 1 << 6,   // effect.invoke: stage, read, drop
    QuotaRead = 1 << 7,      // quota.read
    QuotaGrant = 1 << 8,     // quota.grant and thaw, to descendants only
    VaultUse = 1 << 9,       // use, never read, vault credentials
    ControlAdmin = 1 << 10,  // status and daemon administration
    EffectRelease = 1 << 11, // release a descendant's clean outbox
}

Six rules bound what a port can do:

  • Descent. A child's grants must satisfy child.is_subset_of(parent), which is child & !parent == 0. A fork's --grant caps what its ports may carry, and a world can pass on only grants it holds.
  • Scope. A world's port reaches only that world and its descendants. Inside a world, self names the caller. Any other name resolves among the caller's subtree, and naming a world outside it fails with Denied.
  • Mounts. A world may pass read-only binds to the worlds it runs only for host paths it was itself given. The daemon compares paths after resolving symbolic links (canonical_bind_source), and the sandbox mounts the resolved path, so a link inside a granted directory cannot reach past it. No caller, not even the host socket, may bind the daemon's data root, or a path above or below it, into a world.
  • Images. A world's base image passes to its forks and rewinds. Inside a world on a base image, a caller cannot switch to another image, fall back to the host's /usr, or bind host paths.
  • Egress. A world may pass on at most a subset of its own egress routes and CONNECT hosts.
  • Control. From inside a world, WorldExecWait, WorldExecCtl, and WorldExecAttach reach only an execution that the caller's subtree started, running in that subtree, on the same base image, and holding no grant, host bind, plsh mount, or egress beyond the caller's own.

Wire names run from world_fork to effect_release. The parser also takes their hyphenated spellings and the short names fork, exec, seal, diff, commit, discard, effect, vault, admin, and release.

The world store#

The world store does no I/O of its own. It reaches the file system through CowFs, which the host implements in three tiers, probing the data root to choose one:

TierMechanismFork cost
Subvolumebtrfs subvolume snapshotO(1)
ReflinkPer-file FICLONE on Linux, clonefile on macOSO(files), no data copied
CopyA full copy, for ext4 and tmpfsO(bytes)
  • Fork clones the working copy and adds a row to the head table. Executable bits survive fork, seal, and merge.
  • Seal hashes the State paths into a history-independent BLAKE3 tree and moves the world's head to the new ValueId.
  • Conflicts are values. A Conflict<T> holds terms adds and removes, with one more add than removes, read as A + (C − B) in the style of Jujutsu. Rebasing concatenates terms, and simplification cancels equal pairs, so backing a change out restores the prior state exactly.
  • Merge drivers are pure and versioned: tier1.diff3, a Myers O(ND) line merge, and tier3.json-lens, a key-wise JSON merge. Each merged entry records the driver and version that produced it.
  • Inert conflicts. A conflicted world never integrates into a protected line. The root world that init imports is protected, so a merge into it stops and reports the conflicted paths instead.
  • Receipts. A Receipt records a hermetic run's read set: every input path and its hash. valid_for(receipt, tree) holds when every input still has the same hash. Nothing re-executes, and a change to an unread path keeps the receipt valid.

Base images#

By default, a world's programs come from the host's /usr. Host package updates then change what a world runs, and a world sealed today may not run the same way next month. A base image fixes that: an immutable root file system that is itself a value. plsh image import tools --minimal /bin/sh,/usr/bin/sqlite3 builds an image named tools from two host binaries and the libraries they load, and plsh world fork job --image tools forks a world that runs on it.

ImageImport reads a host directory, or a list of host binaries and their libraries, and names the result by a BLAKE3 hash under the domain plurics.image.v1. The hash covers each entry's relative path, kind, executable bit, length, and contents, or a symbolic link's target. Times, owners, inodes, and the host path play no part, so the same tree imported on any host is the same value. The daemon keeps it read-only in images/<value>/, and only the host socket may import one. ImageList lists images by name, value, file count, and size.

A world records the image it runs on, and every execution in it uses that image. bwrap then mounts the image's top-level entries read-only as / and binds nothing of the host's /usr, /bin, /lib*, /sbin, or /etc.

Closed-world execution#

A world's program runs unmodified. Every execution goes through a WorldRunner, and Status reports the runner's capabilities (RunnerCaps): live memory fork, deterministic mode, freeze, terminals, and base images. The default runner, BwrapRunner, uses unprivileged bwrap:

  • --unshare-all unshares every namespace: user, mount, PID, network, IPC, and UTS. --die-with-parent kills the sandbox with its supervisor.
  • --clearenv clears the environment to PATH, HOME, TMPDIR, and TERM, plus what the request adds. HOME and /tmp are empty private tmpfs mounts.
  • The sandbox never binds the host's home directories, /root, /var, or the daemon's control socket. Without a base image, it binds /usr, the top-level runtime directories, and a few files under /etc read-only. With one, it binds the image instead.
  • The working copy, at /work, is the only writable host path.
  • The doors out are /run/plurics/port.sock and /run/plurics/egress.sock, each present only if the request asks for it.

When the host delegates a cgroup, each execution gets a fresh child of the daemon's own cgroup. This backend, bwrap+cgroupv2, uses the cgroup's files:

  • Freeze and thaw: cgroup.freeze.
  • Kill: cgroup.kill.
  • Memory cap: memory.max, where the memory controller is delegated.
  • CPU cap: cpu.max, where the CPU controller is delegated.
  • CPU time: cpu.stat.

Elsewhere, bwrap+pgid signals the process group.

ExecCtl is freeze, thaw, kill, or status. An ExecState is running, frozen, exited, killed, or timed_out. Reader threads drain output into bounded buffers, 1 MiB per stream by default and at most 16 MiB, so a noisy child never blocks on a full pipe. The ExitReceipt reports the exit code, the captured streams, whether either was truncated, the wall time, and the CPU time of the whole tree.

Terminals and live output. A request with a pty of rows and cols gets a fresh pseudo-terminal as its standard streams and controlling terminal. plurics-relay hands the program foreground job control, so ^C reaches only the program. Output also streams live to subscribers, each of which first receives up to the newest 256 KiB already written.

Virtual machines. pluricsd serve --runner vm selects QemuKvmRunner, which boots each execution in a fresh KVM micro-VM under QEMU with no network device:

  • The guest boots from an initramfs: the base image, a small bootstrap runtime under /.plurics, and /init. The bootstrap carries its own shell, mount, umount, sync, their libraries, and their dynamic linker, so an image that holds only one program and its libraries still boots. The daemon caches packed images, so a later boot on the same image skips the packing.
  • /work is an ext4 disk image. Standard output, standard error, and the port travel over virtio-serial channels.
  • When the guest exits cleanly, the daemon copies /work back into the working copy with debugfs under bwrap. The guest is root and can write its disk raw, so the disk image is untrusted input. The daemon lists it first and refuses it unless everything debugfs would write, with every hole filled and every hard link copied, fits in the disk image's own size. It caps each file it writes, and it drops set-user-ID, set-group-ID, and sticky bits. A killed or timed-out guest changes nothing on the host.
  • This runner freezes an execution by stopping its whole QEMU process. It gives no terminal and no egress door.
  • The VM runner can also fork a running machine, memory, devices, and disk included, and gives the child a fresh generation ID so the two draw different random numbers. The daemon does not offer that as a world verb yet, so RunnerCaps reports live_fork: false.

When a process ends. A process writes straight into the world's working copy, world/wd/<n>/. When it ends, the daemon charges the bytes it wrote to cow_bytes (RFC-003) and stores the world's record in ledger.db.

Verification. WorldVerify takes a world, a command, its environment, read-only binds, a timeout, and optionally an image. It forks a zero-grant world holding exactly the sealed value and runs the check in it, on the world's base image if it has one. While the check runs, no request can name the copy or see its execution, and the check's compute_ms and cow_bytes go to the verified world. The daemon then journals a Verdict that binds the value, pass or fail, the exit code, and the hashes of the command, its environment, its binds, the sealed tree, and the image, and it always discards the copy. The returned verdict digest covers all of that except the value itself, because the value names a commit whose time and message come from the host. The same check of the same tree on the same image yields the same verdict on every host.

Recursion#

A world calls the same verbs as the host. In the opening session, the inner plsh reaches the daemon over /run/plurics/port.sock, and every verb it calls is checked against that port's grants.

The inner plsh exec is not a nested sandbox. The daemon runs it in world a, with no port unless the caller passes grants it holds. Without a grant, or without a network door, the world is closed:

$ plsh exec job --grant diff --mount-plsh -- plsh world fork c
plsh: Denied: this port does not carry world_fork
plsh: exec 6 in job exited with status 1
$ plsh exec job -- sh -c 'cat < /dev/tcp/1.1.1.1/80'
sh: connect: Network is unreachable
sh: line 1: /dev/tcp/1.1.1.1/80: Network is unreachable
plsh: exec 1 in job exited with status 1

Protocol#

The control socket and every port speak newline-delimited JSON-RPC 2.0. Each message is one JSON object on one line of at most 16 MiB (MAX_RPC_LINE). A request has jsonrpc, id, method, and named params. A response echoes the id and carries exactly one of result and error. A fork request from inside a world looks like this:

{"jsonrpc":"2.0","id":7,"method":"ForkWorld","params":{"name":"a","from":"self"}}

An error carries the ApiErrorKind name in kind beside code and message. Service errors use code -32000 minus the kind's ordinal: NotFound, AlreadyExists, Invalid, Denied, Flow, State, Conflict, Quota, Unsupported, Io, and Unknown. Protocol errors use the standard codes, -32700 to -32603.

TCP. pluricsd serve --listen <host:port> also serves the protocol over TCP. Before the first JSON-RPC line, both ends prove they hold the same 32-byte key, by default control.key (mode 0600, 64 hex digits) in the data root, with three fixed-size frames:

server -> client  "PLURICS1" || server_nonce[32]                    40 bytes
client -> server  "PLURICS1" || client_nonce[32] || mac_c2s[32]     72 bytes
server -> client  mac_s2c[32]                                       32 bytes

Each MAC is a keyed BLAKE3 hash over a direction label and both nonces, checked in constant time, so a recorded exchange replays against no fresh nonce and a reflected MAC fails the other direction. The server allows at most 32 connections in the handshake at once, each for at most 5 seconds. After the handshake, both ends derive a session key per direction from the key and both nonces and wrap every subsequent JSON-RPC message in encrypt-then-MAC frames: a BLAKE3 XOF keystream and a keyed BLAKE3 tag over a 64-bit sequence number, the length, and the ciphertext. A tampered, dropped, replayed, or reordered frame fails its tag and closes the session.

Streams. WorldExecStream and WorldExecAttach hold their connection until the execution ends and interleave JSON-RPC notifications, messages with no id, before the final response. The daemon sends exec.started and exec.output, whose stream is stdout, stderr, or pty and whose data_b64 is padded standard base64. The client may send exec.input (at most 64 KiB decoded), exec.resize, exec.ctl, and exec.detach. Leaving WorldExecStream kills its execution, so a closed terminal leaves no process behind. exec.detach on WorldExecAttach leaves the execution running and answers with its status and "detached": true. A request sent during a stream gets INVALID_REQUEST.

Each method needs one grant, with three exceptions. Ping needs none. EffectStage also needs vault_use when it names a credential. And OutboxList and EffectBundle also answer a port that carries effect_release alone, so a reviewer reads the outboxes it reviews without the right to stage into them:

GrantMethods
NonePing
control_adminStatus, InitRepo, ImageImport, VaultStore, EffectReconcile, Gc, Shutdown
world_forkForkWorld
world_diffListWorlds, WorldDiff, ReadFile, ImageList
world_sealSealWorld
world_commitMergeWorld
world_discardRewindWorld, DiscardWorld
world_execWriteFile, WorldExec, WorldExecStart, WorldExecStream, WorldExecAttach, WorldExecCtl, WorldExecWait, WorldExecList, WorldVerify
vault_useVaultDescribe, VaultList
effect_invokeOutboxList, EffectStage, EffectDrop, EffectBundle
effect_releaseEffectRelease
quota_readQuotaList
quota_grantQuotaGrant, QuotaThaw

These control_admin methods are served on the host control socket only: InitRepo, ImageImport, VaultStore, EffectReconcile, Gc, and Shutdown. Status also answers on a world's port, without the data root's path. A world cannot rewind itself from inside its own execution. Inside a world, EffectStage and EffectDrop act on the caller's own outbox only, and EffectRelease reaches only a strict descendant's clean outbox (RFC-002).

A request names a world by hex id or by name; for a name, the newest live world with that name wins. A world row is {id, name, parent, lineage, head, head_seq, state, provenance, dirty, workdir, image, outbox_count}, plus its quota fields when the world has its own quota node. A world caller never sees workdir, and outbox_count is null while a release is in flight.