The inf3r peer protocol — wire 2

docs/protocol.md · wiki index

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 not a process. A plugin is not a directory. The catalogue and the frames describe the plugin, not the bundle.

2. Six principles

  1. The header is one word. 8 bytes. No varints. No name lengths.
  2. Streams, not jobs. A frame carries a u16 stream id. A UUID never touches a frame.
  3. Three states per job. open → (accept | reject) → done. Nothing else is legal, and every path has a terminal frame.
  4. 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.
  5. Media is a file descriptor or inline bytes. No path. No blob id. No hash.
  6. 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  |
 +--------------------+--------+--------+--------+

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.

typeframedirstreambody
0x01hello→0version range, role, peer id
0x02welcome←0version chosen, max_inflight
0x03catalogue←0the static description of the server
0x04grant→0one file descriptor per declared dependency
0x05ready←0load time, measured
0x06window→ncredit, absolute
0x07ping↔0sender time
0x08pong↔0the same time, echoed
0x09bye→0drain and close
0x0afatal↔0code and detail. Close now.
0x10open→njob envelope, initial credit, part descriptors
0x11accept←nestimated duration, or null
0x12event←nchannel, mime, opaque bytes
0x13done←noutcome, artifacts, usage, meta
0x14reject←ncode and detail
0x15cancel→nreason
0x20cache_lookup←0prefix chain, optional lineage
0x21cache_lookup_res→0hit or null, plus a read descriptor
0x22cache_release←0lease id, restore result
0x23cache_reserve←0key, lineage, size, prefill
0x24cache_grant→0writable temp descriptor or null
0x25cache_commit←0actual bytes and CRC32C
0x26cache_flush→0save dirty slots within a budget
0x27cache_flushed←0saved, 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.

  1. A new stream id is strictly greater than every id used before it, until the space is exhausted.
  2. 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.
  3. The server never allocates a stream id and never reuses one.
  4. A control frame can cross a terminal frame in the other direction. A window or cancel for a stream that has ended is ignored. It is not fatal{stream}. An id that the peer never opened is fatal{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:

  1. The server cannot receive open before READY.
  2. grant is optional. A server with no dependencies goes from CATALOGUED to LOADING with an empty grant, or straight to READY.
  3. ready reports 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.
  4. bye means: 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.
  5. 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
  1. reject is legal only in OPEN. It is the last moment at which the server has spent nothing that it cannot give back.
  2. done is legal only in ACTIVE.
  3. Every job ends with exactly one terminal frame: done or reject. A stream that closes without one is fatal{stream} for the whole session.
  4. cancel is legal in any state. The server answers reject{cancelled} in OPEN and done{cancelled} in ACTIVE.
  5. done.outcome is completed | failed | cancelled | expired. reject.code is a refusal reason. The two vocabularies do not overlap.
  6. The server sends the events of one stream in one total order. Channels do not interleave independently; the single writer defines the order.
  7. done.meta is a map that the vocabulary defines. The caller stores it and never reads it. An absent meta means {}. 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:

  1. Terminal frames are never credit-limited. done, reject, and fatal always send. If they were limited, a full window would deadlock the frame that closes the stream.
  2. 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 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 }
  1. An input part is inline bytes or a file descriptor that the caller sends with open.
  2. An output artifact is inline bytes or a file descriptor that the server sends with done.
  3. A file descriptor is passed as SCM_RIGHTS ancillary data on the same SOCK_STREAM write as the first byte of the frame. The body names it by its index in the ancillary array.
  4. Ownership transfers on receipt. SCM_RIGHTS duplicates the descriptor. The sender closes its copy immediately after the write returns.
  5. The sender closes every descriptor it does not pass.
  6. The server reads an input descriptor through a bounded offset window. A plugin in another language may mmap the descriptor; the caller may sendfile an 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 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.

  1. A key is an opaque 32-byte prefix boundary. The plugin sends the deepest key first and the shortest last.
  2. A lookup hit carries one read descriptor. The plugin closes it and answers cache_release { ok, restore_ms, abandoned }. A corrupt restore says ok = false; the core deletes the entry and the plugin erases the slot. A caller that timed out before restoring sends abandoned = true: the lease is released without a hit or a corrupt verdict.
  3. 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.
  4. A miss erases the slot unconditionally, even when the cache is disabled.
  5. A tip may name its supersedes key. The core retires the parent unless it is pinned or an anchor. Two lineages promote a shared parent to an anchor.
  6. 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.
  7. cache_flush is bounded by budget_ms. The plugin saves what it can; the core kills the process when the budget ends. D13 is unchanged.
  8. 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.

  1. target.toml and models/*.toml belong to the plugin. They are how the plugin produces its catalogue. The core never opens them.
  2. Two sources of truth cannot drift if there is one source of truth.
  3. A golden (catalogue.json) pins the catalogue, so a change is visible in the diff and in CI.
  4. serve names must be unique across all peers. A duplicate is ambiguous_model at discovery, never at request time.

13. Errors

One enum for fatal.code and reject.code. Each refusal maps to one HTTP code.

codeHTTPmeaning
version500no overlap in the version range
frame500unknown type, bad flags, or bad framing
stream500unknown stream, or a stream closed without a terminal frame
size400a frame or a part is larger than one frame and is not an fd
credit500a window value below the current one
busy429max_inflight is reached
unknown_model404the model name is not in the catalogue
capability400the model does not declare the capability
part400the kind, mime, or role is not permitted
dependency503a declared dependency could not be granted
timeout504the budget expired
cancelled—the caller cancelled
internal502the server failed

detail is a string for humans and logs. Nothing branches on it.

14. Deliberately absent

15. Why it is better than the obvious choices

inf3r wireHTTP/JSONgRPCJSON-lines
framing8 bytes, fixedtext and chunkingHTTP/2 and HPACKnewline
schema in the data pathnone, payload opaquenoneprotobufnone
code generatornonenonerequirednone
backpressurecredit, reaches the kernelnoneHTTP/2 windownone
cancelflag, one stepclose the socketRST_STREAMclose the socket
bulk mediafd, zero copybase64 multipartbase64 in messagesbase64
authinherited descriptortoken or mTLSTLStoken
a conforming peerunder 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

  1. u16 stream ids. 65 535 concurrent streams per socket. Nothing needs that today. A larger space is a new wire, which is the friction we want.
  2. 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.
  3. grant by 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.