# IPC

Session handshake, shared memory layout and record rules for custom clients of the local agent's IPC interface

Source: https://zerocopy.sh/docs/reference/ipc

Use this reference when implementing a client for the local agent's Linux shared memory interface. The [transaction senders](#example) include Rust, Go and TypeScript clients; the [standalone C example](/docs/examples/swqos-ipc-send.c) is also available. For agent setup, see [Local interfaces](/docs/swqos/agent/local-interfaces#ipc).

All multi-byte integers are little-endian. Access control words with aligned 32-bit or 64-bit atomic operations and the memory ordering below. Plain loads and stores are not sufficient for those words.

## Session setup [#handshake]

1. Connect a Unix `SOCK_STREAM` socket to the configured `listen.ipc` path.
2. Send the four ASCII bytes `ZCI1` (`5A 43 49 31`) within 2 seconds. The hello carries no API key: the local agent sends under its executable's license.
3. Read the nine-byte reply with `recvmsg`, collecting the shared-memory file descriptor from `SCM_RIGHTS` ancillary data. A stream read can be partial; collect all nine bytes and the descriptor before proceeding.
4. Validate the capacities and use `fstat` to check the descriptor holds at least `4096 + submission capacity + completion capacity` bytes. Map that length from offset 0 with `PROT_READ | PROT_WRITE` and `MAP_SHARED`.
5. Validate the mapping header against the reply, including magic `ZCR1` and version `1`.
6. Keep the socket open and switch it to nonblocking mode. It carries wake-up bytes; closing it ends the session.

| Reply offset | Size | Field |
| --- | --- | --- |
| 0 | 1 | Reply code, `0` |
| 1 | 4 | Submission capacity in bytes |
| 5 | 4 | Completion capacity in bytes |

Read capacities from the reply; do not hard-code them. Each must be a power of two of at least 16 bytes. Treat a nonzero reply code as a refused session. An invalid hello closes the socket without a reply.

Each connection has its own mapping. Use one producer and one consumer per ring, or serialize access within your process. Separate sending threads can use separate sessions.

## Shared-memory layout [#layout]

| Offset | Size | Field | Writer |
| --- | --- | --- | --- |
| 0 | 4 | Magic `ZCR1` | Agent, once |
| 4 | 4 | Version `1` | Agent, once |
| 8 | 4 | Submission capacity | Agent, once |
| 12 | 4 | Completion capacity | Agent, once |
| 64 | 8 | Submission tail | Client |
| 128 | 8 | Submission head | Agent |
| 192 | 8 | Completion tail | Agent |
| 256 | 8 | Completion head | Client |
| 320 | 4 | Agent parked flag | Agent sets; client clears |
| 384 | 4 | Client parked flag | Client sets; agent clears |
| 4096 | Submission capacity | Submission ring | Client |
| 4096 + submission capacity | Completion capacity | Completion ring | Agent |

The remaining header bytes are reserved. Leave them unchanged.

## Ring rules [#rings]

The client produces submissions and consumes completions. Each ring has one producer and one consumer.

### Positions [#positions]

Head and tail are monotonically increasing 64-bit byte counters, not offsets that wrap at the capacity. Both are multiples of 16, `head <= tail`, and `tail - head <= capacity`. The byte offset of a position is `position % capacity`.

Use acquire loads for the peer's counter and release stores to publish your own counter. Do not wrap a counter through zero.

### Records [#records]

A record contains a 16-byte header, the payload, then zero padding to a multiple of 16 bytes. Its total size is `(16 + payload_length + 15) & ~15`.

| Header offset | Size | Field |
| --- | --- | --- |
| 0 | 4 | Payload length, excluding header and padding |
| 4 | 1 | Kind |
| 5 | 1 | Flags |
| 6 | 2 | Reserved; write 0 |
| 8 | 8 | Request ID |

A record must not cross the ring boundary. If it would, publish a pad record in the remaining bytes before writing the real record at offset 0. The pad header has kind, flags, reserved and ID all zero; its length is `remaining bytes - 16`. Consumers skip the whole remainder, without interpreting its payload.

### Writing a record [#writing]

