The inf3r peer protocol — wire 2
Claim: one 8-byte header, 24 frame types, 3 job states, 7 session states, one structural size ceiling, and no tunable numbers. Wire 1 peers still negotiate.
This document is normative. The machine grammar is spec/protocol.cddl. If the
two disagree, the grammar is wrong and this document is right, because the
grammar is generated from the rules here.
1. What it is
One protocol connects any two inf3r processes. The pairs are core to plugin, core to web, and core to cli. A peer either calls (opens jobs) or serves (runs jobs). A process can be both.
The core serves fronts and calls plugins. The framing is the same in all directions. There is no separate plugin API. A plugin is the first peer that serves.
1.1 Three words
- A bundle is a self-contained directory for one model, one target, one
engine. In a checkout it lives below
plugins/<model>/<target>/; a release carries no real-model bundle. It is the unit of work. Section 5 of the specification. - An engine is the code inside a bundle that runs inference. It is authored or bound, and it can be any language.
- A plugin is the process that a bundle becomes when the core starts it. It is the role on this wire. This document uses "plugin" only in that sense.
A bundle is not a process. A plugin is not a directory. The catalogue and the frames describe the plugin, not the bundle.
2. Six principles
- The header is one word. 8 bytes. No varints. No name lengths.
- Streams, not jobs. A frame carries a
u16stream id. A UUID never touches a frame. - Three states per job.
open → (accept | reject) → done. Nothing else is legal, and every path has a terminal frame. - Credit is the backpressure. The consumer states how much it will accept. The producer blocks when it has no credit. There is no buffer to size.
- Media is a file descriptor or inline bytes. No path. No blob id. No hash.
- The core decodes envelopes and never payloads. Routing needs the envelope only.
3. The frame
0 4 6 7 8
+--------------------+--------+--------+--------+
| length (u32 LE) | stream | type | flags |
+--------------------+--------+--------+--------+
length: payload bytes, little-endianu32. The header is not included. The value is at most0xFFFFFF; a larger value is a frame error.stream:0is a session frame. Any other value is a job stream.type: one byte from the table in section 4.flags: must be0in wire 2. It is reserved so a later wire can add per-frame meaning without a new header.
The length is at most 0xFFFFFF. Thus the largest frame is 16 MiB. That ceiling is the
wire format, not a setting. A part that is larger than one frame must be a
file descriptor. There is nothing to negotiate and nothing to tune.
The header is one 64-bit load, one mask, three shifts.
4. Frames
Two roles share one table. → is caller to server. ← is server to caller.
| type | frame | dir | stream | body |
|---|---|---|---|---|
0x01 | hello | → | 0 | version range, role, peer id |
0x02 | welcome | ← | 0 | version chosen, max_inflight |
0x03 | catalogue | ← | 0 | the static description of the server |
0x04 | grant | → | 0 | one file descriptor per declared dependency |
0x05 | ready | ← | 0 | load time, measured |
0x06 | window | → | n | credit, absolute |
0x07 | ping | ↔ | 0 | sender time |
0x08 | pong | ↔ | 0 | the same time, echoed |
0x09 | bye | → | 0 | drain and close |
0x0a | fatal | ↔ | 0 | code and detail. Close now. |
0x10 | open | → | n | job envelope, initial credit, part descriptors |
0x11 | accept | ← | n | estimated duration, or null |
0x12 | event | ← | n | channel, mime, opaque bytes |
0x13 | done | ← | n | outcome, artifacts, usage, meta |
0x14 | reject | ← | n | code and detail |
0x15 | cancel | → | n | reason |
0x20 | cache_lookup | ← | 0 | prefix chain, optional lineage |
0x21 | cache_lookup_res | → | 0 | hit or null, plus a read descriptor |
0x22 | cache_release | ← | 0 | lease id, restore result |
0x23 | cache_reserve | ← | 0 | key, lineage, size, prefill |
0x24 | cache_grant | → | 0 | writable temp descriptor or null |
0x25 | cache_commit | ← | 0 | actual bytes and CRC32C |
0x26 | cache_flush | → | 0 | save dirty slots within a budget |
0x27 | cache_flushed | ← | 0 | saved, skipped, dirty remaining |
0x20–0x3f is reserved for this document. The cache frames occupy 0x20–0x27.
0x40–0x7f is the extension range:
a peer ignores an unknown frame there. Any other unknown type is
fatal{frame}.
An extension frame must never be necessary. A peer that ignores the whole extension range must still complete every job correctly. If a feature cannot meet that rule, it is a wire change and not an extension.
5. Streams
The caller allocates the stream id. The caller owns the whole space. There is no odd/even split, because a stream is opened in one direction only.
- A new stream id is strictly greater than every id used before it, until the space is exhausted.
- When the space is exhausted, the caller may reuse an id only after it has received the terminal frame of the previous stream with that id. At that point both peers have seen the end of that stream and the transport is ordered, so reuse is unambiguous.
- The server never allocates a stream id and never reuses one.
- A control frame can cross a terminal frame in the other direction. A
windoworcancelfor a stream that has ended is ignored. It is notfatal{stream}. An id that the peer never opened isfatal{stream}.
Rule 2 is the reason a plugin can stay resident forever. u16 gives 65 535
concurrent streams, and reuse makes sequential use unbounded. A reconnect would
unload the model, which is the expensive thing this engine exists to avoid.
The caller keeps the map stream → job. The server never sees a job id. The
request_id travels once, inside open, for log joins.
6. Session lifecycle
NEW
└─ hello → HELLO
HELLO
├─ welcome ← WELCOMED
└─ fatal ↔ CLOSED
WELCOMED
└─ catalogue ← CATALOGUED
CATALOGUED
└─ grant → LOADING
LOADING
├─ ready ← READY
└─ fatal ↔ CLOSED
READY
├─ open → READY
├─ bye → DRAINING
└─ fatal ↔ CLOSED
DRAINING
└─ last terminal frame → CLOSED
Rules for the session:
- The server cannot receive
openbeforeREADY. grantis optional. A server with no dependencies goes fromCATALOGUEDtoLOADINGwith an empty grant, or straight toREADY.readyreports the load time that the server measured. The catalogue declares an expected load time. After the first cold start, the caller uses the measurement instead of the expectation. A declared load time is advice, not a deadline.byemeans: send no new jobs. Finish the open jobs. Then close. The drain window is the sum of the remaining budgets of the open jobs. There is no other timeout.- If both peers send
fatal, the first one wins. The second is ignored. Both processes close the socket.
7. Job lifecycle
open ─► OPEN ──accept──► ACTIVE ──done──► CLOSED
└──reject──► CLOSED
rejectis legal only inOPEN. It is the last moment at which the server has spent nothing that it cannot give back.doneis legal only inACTIVE.- Every job ends with exactly one terminal frame:
doneorreject. A stream that closes without one isfatal{stream}for the whole session. cancelis legal in any state. The server answersreject{cancelled}inOPENanddone{cancelled}inACTIVE.done.outcomeiscompleted | failed | cancelled | expired.reject.codeis a refusal reason. The two vocabularies do not overlap.- The server sends the events of one stream in one total order. Channels do not interleave independently; the single writer defines the order.
done.metais a map that the vocabulary defines. The caller stores it and never reads it. An absentmetameans{}. This is the only place where a vocabulary can add a terminal field without a wire change.
Point 6 simplifies the server: one writer thread, no per-channel locks, and the
consumer sees a total order. The seq field in the HTTP event stream is added
by the web from that order.
8. Credit
Credit is an absolute watermark, not a delta.
open → credit = C0 // the caller's initial grant
window → credit = Cn // must be >= the previous value
The server tracks sent, the total bytes of event bodies it has sent on this
stream. It may send an event when sent + len <= credit.
Why absolute: a duplicated, delayed, or reordered window cannot corrupt the
count. window with a value below the current one is fatal{credit}.
Two rules make this do the work:
- Terminal frames are never credit-limited.
done,reject, andfatalalways send. If they were limited, a full window would deadlock the frame that closes the stream. - A reader thread must never block on the worker. The server reads control
frames —
window,cancel,bye,fatal— while the worker blocks on credit. If one thread did both, the pair would deadlock: the worker waits for credit, the caller waits for the worker to read the credit it is sending.
Rule 2 is a requirement on any implementation and on the SDK. The SDK gives every peer one reader thread and one worker per job. The reader owns the socket. The worker owns the model.
emit returns one of three values: Sent, Blocked, Cancelled. The plugin
loop is:
for token in model.stream(prompt) {
match out.emit(Channel::Text, "text/plain; charset=utf-8", token.bytes())? {
Emit::Sent => {}
Emit::Cancelled => break,
Emit::Blocked => {} // emit already waited; loop to check again
}
}
There is no buffer size in this document. The consumer's willingness is the buffer.
9. Cancellation
cancel sets a flag in the server. The flag is atomic and is set by the reader.
The worker reads it at the top of the next emit call, and at the top of its own
loop. The result is:
- the compute stops within one step, at both hops;
- no event is written after the cancel is observed;
- the server still sends its terminal frame, so the caller never waits.
The caller may then close the stream. The server closes its side after the terminal frame.
Cancellation is not a credit operation. Credit is monotonic and a cancel is not. The shared thing is the blocking point: one place to wait, two reasons to stop. That is the whole of the interaction.
10. Media
A part and an artifact are the same object, in opposite directions:
{ ch, mime, len, inline: bytes or fd: fd-index }
- An input part is inline bytes or a file descriptor that the caller sends with
open. - An output artifact is inline bytes or a file descriptor that the server sends
with
done. - A file descriptor is passed as
SCM_RIGHTSancillary data on the sameSOCK_STREAMwrite as the first byte of the frame. The body names it by its index in the ancillary array. - Ownership transfers on receipt.
SCM_RIGHTSduplicates the descriptor. The sender closes its copy immediately after the write returns. - The sender closes every descriptor it does not pass.
- The server reads an input descriptor through a bounded offset window. A
plugin in another language may
mmapthe descriptor; the caller maysendfilean output descriptor. A video artifact can travel from plugin memory to the page cache to a client socket with no copy in inf3r. The engine crates do not map: D20 in the spec gives the safe window they use.
Consequences:
- The protocol does not mention the blob store. Not once.
- A plugin needs no filesystem access to its weights.
grantgives one descriptor per dependency, resolved by the core from the catalogue. - There is no
publishframe, no temporary path, no rename, no fsync order, no time-of-check race, and no permission model for plugins. - The blob store becomes a core detail for HTTP uploads and stored artifacts.
The socket has a random path, and the kernel checks the peer uid. The core
creates a private instance directory /run/inf3r/<random>, mode 0700, binds
<random>.sock inside it, and starts the plugin with --socket <path>. The
path is random, it lives only in the core's private directory and in the
plugin's argv, and a process that was not told it cannot guess it. A path in
argv is world-readable through /proc/<pid>/cmdline, so the path is not the
whole credential: on accept, the core asks the kernel for SO_PEERCRED and
closes any connection whose uid is not the core's effective uid. There is no
separate token on this hop. The path is the token; the private directory is the
access boundary.
A container engine is a sibling with only its own instance directory mounted.
Rootless Docker maps container root to the control uid, so the uid check is the
same check in process mode and container mode. The accepted peer's pid is not
compared: it lives in the container's PID namespace and is not the control's
process handle for the sibling. The uid check is the check that survives.
A plugin connects with inf3r-plugin-sdk::launch, which is the whole
argument interface: --describe or --socket <path>. D28 in the spec records
the trust boundary.
10.1 Cache
KV cache is host-global state. The core owns the store, the quota, the TTL, and the eviction. The plugin owns the engine codec and the VRAM slot table.
The cache frames are session frames on stream 0. They are legal only after a
Wire 2 handshake and only when catalogue.cache is present. A peer that speaks
Wire 1 never receives one.
- A key is an opaque 32-byte prefix boundary. The plugin sends the deepest key first and the shortest last.
- A lookup hit carries one read descriptor. The plugin closes it and answers
cache_release { ok, restore_ms, abandoned }. A corrupt restore saysok = false; the core deletes the entry and the plugin erases the slot. A caller that timed out before restoring sendsabandoned = true: the lease is released without a hit or a corrupt verdict. - A reserve carries an estimated size and a prefill cost. A grant carries one writable temporary descriptor. The plugin writes, then commits the actual bytes and CRC32C. A dropped lease aborts the temp file.
- A miss erases the slot unconditionally, even when the cache is disabled.
- A tip may name its
supersedeskey. The core retires the parent unless it is pinned or an anchor. Two lineages promote a shared parent to an anchor. - A checkpoint-exact engine, such as a hybrid or SSM model, never rolls back to an earlier token position. The plugin derives its keys accordingly.
cache_flushis bounded bybudget_ms. The plugin saves what it can; the core kills the process when the budget ends. D13 is unchanged.- No path, prompt, token, or chat template crosses these frames.
11. Encoding
The frame body is a CBOR item with a grammar in spec/protocol.cddl. Every
event and done payload is an opaque byte string. The protocol never looks
inside one.
Why CBOR: self-describing, no code generator, and a C, Zig, Python, or Go peer needs no build step. A fixed hand-rolled layout would be faster, but the envelope is a few hundred bytes per job and its cost is invisible next to the inference. Protobuf would add a code generator to the exact case we want to support: wrapping a vendored repository.
A JSON mirror exists as a conformance mode (--protocol json). It is not a
production mode. It makes the goldens diffable and lets a human read a trace.
The core decodes the envelope and never the payload. The web decodes the payload and never routes. Each byte has exactly one decoder.
12. The catalogue is the only manifest
The core learns everything about a peer from catalogue. It does not read the
plugin's own files.
Catalogue = {
target: { id, backend, arch, devices, vram_mb },
models: [ { serve, alias_of, capabilities: { * name => Capability } } ]
}
Capability = { vocab, parts: [kind], channels: [name], limits: { * k => uint } }
The core reads two limits for the ledger: context is the token window and
kv_bytes_per_token is the cache of one token. Their product is the KV part of
a load; the weights are weights_bytes.
target.tomlandmodels/*.tomlbelong to the plugin. They are how the plugin produces its catalogue. The core never opens them.- Two sources of truth cannot drift if there is one source of truth.
- A golden (
catalogue.json) pins the catalogue, so a change is visible in the diff and in CI. servenames must be unique across all peers. A duplicate isambiguous_modelat discovery, never at request time.
13. Errors
One enum for fatal.code and reject.code. Each refusal maps to one HTTP code.
| code | HTTP | meaning |
|---|---|---|
version | 500 | no overlap in the version range |
frame | 500 | unknown type, bad flags, or bad framing |
stream | 500 | unknown stream, or a stream closed without a terminal frame |
size | 400 | a frame or a part is larger than one frame and is not an fd |
credit | 500 | a window value below the current one |
busy | 429 | max_inflight is reached |
unknown_model | 404 | the model name is not in the catalogue |
capability | 400 | the model does not declare the capability |
part | 400 | the kind, mime, or role is not permitted |
dependency | 503 | a declared dependency could not be granted |
timeout | 504 | the budget expired |
cancelled | — | the caller cancelled |
internal | 502 | the server failed |
detail is a string for humans and logs. Nothing branches on it.
14. Deliberately absent
- no blob vocabulary, no path, no hash on the wire
- no retry, ack, sequence number, or resume; the transport is an ordered local socket, and a dead socket is a dead peer
- no job id, request id, or timestamp on every frame
- no per-frame deadline; one relative
budget_msperopen, so queue time is counted and clock skew cannot exist - no priority on the wire; the caller orders its own queue
- no batching frame; batching is internal and invisible
- no TLS, no token, no application auth; the kernel's peer credentials are the authentication
- no compression
- no progressive input; a v1 job is fully specified before
open. Continuous input is an extension, and it must obey section 4's rule - no progress protocol;
progressis a channel like any other - no flow-control negotiation; one absolute watermark per stream
- no human-readable mode in production
15. Why it is better than the obvious choices
| inf3r wire | HTTP/JSON | gRPC | JSON-lines | |
|---|---|---|---|---|
| framing | 8 bytes, fixed | text and chunking | HTTP/2 and HPACK | newline |
| schema in the data path | none, payload opaque | none | protobuf | none |
| code generator | none | none | required | none |
| backpressure | credit, reaches the kernel | none | HTTP/2 window | none |
| cancel | flag, one step | close the socket | RST_STREAM | close the socket |
| bulk media | fd, zero copy | base64 multipart | base64 in messages | base64 |
| auth | inherited descriptor | token or mTLS | TLS | token |
| a conforming peer | under 200 lines | — | runtime plus codegen | — |
The last row is the one to defend. A conforming peer is a small program, not a project. That is what "any language" has to mean.
16. The implementation test
If this protocol is right, the conformance plugin is trivial: describe a
catalogue, accept every open, emit three events, done. No model, no weights,
no GPU.
Then the whole engine — discovery, routing, admission, residency, eviction, SSE byte-exactness, cancellation, ledger release on crash — is provable by two processes on a socket. That is what lets the engine exist before any inference engine is written.
17. Three things still open
u16stream ids. 65 535 concurrent streams per socket. Nothing needs that today. A larger space is a new wire, which is the friction we want.- Credit in bytes. It is precise and costs one addition. Credit in events is easier to reason about but lies about the cost of a large frame.
grantby descriptor means the core owns path resolution. That removes filesystem access from plugins, which I think is the larger win. It also means a plugin cannot open its weights itself, even if it wants to.