1. Load your tail and acquire-load the consumer's head. Validate the positions.
2. Calculate the aligned record size and any boundary pad. If their sum exceeds `capacity - (tail - head)`, wait for space without publishing the record.
3. Write any pad header, then the real header, payload and alignment padding.
4. Release-store `tail + pad size + record size` as the new tail.
5. Issue a sequentially consistent fence and [wake the consumer](#doorbells) if parked.

### Reading a record [#reading]

1. Load your head and acquire-load the producer's tail. Validate alignment, ordering and the number of bytes in use. Equal positions mean the ring is empty.
2. Validate the header and payload length before reading. A real record must fit within the ring boundary, the published bytes and the payload limit for its kind. A pad must have the required zero fields and cover exactly the published remainder of the ring.
3. Copy the payload before advancing the head.
4. Release-store `head + record size`, or `head + remaining bytes` for a pad. The producer can overwrite those bytes after this store.

## Submissions [#submissions]

| Kind | Payload | Flags |
| --- | --- | --- |
| `1` | One signed transaction, bare or inside a payload envelope | `0x01` requests a completion. Also set `0x02` for preflight at `processed` commitment: flags `0x03` request both. |
| `3` | Bundle envelope containing one to four signed transactions | `0x01` requests a completion |

Payloads use the [payload envelope](/docs/reference/payload-envelope); IPC has no QUIC stream header. The submission payload limit is 16,403 bytes; the [transaction limits](/docs/swqos/transactions) still apply to each member.

Kind `1` requires a transaction payload and kind `3` requires a bundle payload. A mismatch produces `malformed` with `problem: "expected_transaction"` or `"expected_bundle"`. Other kinds produce `"invalid_record_kind"`; unsupported flag bits produce `"invalid_record_flags"`. The session stays open after these refusals.

The completion echoes the 64-bit request ID. Keep IDs distinct among outstanding requests in a session. Completions can arrive out of order.

Without `0x01`, there is no completion, including on rejection, and no preflight. Use requests with replies while integrating.

## Completions [#completions]

| Field | Meaning |
| --- | --- |
| Kind | `3` for a bundle submission, otherwise `1` |
| Flags | [Reply code](/docs/reference/quic#reply-codes); `0` means accepted |
| Request ID | The submission's ID |
| Kind `1` payload | Empty on acceptance; rejection detail otherwise |
| Kind `3` payload | 32-byte bundle ID, followed by rejection detail on refusal; a refused bundle has an all-zero ID |

Rejection detail is UTF-8 JSON of at most 65,535 bytes, using the [error fields](/docs/reference/errors). The bundle ID is the raw 32 byte value returned as hexadecimal by [`sendBundle`](/docs/reference/json-rpc/send-bundle).

An accepted reply is not proof of landing. See [local interfaces](/docs/swqos/agent/local-interfaces) and [confirmation and retries](/docs/swqos/confirmation).

Keep draining completions. If an error detail will not fit, the completion can contain only its code: an empty payload for kind `1`, or 32 zero bytes for kind `3`. If the completion ring has no room even for that, the completion is lost. Give every outstanding request a timeout.

## Doorbells [#doorbells]

A parked consumer blocks on the Unix socket. The producer clears the consumer's parked flag and writes one byte to wake it. The byte's value is irrelevant.

To wait for completions:

1. Release-store `1` in the client parked flag at offset 384, then issue a sequentially consistent fence.
2. Acquire-load the completion tail again. If data arrived, clear the parked flag and read it without sleeping.
3. Otherwise wait for socket readability, for example with `poll` and a request timeout.
4. Clear the flag with a release store, then drain wake-up bytes until the nonblocking read would block. A read of 0 means the session ended.

After publishing a submission:

1. Issue a sequentially consistent fence after the release store to the submission tail.
2. Acquire-load the agent parked flag at offset 320. If it is `1`, exchange it with `0` using sequentially consistent ordering.
3. If the exchange returned `1`, write a byte to the socket with `MSG_NOSIGNAL`. A failed or would-block wake-up write does not invalidate the published record.

The agent wakes the client the same way after publishing a completion. Implement doorbells even when [busy polling](/docs/swqos/agent/configuration#busy-poll) is enabled, so the client also works with it disabled.

## Session end and errors [#errors]

- Closing the socket ends the session, but does not cancel submissions already published.
- A stop or update closes the agent's socket. `poll` can report `POLLHUP`, or a read returns 0. Completions already published remain readable in the mapping.
- Invalid submission positions or record boundaries close the session without an error completion. Fix the producer before reconnecting.

Drain any published completions, unmap the old memory and connect again with a fresh handshake. Do not reuse the old mapping. Check transaction signatures before replaying requests whose outcomes are unknown.

## Transaction sender [#example]

These clients send one transaction with request ID 1 and no preflight, wait up to five seconds for its completion and exit with status 0 only for acceptance. Save raw signed wire bytes in a file; the clients do not construct or sign a transaction. They validate the handshake, mapping and record boundaries, copy a completion before releasing its ring space, and implement both doorbells. Empty rejection detail is allowed when the agent cannot fit the JSON in the completion ring.

Use Linux x86_64. Rust and Go are files in the [example project](/docs/reference/json-rpc#example-project); Rust also needs the `libc` crate. TypeScript requires Bun, glibc (`libc.so.6`) and GCC's atomic runtime (`libatomic.so.1`). It calls those libraries through Bun's experimental FFI, which Bun does not recommend for production. It does not run in Node.js, browsers or on musl Linux. Atomic control words use native acquire/release operations and sequentially consistent exchanges; JavaScript buffer reads alone cannot implement the ring protocol.

Download [Rust](/docs/examples/swqos-ipc-send.rs), [Go](/docs/examples/swqos-ipc-send.go) or [TypeScript](/docs/examples/swqos-ipc-send.ts). Save the Rust file as `src/bin/ipc_send.rs` and the Go file as `ipc-send/main.go` in the example project; keep the TypeScript filename unchanged. The [C client](/docs/examples/swqos-ipc-send.c) remains available, with [build instructions](/docs/swqos/agent/local-interfaces#example).

```rust title="src/bin/ipc_send.rs" tab="Rust" tab-group="language"
use std::{
    fs::File,
    io::{self, Read, Write},
    mem,
    os::fd::{AsRawFd, FromRawFd, OwnedFd},
    os::unix::net::UnixStream,
    ptr::NonNull,
    sync::atomic::{AtomicU32, AtomicU64, Ordering, fence},
    time::{Duration, Instant},
};

type Result<T, E = Box<dyn std::error::Error>> = std::result::Result<T, E>;
const HEADER: usize = 4096;
const MAX_PAYLOAD: usize = 16403;
const MAX_DETAIL: usize = 65535;

struct Session {
    socket: UnixStream,
    base: NonNull<u8>,
    length: usize,
    submission: u64,
    completion: u64,
}

impl Drop for Session {
    fn drop(&mut self) {
        unsafe { libc::munmap(self.base.as_ptr().cast(), self.length); }
    }
}

fn capacity(value: u64) -> bool { value >= 16 && value.is_power_of_two() }
fn size(length: u64) -> u64 { (16 + length + 15) & !15 }
fn u32_at(bytes: &[u8], at: usize) -> u32 {
    u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap())
}
fn u64_at(bytes: &[u8], at: usize) -> u64 {
    u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap())
}
fn positions(head: u64, tail: u64, cap: u64) -> Result<()> {
    if (head | tail) & 15 != 0 || head > tail || tail - head > cap {
        return Err("invalid ring positions".into());
    }
    Ok(())
}

impl Session {
    fn connect(path: &str) -> Result<Self> {
        let mut socket = UnixStream::connect(path)?;
        socket.set_write_timeout(Some(Duration::from_secs(2)))?;
        let deadline = Instant::now() + Duration::from_secs(2);
        socket.write_all(b"ZCI1")?;
        let mut reply = [0u8; 9];
        let mut received = 0;
        let mut descriptor: Option<OwnedFd> = None;
        while received < reply.len() {
            let left = deadline.checked_duration_since(Instant::now())
                .ok_or("IPC handshake timed out")?;
            socket.set_read_timeout(Some(left))?;
            // usize storage gives cmsghdr its required alignment.
            let mut control = [0usize; 3];
            let mut part = libc::iovec {
                iov_base: reply[received..].as_mut_ptr().cast(),
                iov_len: reply.len() - received,
            };
            let mut message: libc::msghdr = unsafe { mem::zeroed() };
            message.msg_iov = &mut part;
            message.msg_iovlen = 1;
            message.msg_control = control.as_mut_ptr().cast();
            message.msg_controllen = mem::size_of_val(&control);
            let count = unsafe { libc::recvmsg(socket.as_raw_fd(), &mut message, libc::MSG_CMSG_CLOEXEC) };
            if count < 0 {
                let error = io::Error::last_os_error();
                if error.kind() == io::ErrorKind::Interrupted { continue; }
                return Err(error.into());
            }
            if count == 0 { return Err("agent closed during handshake".into()); }
            unsafe {
                let mut entry = libc::CMSG_FIRSTHDR(&message);
                while !entry.is_null() {
                    if (*entry).cmsg_level == libc::SOL_SOCKET && (*entry).cmsg_type == libc::SCM_RIGHTS {
                        let header = libc::CMSG_LEN(0) as usize;
                        let length = (*entry).cmsg_len;
                        if length < header || (length - header) % mem::size_of::<i32>() != 0 {
                            return Err("invalid descriptor message".into());
                        }
                        let count = (length - header) / mem::size_of::<i32>();
                        for index in 0..count {
                            let fd = std::ptr::read_unaligned(libc::CMSG_DATA(entry).cast::<i32>().add(index));
                            let owned = OwnedFd::from_raw_fd(fd);
                            if descriptor.is_some() || count != 1 {
                                return Err("unexpected descriptors in handshake".into());
                            }
                            descriptor = Some(owned);
                        }
                    }
                    entry = libc::CMSG_NXTHDR(&message, entry);
                }
            }
            if message.msg_flags & (libc::MSG_CTRUNC | libc::MSG_TRUNC) != 0 {
                return Err("truncated handshake".into());
            }
            received += count as usize;
        }
        if reply[0] != 0 { return Err(format!("session refused with code {}", reply[0]).into()); }
        let file = File::from(descriptor.ok_or("handshake carried no shared memory")?);
        let submission = u64::from(u32_at(&reply, 1));
        let completion = u64::from(u32_at(&reply, 5));
        if !capacity(submission) || !capacity(completion) { return Err("invalid capacity".into()); }
        let length = usize::try_from(HEADER as u64 + submission + completion)?;
        if file.metadata()?.len() < length as u64 { return Err("shared memory is too small".into()); }
        let mapped = unsafe {
            libc::mmap(std::ptr::null_mut(), length, libc::PROT_READ | libc::PROT_WRITE,
                libc::MAP_SHARED, file.as_raw_fd(), 0)
        };
        if mapped == libc::MAP_FAILED { return Err(io::Error::last_os_error().into()); }
        let session = Self {
            socket, base: NonNull::new(mapped.cast()).ok_or("null mapping")?,
            length, submission, completion,
        };
        let header = session.bytes(0, 16);
        if &header[..4] != b"ZCR1" || u32_at(header, 4) != 1
            || u64::from(u32_at(header, 8)) != submission
            || u64::from(u32_at(header, 12)) != completion {
            return Err("unexpected shared memory header".into());
        }
        session.socket.set_nonblocking(true)?;
        Ok(session)
    }

    fn bytes(&self, offset: usize, length: usize) -> &[u8] {
        unsafe { std::slice::from_raw_parts(self.base.as_ptr().add(offset), length) }
    }
    fn word64(&self, offset: usize) -> &AtomicU64 {
        unsafe { &*self.base.as_ptr().add(offset).cast::<AtomicU64>() }
    }
    fn word32(&self, offset: usize) -> &AtomicU32 {
        unsafe { &*self.base.as_ptr().add(offset).cast::<AtomicU32>() }
    }

    fn submit(&self, id: u64, payload: &[u8]) -> Result<()> {
        let tail = self.word64(64).load(Ordering::Relaxed);
        let head = self.word64(128).load(Ordering::Acquire);
        positions(head, tail, self.submission)?;
        let record_size = size(payload.len() as u64);
        let mut offset = tail & (self.submission - 1);
        let remaining = self.submission - offset;
        let pad = if record_size > remaining { remaining } else { 0 };
        if pad + record_size > self.submission - (tail - head) {
            return Err("submission ring is full".into());
        }
        let next = tail.checked_add(pad + record_size).ok_or("submission counter overflow")?;
        unsafe {
            if pad != 0 {
                let record = self.base.as_ptr().add(HEADER + offset as usize);
                std::ptr::write_bytes(record, 0, 16);
                std::ptr::copy_nonoverlapping(((pad - 16) as u32).to_le_bytes().as_ptr(), record, 4);
                offset = 0;
            }
            let record = std::slice::from_raw_parts_mut(
                self.base.as_ptr().add(HEADER + offset as usize), record_size as usize);
            record.fill(0);
            record[..4].copy_from_slice(&(payload.len() as u32).to_le_bytes());
            record[4] = 1;
            record[5] = 1; // Request a completion, without preflight.
            record[8..16].copy_from_slice(&id.to_le_bytes());
            record[16..16 + payload.len()].copy_from_slice(payload);
        }
        self.word64(64).store(next, Ordering::Release);
        fence(Ordering::SeqCst);
        if self.word32(320).swap(0, Ordering::SeqCst) == 1 {
            let byte = 0u8;
            unsafe {
                libc::send(self.socket.as_raw_fd(), (&byte as *const u8).cast(), 1,
                    libc::MSG_NOSIGNAL | libc::MSG_DONTWAIT);
            }
        }
        Ok(())
    }

    fn read_completion(&self) -> Result<Option<(u64, u8, Vec<u8>)>> {
        loop {
            let head = self.word64(256).load(Ordering::Relaxed);
            let tail = self.word64(192).load(Ordering::Acquire);
            positions(head, tail, self.completion)?;
            let used = tail - head;
            if used == 0 { return Ok(None); }
            let offset = head & (self.completion - 1);
            let remaining = self.completion - offset;
            let record = self.bytes(HEADER + self.submission as usize + offset as usize, 16);
            let length = u64::from(u32_at(record, 0));
            let id = u64_at(record, 8);
            let kind = record[4];
            let code = record[5];
            if record[6] != 0 || record[7] != 0 { return Err("nonzero reserved bytes".into()); }
            if kind == 0 {
                if length != remaining - 16 || remaining > used || code != 0 || id != 0 {
                    return Err("invalid pad record".into());
                }
                self.word64(256).store(head + remaining, Ordering::Release);
                continue;
            }
            let record_size = size(length);
            if kind != 1 || length > MAX_DETAIL as u64 || record_size > remaining
                || record_size > used || code > 13 || (code == 0 && length != 0) {
                return Err("invalid transaction completion".into());
            }
            let payload = self.bytes(HEADER + self.submission as usize + offset as usize + 16,
                length as usize).to_vec();
            self.word64(256).store(head + record_size, Ordering::Release);
            return Ok(Some((id, code, payload)));
        }
    }

    fn wait_for(&mut self, id: u64) -> Result<(u8, Vec<u8>)> {
        let deadline = Instant::now() + Duration::from_secs(5);
        let mut ended = false;
        loop {
            while let Some((received_id, code, payload)) = self.read_completion()? {
                if received_id == id { return Ok((code, payload)); }
            }
            if ended { return Err("session ended; check the signature before retrying".into()); }
            let left = deadline.checked_duration_since(Instant::now())
                .ok_or("no completion within 5 seconds; check the signature before retrying")?;
            self.word32(384).store(1, Ordering::Release);
            fence(Ordering::SeqCst);
            if self.word64(192).load(Ordering::Acquire) != self.word64(256).load(Ordering::Relaxed) {
                self.word32(384).store(0, Ordering::Release);
                continue;
            }
            let mut watch = libc::pollfd { fd: self.socket.as_raw_fd(), events: libc::POLLIN, revents: 0 };
            let ready = unsafe { libc::poll(&mut watch, 1, left.as_millis().max(1) as i32) };
            self.word32(384).store(0, Ordering::Release);
            if ready < 0 {
                let error = io::Error::last_os_error();
                if error.kind() == io::ErrorKind::Interrupted { continue; }
                return Err(error.into());
            }
            if ready > 0 {
                ended = watch.revents & (libc::POLLERR | libc::POLLHUP | libc::POLLNVAL) != 0;
                let mut bytes = [0u8; 128];
                loop {
                    match self.socket.read(&mut bytes) {
                        Ok(0) => { ended = true; break; }
                        Ok(_) => {}
                        Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
                        Err(error) if error.kind() == io::ErrorKind::WouldBlock => break,
                        Err(_) => { ended = true; break; }
                    }
                }
            }
        }
    }
}

fn run() -> Result<bool> {
    if !cfg!(all(target_os = "linux", target_arch = "x86_64", target_endian = "little")) {
        return Err("this client requires Linux x86_64".into());
    }
    let args: Vec<String> = std::env::args().collect();
    if args.len() != 3 { return Err("usage: ipc_send SOCKET_PATH TRANSACTION_FILE".into()); }
    let mut payload = Vec::new();
    File::open(&args[2])?.take((MAX_PAYLOAD + 1) as u64).read_to_end(&mut payload)?;
    if payload.is_empty() || payload.len() > MAX_PAYLOAD {
        return Err("transaction payload must hold 1 to 16403 bytes".into());
    }
    let mut session = Session::connect(&args[1])?;
    session.submit(1, &payload)?;
    let (code, detail) = session.wait_for(1)?;
    let text = std::str::from_utf8(&detail)?;
    if !detail.is_empty() {
        let rejection: serde_json::Value = serde_json::from_str(text)?;
        if rejection.get("reason").and_then(|value| value.as_str()).filter(|reason| !reason.is_empty()).is_none() {
            return Err("invalid rejection detail".into());
        }
    }
    println!("code {code}");
    if !text.is_empty() { println!("{text}"); }
    Ok(code == 0)
}

fn main() {
    match run() {
        Ok(true) => {}
        Ok(false) => std::process::exit(1),
        Err(error) => { eprintln!("{error}"); std::process::exit(1); }
    }
}
```

```go title="ipc-send/main.go" tab="Go" tab-group="language"
package main

import (
	"encoding/binary"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"os"
	"runtime"
	"sync/atomic"
	"time"
	"unicode/utf8"
	"unsafe"

	"golang.org/x/sys/unix"
)

const headerSize = 4096
const maxPayload = 16403
const maxDetail = 65535

type session struct {
	fd int
	memory []byte
	submission uint64
	completion uint64
}

type completion struct {
	id uint64
	code byte
	payload []byte
}

func recordSize(length uint64) uint64 { return (16 + length + 15) &^ 15 }
func validCapacity(value uint64) bool { return value >= 16 && value&(value-1) == 0 }
func positions(head, tail, capacity uint64) error {
	if (head|tail)&15 != 0 || head > tail || tail-head > capacity {
		return errors.New("invalid ring positions")
	}
	return nil
}
func (s *session) word64(offset int) *uint64 { return (*uint64)(unsafe.Pointer(&s.memory[offset])) }
func (s *session) word32(offset int) *uint32 { return (*uint32)(unsafe.Pointer(&s.memory[offset])) }

func connectAgent(path string) (_ *session, err error) {
	fd, err := unix.Socket(unix.AF_UNIX, unix.SOCK_STREAM|unix.SOCK_CLOEXEC, 0)
	if err != nil { return nil, err }
	ok := false
	defer func() { if !ok { unix.Close(fd) } }()
	if err := unix.Connect(fd, &unix.SockaddrUnix{Name: path}); err != nil { return nil, err }
	deadline := time.Now().Add(2 * time.Second)
	limit := unix.NsecToTimeval((2 * time.Second).Nanoseconds())
	if err := unix.SetsockoptTimeval(fd, unix.SOL_SOCKET, unix.SO_SNDTIMEO, &limit); err != nil {
		return nil, err
	}
	hello := []byte("ZCI1")
	for len(hello) != 0 {
		n, err := unix.SendmsgN(fd, hello, nil, nil, unix.MSG_NOSIGNAL)
		if err == unix.EINTR { continue }
		if err != nil { return nil, err }
		if n == 0 { return nil, errors.New("agent closed during handshake") }
		hello = hello[n:]
	}
	reply := make([]byte, 9)
	received, memfd := 0, -1
	defer func() { if memfd >= 0 { unix.Close(memfd) } }()
	for received < len(reply) {
		left := time.Until(deadline)
		if left <= 0 { return nil, errors.New("IPC handshake timed out") }
		limit = unix.NsecToTimeval(left.Nanoseconds())
		if err := unix.SetsockoptTimeval(fd, unix.SOL_SOCKET, unix.SO_RCVTIMEO, &limit); err != nil {
			return nil, err
		}
		control := make([]byte, unix.CmsgSpace(4))
		n, controlLength, flags, _, err := unix.Recvmsg(fd, reply[received:], control, unix.MSG_CMSG_CLOEXEC)
		if err == unix.EINTR { continue }
		if err != nil { return nil, err }
		if n == 0 { return nil, errors.New("agent closed during handshake") }
		messages, err := unix.ParseSocketControlMessage(control[:controlLength])
		if err != nil { return nil, err }
		for _, message := range messages {
			if message.Header.Level != unix.SOL_SOCKET || message.Header.Type != unix.SCM_RIGHTS { continue }
			rights, err := unix.ParseUnixRights(&message)
			if err != nil { return nil, err }
			if len(rights) != 1 || memfd >= 0 {
				for _, extra := range rights { unix.Close(extra) }
				return nil, errors.New("unexpected descriptors in handshake")
			}
			memfd = rights[0]
		}
		if flags&(unix.MSG_CTRUNC|unix.MSG_TRUNC) != 0 { return nil, errors.New("truncated handshake") }
		received += n
	}
	if reply[0] != 0 { return nil, fmt.Errorf("session refused with code %d", reply[0]) }
	if memfd < 0 { return nil, errors.New("handshake carried no shared memory") }
	submission := uint64(binary.LittleEndian.Uint32(reply[1:5]))
	completionCapacity := uint64(binary.LittleEndian.Uint32(reply[5:9]))
	if !validCapacity(submission) || !validCapacity(completionCapacity) {
		return nil, errors.New("invalid capacity")
	}
	length := uint64(headerSize) + submission + completionCapacity
	var stat unix.Stat_t
	if err := unix.Fstat(memfd, &stat); err != nil { return nil, err }
	if stat.Size < 0 || uint64(stat.Size) < length { return nil, errors.New("shared memory is too small") }
	memory, err := unix.Mmap(memfd, 0, int(length), unix.PROT_READ|unix.PROT_WRITE, unix.MAP_SHARED)
	if err != nil { return nil, err }
	defer func() { if !ok { unix.Munmap(memory) } }()
	if string(memory[:4]) != "ZCR1" || binary.LittleEndian.Uint32(memory[4:8]) != 1 ||
		uint64(binary.LittleEndian.Uint32(memory[8:12])) != submission ||
		uint64(binary.LittleEndian.Uint32(memory[12:16])) != completionCapacity {
		return nil, errors.New("unexpected shared memory header")
	}
	if err := unix.SetNonblock(fd, true); err != nil { return nil, err }
	ok = true
	return &session{fd, memory, submission, completionCapacity}, nil
}

func (s *session) submit(id uint64, payload []byte) error {
	// Go's atomics are sequentially consistent, stronger than acquire/release.
	tail := atomic.LoadUint64(s.word64(64))
	head := atomic.LoadUint64(s.word64(128))
	if err := positions(head, tail, s.submission); err != nil { return err }
	size := recordSize(uint64(len(payload)))
	offset := tail & (s.submission-1)
	remaining, pad := s.submission-offset, uint64(0)
	if size > remaining { pad = remaining }
	if pad+size > s.submission-(tail-head) { return errors.New("submission ring is full") }
	if tail > ^uint64(0)-(pad+size) { return errors.New("submission counter overflow") }
	if pad != 0 {
		record := s.memory[headerSize+offset:headerSize+offset+16]
		clear(record)
		binary.LittleEndian.PutUint32(record, uint32(pad-16))
		offset = 0
	}
	record := s.memory[headerSize+offset:headerSize+offset+size]
	clear(record)
	binary.LittleEndian.PutUint32(record, uint32(len(payload)))
	record[4], record[5] = 1, 1 // Transaction, request a completion, no preflight.
	binary.LittleEndian.PutUint64(record[8:16], id)
	copy(record[16:], payload)
	atomic.StoreUint64(s.word64(64), tail+pad+size)
	// The SC exchange supplies the store/load fence and clears the doorbell flag.
	if atomic.SwapUint32(s.word32(320), 0) == 1 {
		_, _ = unix.SendmsgN(s.fd, []byte{0}, nil, nil, unix.MSG_NOSIGNAL|unix.MSG_DONTWAIT)
	}
	return nil
}

func (s *session) readCompletion() (*completion, error) {
	for {
		head := atomic.LoadUint64(s.word64(256))
		tail := atomic.LoadUint64(s.word64(192))
		if err := positions(head, tail, s.completion); err != nil { return nil, err }
		used := tail-head
		if used == 0 { return nil, nil }
		offset := head & (s.completion-1)
		remaining := s.completion-offset
		start := uint64(headerSize)+s.submission+offset
		record := s.memory[start:start+16]
		length := uint64(binary.LittleEndian.Uint32(record))
		id := binary.LittleEndian.Uint64(record[8:16])
		kind, code := record[4], record[5]
		if record[6] != 0 || record[7] != 0 { return nil, errors.New("nonzero reserved bytes") }
		if kind == 0 {
			if length != remaining-16 || remaining > used || code != 0 || id != 0 {
				return nil, errors.New("invalid pad record")
			}
			atomic.StoreUint64(s.word64(256), head+remaining)
			continue
		}
		size := recordSize(length)
		if kind != 1 || length > maxDetail || size > remaining || size > used ||
			code > 13 || (code == 0 && length != 0) {
			return nil, errors.New("invalid transaction completion")
		}
		payload := append([]byte(nil), s.memory[start+16:start+16+length]...)
		atomic.StoreUint64(s.word64(256), head+size)
		return &completion{id, code, payload}, nil
	}
}

func (s *session) waitFor(id uint64) (*completion, error) {
	deadline := time.Now().Add(5 * time.Second)
	ended := false
	for {
		for {
			reply, err := s.readCompletion()
			if err != nil { return nil, err }
			if reply == nil { break }
			if reply.id == id { return reply, nil }
		}
		if ended { return nil, errors.New("session ended; check the signature before retrying") }
		left := time.Until(deadline)
		if left <= 0 { return nil, errors.New("no completion within 5 seconds; check the signature before retrying") }
		atomic.SwapUint32(s.word32(384), 1)
		if atomic.LoadUint64(s.word64(192)) != atomic.LoadUint64(s.word64(256)) {
			atomic.StoreUint32(s.word32(384), 0)
			continue
		}
		watch := []unix.PollFd{{Fd: int32(s.fd), Events: unix.POLLIN}}
		ready, err := unix.Poll(watch, int((left+time.Millisecond-1)/time.Millisecond))
		atomic.StoreUint32(s.word32(384), 0)
		if err == unix.EINTR { continue }
		if err != nil { return nil, err }
		if ready != 0 {
			ended = watch[0].Revents&(unix.POLLERR|unix.POLLHUP|unix.POLLNVAL) != 0
			var wakeups [128]byte
			for {
				n, _, err := unix.Recvfrom(s.fd, wakeups[:], unix.MSG_DONTWAIT)
				if err == unix.EINTR { continue }
				if err == unix.EAGAIN || err == unix.EWOULDBLOCK { break }
				if err != nil || n == 0 { ended = true; break }
			}
		}
	}
}

func run() (bool, error) {
	if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" { return false, errors.New("this client requires Linux x86_64") }
	if len(os.Args) != 3 { return false, errors.New("usage: ipc-send SOCKET_PATH TRANSACTION_FILE") }
	file, err := os.Open(os.Args[2])
	if err != nil { return false, err }
	defer file.Close()
	payload, err := io.ReadAll(io.LimitReader(file, maxPayload+1))
	if err != nil { return false, err }
	if len(payload) == 0 || len(payload) > maxPayload { return false, errors.New("transaction payload must hold 1 to 16403 bytes") }
	s, err := connectAgent(os.Args[1])
	if err != nil { return false, err }
	defer unix.Close(s.fd)
	defer unix.Munmap(s.memory)
	if err := s.submit(1, payload); err != nil { return false, err }
	reply, err := s.waitFor(1)
	if err != nil { return false, err }
	if len(reply.payload) != 0 {
		var rejection struct { Reason string `json:"reason"` }
		if !utf8.Valid(reply.payload) { return false, errors.New("invalid UTF-8 rejection detail") }
		if err := json.Unmarshal(reply.payload, &rejection); err != nil { return false, err }
		if rejection.Reason == "" { return false, errors.New("invalid rejection detail") }
	}
	fmt.Printf("code %d\n", reply.code)
	if len(reply.payload) != 0 { fmt.Println(string(reply.payload)) }
	return reply.code == 0, nil
}

func main() {
	accepted, err := run()
	if err != nil { fmt.Fprintln(os.Stderr, err) }
	if err != nil || !accepted { os.Exit(1) }
}
```

```ts title="swqos-ipc-send.ts" tab="TypeScript" tab-group="language"
/// <reference types="bun" />
import { dlopen, read as nativeRead, ptr, toArrayBuffer } from 'bun:ffi'
import { closeSync, fstatSync, openSync, readSync } from 'node:fs'

if (process.platform !== 'linux' || process.arch !== 'x64') {
  throw new Error(
    'this client requires Bun on Linux x86_64 with glibc and libatomic.so.1',
  )
}

// These structures and constants use the Linux x86_64 glibc ABI.
const libc = dlopen('libc.so.6', {
  socket: { args: ['i32', 'i32', 'i32'], returns: 'i32' },
  connect: { args: ['i32', 'ptr', 'u32'], returns: 'i32' },
  send: { args: ['i32', 'ptr', 'u64', 'i32'], returns: 'i64' },
  recv: { args: ['i32', 'ptr', 'u64', 'i32'], returns: 'i64' },
  recvmsg: { args: ['i32', 'ptr', 'i32'], returns: 'i64' },
  poll: { args: ['ptr', 'u64', 'i32'], returns: 'i32' },
  fcntl: { args: ['i32', 'i32', 'i32'], returns: 'i32' },
  mmap: { args: ['ptr', 'u64', 'i32', 'i32', 'i32', 'i64'], returns: 'u64' },
  munmap: { args: ['ptr', 'u64'], returns: 'i32' },
  close: { args: ['i32'], returns: 'i32' },
  __errno_location: { args: [], returns: 'u64' },
})
const atomic = dlopen('libatomic.so.1', {
  __atomic_load_8: { args: ['ptr', 'i32'], returns: 'u64' },
  __atomic_store_8: { args: ['ptr', 'u64', 'i32'], returns: 'void' },
  __atomic_store_4: { args: ['ptr', 'u32', 'i32'], returns: 'void' },
  __atomic_exchange_4: { args: ['ptr', 'u32', 'i32'], returns: 'u32' },
})
const c = libc.symbols
const a = atomic.symbols
const HEADER = 4096
const MAX_PAYLOAD = 16403
const MAX_DETAIL = 65535
const U64_MAX = (1n << 64n) - 1n
const MSG_DONTWAIT = 0x40
const MSG_NOSIGNAL = 0x4000
const EINTR = 4
const EAGAIN = 11

function errno(): number {
  return nativeRead.i32(c.__errno_location())
}
function failure(operation: string): never {
  throw new Error(operation + ': errno ' + errno())
}
function checked(value: number, operation: string): number {
  if (value < 0) failure(operation)
  return value
}
function recordSize(length: bigint): bigint {
  return (16n + length + 15n) & ~15n
}
function positions(head: bigint, tail: bigint, capacity: bigint) {
  if (((head | tail) & 15n) !== 0n || head > tail || tail - head > capacity) {
    throw new Error('invalid ring positions')
  }
}
function validCapacity(value: number): boolean {
  const capacity = BigInt(value)
  return capacity >= 16n && (capacity & (capacity - 1n)) === 0n
}
function poll(fd: number, events: number, deadline: number): number {
  const watch = Buffer.alloc(8)
  watch.writeInt32LE(fd)
  watch.writeInt16LE(events, 4)
  for (;;) {
    const left = Math.ceil(deadline - performance.now())
    if (left <= 0) return 0
    const ready = c.poll(watch, 1, left)
    if (ready < 0 && errno() === EINTR) continue
    checked(ready, 'poll')
    return ready === 0 ? 0 : watch.readInt16LE(6)
  }
}

class Session {
  constructor(
    readonly fd: number,
    readonly base: bigint,
    readonly memory: Buffer,
    readonly submission: bigint,
    readonly completion: bigint,
  ) {}

  load64(offset: number): bigint {
    return a.__atomic_load_8(this.base + BigInt(offset), 2)
  }
  store64(offset: number, value: bigint) {
    a.__atomic_store_8(this.base + BigInt(offset), value, 3)
  }
  store32(offset: number, value: number) {
    a.__atomic_store_4(this.base + BigInt(offset), value, 3)
  }
  exchange32(offset: number, value: number): number {
    return a.__atomic_exchange_4(this.base + BigInt(offset), value, 5)
  }
  close() {
    c.munmap(this.base, this.memory.byteLength)
    c.close(this.fd)
  }

  submit(id: bigint, payload: Buffer) {
    const tail = this.load64(64)
    const head = this.load64(128)
    positions(head, tail, this.submission)
    const size = recordSize(BigInt(payload.length))
    let offset = tail & (this.submission - 1n)
    const remaining = this.submission - offset
    const pad = size > remaining ? remaining : 0n
    if (pad + size > this.submission - (tail - head))
      throw new Error('submission ring is full')
    const next = tail + pad + size
    if (next > U64_MAX) throw new Error('submission counter overflow')
    if (pad !== 0n) {
      const start = HEADER + Number(offset)
      this.memory.fill(0, start, start + 16)
      this.memory.writeUInt32LE(Number(pad - 16n), start)
      offset = 0n
    }
    const start = HEADER + Number(offset)
    this.memory.fill(0, start, start + Number(size))
    this.memory.writeUInt32LE(payload.length, start)
    this.memory[start + 4] = 1
    this.memory[start + 5] = 1 // Transaction, completion requested, no preflight.
    this.memory.writeBigUInt64LE(id, start + 8)
    payload.copy(this.memory, start + 16)
    this.store64(64, next)
    // An SC exchange supplies the store/load fence and clears the parked flag.
    if (this.exchange32(320, 0) === 1) {
      c.send(this.fd, Buffer.from([0]), 1, MSG_NOSIGNAL | MSG_DONTWAIT)
    }
  }

  readCompletion(): { id: bigint; code: number; payload: Buffer } | undefined {
    for (;;) {
      const head = this.load64(256)
      const tail = this.load64(192)
      positions(head, tail, this.completion)
      const used = tail - head
      if (used === 0n) return undefined
      const offset = head & (this.completion - 1n)
      const remaining = this.completion - offset
      const start = HEADER + Number(this.submission + offset)
      const length = this.memory.readUInt32LE(start)
      const kind = this.memory[start + 4]
      const code = this.memory[start + 5]
      const id = this.memory.readBigUInt64LE(start + 8)
      if (this.memory.readUInt16LE(start + 6) !== 0)
        throw new Error('nonzero reserved bytes')
      if (kind === 0) {
        if (
          BigInt(length) !== remaining - 16n ||
          remaining > used ||
          code !== 0 ||
          id !== 0n
        ) {
          throw new Error('invalid pad record')
        }
        this.store64(256, head + remaining)
        continue
      }
      const size = recordSize(BigInt(length))
      if (
        kind !== 1 ||
        length > MAX_DETAIL ||
        size > remaining ||
        size > used ||
        code > 13 ||
        (code === 0 && length !== 0)
      ) {
        throw new Error('invalid transaction completion')
      }
      // Copy before publishing the head; the agent can then reuse the record.
      const payload = Buffer.from(this.memory.subarray(start + 16, start + 16 + length))
      this.store64(256, head + size)
      return { id, code, payload }
    }
  }

  waitFor(id: bigint) {
    const deadline = performance.now() + 5_000
    let ended = false
    for (;;) {
      for (;;) {
        const reply = this.readCompletion()
        if (!reply) break
        if (reply.id === id) return reply
      }
      if (ended) throw new Error('session ended; check the signature before retrying')
      if (performance.now() >= deadline) {
        throw new Error(
          'no completion within 5 seconds; check the signature before retrying',
        )
      }
      // SC exchange parks and fences before rechecking the producer's tail.
      this.exchange32(384, 1)
      if (this.load64(192) !== this.load64(256)) {
        this.store32(384, 0)
        continue
      }
      let events: number
      try {
        events = poll(this.fd, 1, deadline)
      } finally {
        this.store32(384, 0)
      }
      if (events !== 0) {
        ended = (events & (8 | 16 | 32)) !== 0 // POLLERR | POLLHUP | POLLNVAL
        const wakeups = Buffer.alloc(128)
        for (;;) {
          const count = c.recv(this.fd, wakeups, wakeups.length, MSG_DONTWAIT)
          if (count > 0n) continue
          if (count === 0n) {
            ended = true
            break
          }
          const error = errno()
          if (error === EINTR) continue
          if (error !== EAGAIN) ended = true
          break
        }
      }
    }
  }
}

function connectAgent(path: string): Session {
  const name = Buffer.from(path)
  if (name.length === 0 || name.length >= 108 || name.includes(0))
    throw new Error('invalid socket path')
  const address = Buffer.alloc(110)
  address.writeUInt16LE(1) // AF_UNIX
  name.copy(address, 2)
  const fd = checked(c.socket(1, 1 | 0x80000, 0), 'socket') // SOCK_STREAM | SOCK_CLOEXEC
  let memfd = -1
  let base: bigint | undefined
  let length = 0
  let success = false
  try {
    checked(c.connect(fd, address, address.length), 'connect')
    const deadline = performance.now() + 2_000
    const hello = Buffer.from('ZCI1')
    let sent = 0
    while (sent < hello.length) {
      const count = c.send(
        fd,
        hello.subarray(sent),
        hello.length - sent,
        MSG_NOSIGNAL | MSG_DONTWAIT,
      )
      if (count > 0n) {
        sent += Number(count)
        continue
      }
      if (count === 0n) throw new Error('agent closed during handshake')
      const error = errno()
      if (error === EINTR) continue
      if (error !== EAGAIN) failure('send hello')
      if (poll(fd, 4, deadline) === 0) throw new Error('IPC handshake timed out')
    }
    const reply = Buffer.alloc(9)
    let received = 0
    while (received < reply.length) {
      if (poll(fd, 1, deadline) === 0) throw new Error('IPC handshake timed out')
      const control = Buffer.alloc(24) // CMSG_SPACE(sizeof(int))
      const iovec = Buffer.alloc(16)
      iovec.writeBigUInt64LE(BigInt(ptr(reply)) + BigInt(received))
      iovec.writeBigUInt64LE(BigInt(reply.length - received), 8)
      const message = Buffer.alloc(56)
      message.writeBigUInt64LE(BigInt(ptr(iovec)), 16)
      message.writeBigUInt64LE(1n, 24)
      message.writeBigUInt64LE(BigInt(ptr(control)), 32)
      message.writeBigUInt64LE(BigInt(control.length), 40)
      const count = c.recvmsg(fd, message, 0x40000000 | MSG_DONTWAIT) // MSG_CMSG_CLOEXEC
      if (count < 0n) {
        if (errno() === EINTR || errno() === EAGAIN) continue
        failure('receive handshake')
      }
      if (count === 0n) throw new Error('agent closed during handshake')
      const controlLength = Number(message.readBigUInt64LE(40))
      for (let offset = 0; offset + 16 <= controlLength; ) {
        const size = Number(control.readBigUInt64LE(offset))
        if (size < 16 || offset + size > controlLength)
          throw new Error('invalid ancillary data')
        if (
          control.readInt32LE(offset + 8) === 1 &&
          control.readInt32LE(offset + 12) === 1
        ) {
          const descriptors: number[] = []
          if ((size - 16) % 4 !== 0) throw new Error('invalid descriptor message')
          for (let at = offset + 16; at < offset + size; at += 4)
            descriptors.push(control.readInt32LE(at))
          if (descriptors.length !== 1 || memfd >= 0) {
            for (const extra of descriptors) c.close(extra)
            throw new Error('unexpected descriptors in handshake')
          }
          memfd = descriptors[0]
        }
        offset += (size + 7) & ~7
      }
      if ((message.readInt32LE(48) & (8 | 0x20)) !== 0)
        throw new Error('truncated handshake')
      received += Number(count)
    }
    if (reply[0] !== 0) throw new Error('session refused with code ' + reply[0])
    if (memfd < 0) throw new Error('handshake carried no shared memory')
    const submission = reply.readUInt32LE(1)
    const completion = reply.readUInt32LE(5)
    if (!validCapacity(submission) || !validCapacity(completion))
      throw new Error('invalid capacity')
    length = HEADER + submission + completion
    if (fstatSync(memfd, { bigint: true }).size < BigInt(length))
      throw new Error('shared memory is too small')
    const mapped = c.mmap(null, length, 3, 1, memfd, 0) // PROT_READ | PROT_WRITE, MAP_SHARED
    if (mapped === U64_MAX) failure('mmap')
    base = mapped
    const memory = Buffer.from(toArrayBuffer(base, 0, length))
    if (
      memory.readUInt32LE(0) !== 0x3152435a ||
      memory.readUInt32LE(4) !== 1 ||
      memory.readUInt32LE(8) !== submission ||
      memory.readUInt32LE(12) !== completion
    ) {
      throw new Error('unexpected shared memory header')
    }
    const flags = checked(c.fcntl(fd, 3, 0), 'fcntl F_GETFL')
    checked(c.fcntl(fd, 4, flags | 0x800), 'fcntl F_SETFL') // O_NONBLOCK
    const session = new Session(
      fd,
      base,
      memory,
      BigInt(submission),
      BigInt(completion),
    )
    success = true
    return session
  } finally {
    if (memfd >= 0) c.close(memfd)
    if (!success) {
      if (base !== undefined) c.munmap(base, length)
      c.close(fd)
    }
  }
}

function run(): boolean {
  const [, , path, file] = process.argv
  if (!path || !file || process.argv.length !== 4)
    throw new Error('usage: bun swqos-ipc-send.ts SOCKET_PATH TRANSACTION_FILE')
  const fd = openSync(file, 'r')
  const bytes = Buffer.alloc(MAX_PAYLOAD + 1)
  let length = 0
  try {
    while (length < bytes.length) {
      const count = readSync(fd, bytes, length, bytes.length - length, null)
      if (count === 0) break
      length += count
    }
  } finally {
    closeSync(fd)
  }
  if (length === 0 || length > MAX_PAYLOAD)
    throw new Error('transaction payload must hold 1 to 16403 bytes')
  const session = connectAgent(path)
  try {
    session.submit(1n, bytes.subarray(0, length))
    const reply = session.waitFor(1n)
    const detail = new TextDecoder('utf-8', { fatal: true }).decode(reply.payload)
    if (detail !== '') {
      const rejection: unknown = JSON.parse(detail)
      if (
        typeof rejection !== 'object' ||
        rejection === null ||
        !('reason' in rejection) ||
        typeof rejection.reason !== 'string' ||
        rejection.reason === ''
      )
        throw new Error('invalid rejection detail')
    }
    console.log('code ' + reply.code)
    if (detail !== '') console.log(detail)
    return reply.code === 0
  } finally {
    session.close()
  }
}

try {
  if (!run()) process.exitCode = 1
} catch (error) {
  console.error(error)
  process.exitCode = 1
} finally {
  atomic.close()
  libc.close()
}
```

Run the selected client from its project directory, using your configured socket path and signed transaction file:

```sh title="Run the IPC sender"
cargo run --bin ipc_send -- /run/zerocopy/agent.sock signed-transaction.bin
# Or:
go run ./ipc-send /run/zerocopy/agent.sock signed-transaction.bin
# Or:
bun swqos-ipc-send.ts /run/zerocopy/agent.sock signed-transaction.bin
```

A successful submission prints `code 0`. A refusal prints its nonzero [reply code](/docs/reference/quic#reply-codes) and any UTF-8 JSON detail, then exits with status 1. Unknown reply codes, nonempty accepted payloads and malformed rejection details are errors. Acceptance does not prove landing. On a timeout or session failure, check the transaction signature before retrying. A long-running client must assign distinct IDs to outstanding requests, keep draining completions, and use the [reconnection rules](#errors) after a restart.
