July 1, 2026

Systems Programmability in the AI Era: A Pure Go I/O Stack

A pure Go I/O stack for real-time communication systems, designed around performance, correctness, and systems programmability for agentic coding.

  • Go
  • io_uring
Systems programmability stack overview
Systems programmability stack overview.

Abstract

This article introduces a pure Go I/O stack (code.hybscloud.com, Go 1.26+, Linux 6.18+) for real-time communication systems. Its focus is systems programmability for agentic coding: building low-latency systems from explicit, composable program facts rather than implicit conventions. In asynchronous I/O, partial progress, resource lifetimes, and connection state across suspension points often hide in callbacks and side tables, making it harder for coding agents to reason about a local change without tracing state across the wider system. This stack keeps low-level runtime facts explicit, extends Go’s io semantics with control outcomes in iox, and represents suspended computations, context checks, completion steps, and protocol steps as values that can be composed and stepped in memory while preserving low-latency execution.

Keywords: Systems Programmability, Agentic Coding, Go, Linux io_uring, Proactor Pattern.


1. Introduction

1.1 Background: Why I Care About This Now

In low-latency systems, performance and correctness are not separate topics. Before coding agents entered the workflow, experienced systems developers often kept many runtime rules in their heads, such as descriptor and buffer lifecycles, partial progress and retries, completion routing, and queue backpressure. That can work when everyone reading and changing the code already shares the same unwritten conventions.

As coding agents take on more implementation, review, and refactoring work, keeping those rules implicit across callbacks and side tables makes local reasoning expensive. Verifying a small change requires tracing state across the wider codebase and relying on black-box tests to catch timing-dependent bugs, such as reusing an active buffer, dropping bytes on a partial write, or resuming a completion after a peer reconnects.

That is why I care about systems programmability. The goal is not only to make I/O fast, but to express low-level runtime facts and asynchronous control in a form that coding agents can inspect and reason about locally, making clear what progress occurred, where evaluation suspends, what context must hold on resume, and which protocol step comes next (Figure 1).

Overview diagram for the systems programmability stack
Figure 1. Runtime facts lifted into explicit computation and protocol structure.

1.2 The Workload Context

The workload I keep in mind is real-time communication: online game servers, large shared virtual worlds, interactive media systems, and low-latency collaborative services. In these systems, latency does not come from one isolated hotspot; it comes from many small costs that multiply across stages. A world update first passes through spatial interest management, which decides which peers should see which entities. That decision controls fanout, and fanout multiplies framing, buffer acquisition, queue handoff, kernel submission, and completion handling (Figure 2). Across those stages, tail latency and correctness are tightly connected:

  • A hidden allocation can become a latency spike and extra garbage collection work.
  • A hidden queue can become unbounded backlog and memory growth under slow consumers.
  • A hidden retry loop can become a retry storm and contention across cores when readiness has not changed.
  • A hidden completion identity can resume the wrong computation after an operation or route ends.
  • A hidden protocol or connection state can accept an invalid message or a stale completion after a reconnect.
Workload pressure diagram for real-time communication systems
Figure 2. Cascading runtime pressure across fanout, buffering, submission, and scheduling stages in real-time communication systems.

1.3 What I Mean by Systems Programmability

Programmability is more than API convenience. A high-level API may be easy to call while hiding the readiness, buffering, and scheduling details that a low-latency runtime eventually has to manage. On the other hand, raw kernel bindings expose low-level mechanics but leave callers to piece control flow back together across callbacks and ad hoc tables. Here, programmability means bridging that gap: keeping low-level runtime facts explicit while representing asynchronous control and protocol steps as composable values that can be checked in unit tests and executed on a low-latency runtime path without hiding state between layers.

Standard Go goroutines and net fit most applications well; this stack focuses on real-time communication paths where keeping buffering, backpressure, completion routing, and protocol order explicit in code is helpful.

1.4 Contributions

The stack combines explicit low-level runtime primitives with structured control for non-blocking outcomes, continuations, context checks, effect runners, and session steps. The focus here is how those pieces work together as one pure Go stack:

  • Non-blocking io semantics and control outcomes (iox): extending Go’s io model so err carries four control outcomes (OutcomeOK, OutcomeWouldBlock, OutcomeMore, OutcomeFailure) alongside progress counts, propagated through Copy, CopyN, TeeReader, TeeWriter, SemanticPolicy, and adaptive Backoff across the stack.
  • Continuations and context checks as values (kont + cove): pairing closure continuations (Cont) with explicit frame chains (Expr), affine one-shot Suspension values, context requirements (ReqExpr), and world transition checks (Preorder, StepIndex) so suspended flows carry their own context rules, with optional frame pools for paths that guarantee single-use evaluation.
  • One effect program across blocking, stepping, and proactor runners (takt + uring): running the same kont computation through blocking dispatch (Exec), single-step advancement (Step, Advance, and AdvanceSuspension over contextual carriers like cove.SuspensionView), or proactor loops (Loop and SubscriptionLoop, where uring.SQEContext maps directly to takt.Token without a side map).
  • Session steps and connection runtime patterns (sess and higher layers): expressing protocol steps as effects over bounded lock-free queues alongside practical patterns for building connection runtimes above uring and takt while keeping runtime state visible.

2. Package Map and iox Outcome Semantics

2.1 Package Map: Separating Mechanism from Policy

The packages at code.hybscloud.com form one stack centered on iox rather than a flat catalog (Figure 3). Across the stack, low-level mechanism stays separate from application policy: the kernel executes asynchronous transfers, the packages keep runtime and control state explicit, and the caller decides queue topology, retry timing, and context rules (Table 1).

Table 1. Package map and division of responsibilities across the packages at code.hybscloud.com.

Layer Packages What the Layer Handles What the Caller Decides
Semantic Center iox Extends Go’s io semantics with four control outcomes (OutcomeOK, OutcomeWouldBlock, OutcomeMore, OutcomeFailure), non-blocking Copy, CopyN, TeeReader, and TeeWriter engines, SemanticPolicy, and adaptive Backoff. Processes progress counts before branching on the outcome; chooses SemanticPolicy or wait strategy.
Runtime Base zcall, iofd, sock, framer Keeps raw non-blocking syscall results, atomic descriptor lifecycles, socket operations, and length-prefix framing explicit. Owns descriptor close ordering, retry timing, and message payload handling.
Runtime Pressure iobuf, lfq, spin, atomix, dwcas Enforces bounded pool and queue capacity, explicit atomic memory ordering, 128-bit CAS, and short-wait primitives. Selects queue shape (SPSC, MPSC, SPMC, MPMC) and backpressure policy.
Kernel Proactor uring Handles io_uring setup, SQEContext encoding, staged kernel pointers, buffer rings, multishot state, and zero-copy tracking. Keeps submitted buffers valid until the final completion arrives and recycles buffers selected by the kernel.
Control & Protocol kont, cove, takt, sess Provides explicit continuation frames, optional frame pools for single-use paths, one-shot Suspension, context checks, effect runners, and session operations. Defines domain operations, context transition rules, dispatchers or backends, and protocol branches.
Layered package stack diagram
Figure 3. Layered package map centered on iox outcome classification.

2.2 iox: Non-Blocking io Semantics and Control Outcomes

iox is small, but it is the semantic center of the stack. Go’s standard io package (Reader, Writer, Copy, TeeReader) is built around blocking calls where any error other than io.EOF stops the operation as a failure. iox extends those io semantics for non-blocking and multishot systems while remaining compatible with standard io interfaces and fast paths (WriterTo, ReaderFrom). In iox, an operation result is progress plus control: the count (n or written) reports work already done, and err carries the control outcome for the next step. Processing progress first and branching on control second avoids two common bugs: dropping transferred bytes when a partial read or write pauses on ErrWouldBlock, and mistaking an active multishot boundary (ErrMore) for a finished one-shot operation (Table 2).

iox.Classify(err) and its predicate helpers (IsProgress, IsWouldBlock, IsMore, IsSemantic, IsNonFailure, IsFailure) classify err into four outcomes (Figure 4):

  1. OutcomeOK (nil): Terminal completion at the current boundary.
  2. OutcomeWouldBlock (iox.ErrWouldBlock): No further progress is possible right now, covering socket EAGAIN, bounded lfq full or empty queues, uring submission queue saturation, and ExtSQE pool exhaustion. The caller waits, yields, or polls completions before retrying.
  3. OutcomeMore (iox.ErrMore): The operation remains active and further completions are expected, such as an io_uring multishot completion with IORING_CQE_F_MORE or a writer frame boundary. IsProgress returns true for both nil and ErrMore, and n may be zero when an active boundary carries no bytes.
  4. OutcomeFailure (any other error): An ordinary non-control error value whose meaning remains operation-specific. Because iox.Classify does not reinterpret standard library sentinels such as io.EOF, higher-level io adapters and iox.Copy treat io.EOF as normal stream termination, whereas raw syscall or socket errors indicate operational or transport failures.

Beyond classification, iox carries these semantics through non-blocking Copy, CopyN, TeeReader, and TeeWriter engines. These engines accumulate written progress across semantic signals, roll back Seeker sources when a partial write pauses on ErrWouldBlock or ErrMore (or return ErrNoSeeker on unseekable sources), and consult a pluggable SemanticPolicy (ReturnPolicy, YieldPolicy, YieldOnWriteWouldBlockPolicy) to decide per operation whether to return immediately (PolicyReturn) or yield and retry (PolicyRetry). When waiting for external I/O readiness, iox.Backoff provides a zero-allocation, block-scaled sleep helper with jitter that callers run on their own schedule.

At the adapter boundary between raw kernel or syscall completions and Go’s io.Reader, a successful zero-byte read from a stream socket indicates peer EOF when the requested length was positive, which an io.Reader adapter translates into (0, io.EOF), whereas a zero result for an empty datagram, a zero-length request, or another opcode has a different meaning [33]. Under the Go io.Reader contract, (0, nil) means that no work occurred rather than EOF [34]; iox.Copy stops and returns (written, nil) on a (0, nil) read to avoid spinning inside an event-loop helper, and callers keep that return distinct from stream termination.

Table 2. Representative (n, outcome) combinations for operations that return a progress count and their caller actions.

Progress count iox.Classify(err) Meaning and caller action
n = 0 OutcomeOK Interpret the result under the operation’s contract. A positive-length stream-socket read returning zero indicates EOF; Go io.Reader.Read returning (0, nil) indicates no work. A generic zero-result CQE does not imply EOF.
n = 0 OutcomeWouldBlock No bytes transferred; yield, poll completions, or apply iox.Backoff before retrying.
n > 0 OutcomeOK Advance buffer cursor by n; the one-shot operation is complete.
n > 0 OutcomeWouldBlock Record the n transferred bytes first, then wait for readiness or completion before retrying the rest.
n >= 0 OutcomeMore Process the current completion (n bytes or accepted descriptor) while keeping the multishot subscription active.
n >= 0 OutcomeFailure Record any n transferred bytes first, then handle the operation-specific non-control error (such as io.EOF at stream end or a transport error requiring recovery or close).
iox outcome semantics diagram
Figure 4. iox separates progress already made from what may happen next.

3. Runtime Layer: Base, Pressure, and uring

3.1 Runtime Base and Bounded Runtime Pressure

The lower runtime packages keep low-level mechanics visible rather than hiding them behind blocking calls or unbounded queues:

  • Runtime Base (zcall, iofd, sock, framer): zcall exposes raw Linux syscalls, byte counts, and unboxed Errno values for callers that manage their own scheduling and retries. iofd manages Unix file descriptors, atomic close ownership, and non-blocking reads and writes so descriptors are not leaked, closed twice, or used after close. sock builds non-blocking socket creation, address and option control, accept and connect calls, and vectored I/O over iofd and zcall when direct socket control beyond standard net is needed. Above raw transports, framer (Reader, Writer) handles length-prefix stream framing and packet passthrough so individual protocols do not reimplement partial read buffering, size checks, and iox.ErrWouldBlock retries.
  • Runtime Pressure (iobuf, lfq, spin, atomix, dwcas): iobuf provides bounded, lock-free tiered buffer pools, page-aligned memory allocation, and iovec assembly so buffer reuse stays explicit instead of turning into allocator and GC pressure. lfq provides bounded lock-free FIFO queues in the four standard shapes (SPSC, MPSC, SPMC, MPMC) [7–11]: a full or empty queue returns iox.ErrWouldBlock rather than growing memory or spinning inside the queue. spin provides explicit short-wait primitives (CPU pause hint, adaptive spinning, spinlock, and cooperative yield); atomix provides cache-line-padded typed atomics with memory ordering (Relaxed, Acquire, Release, AcqRel) stated at the call site; and dwcas provides 128-bit compare-and-swap (Uint128) on 16-byte-aligned values so a pointer or state word and a generation counter can be updated together atomically.

3.2 uring: Linux io_uring in Pure Go

uring is the Linux proactor layer of the stack [1, 3–6]. Unlike readiness notifications, where user space still performs the read or write after waking up, io_uring accepts submitted operations and posts completions after the kernel finishes the transfer. An io_uring package that tries to be the whole application runtime ends up hiding retry and scheduling decisions, while one that exposes only raw kernel structs leaves every caller to rebuild SQE lifetimes, user_data lookup, buffer selection, and multishot state. uring sits between those extremes: it handles ring mechanics, exposes the submission and completion details that affect correctness and latency, and leaves scheduling policy to higher layers (Figure 5).

A ring is created unstarted and configured with uring.Options before Start(), which registers probes, fixed buffers, and provided buffer rings or groups before enabling the ring. Setup requests IORING_SETUP_NO_SQARRAY by default. When MultiIssuers: false is used on a single goroutine locked to one OS thread from New through Stop with serialized ring calls, setup also requests IORING_SETUP_SINGLE_ISSUER and IORING_SETUP_DEFER_TASKRUN so the hot path skips shared submission locking and runs kernel task work on the polling thread [1]. Write operations omit success CQEs by default to reduce completion traffic, whereas NotifySucceed: true requests a CQE for every completed write when a loop tracks each write individually (as in Listing 2). SQAvailable() and CQPending() report submission headroom and completion backlog directly, memory budget helpers size ring entries and buffer group tiers from an explicit byte budget, and Stop() performs idempotent teardown after active operations and subscriptions have been drained.

To keep 64-bit user_data completion tokens structured rather than opaque, uring encodes submission and completion identity through SQEContext in three modes:

  1. Direct mode (PackDirect): packs the operation code, SQE flags, buffer group, and file descriptor directly into the 64-bit SQEContext value with no extra allocation.
  2. Indirect mode (PackIndirect): indexes a pooled 64-byte IndirectSQE sidecar when an operation needs more bits than fit inline.
  3. Extended mode (PackExtended): references a pooled 128-byte ExtSQE (borrowed via ring.ExtSQE() and packed via uring.PackExtended(ext)), pairing a 64-byte base SQE with 64 bytes of caller UserData (distinct from the kernel’s SQE128 ring configuration). Since ExtSQE.UserData is raw memory untraced by the Go garbage collector, callers retain those references separately while uring keeps bounded roots visible to the garbage collector for its own staged arguments, and ScopedExtSQE makes clear at the call site whether a borrowed ExtSQE is freed on error or handed off to the completion path.

Reserving a submission slot checks the submission queue head and tail and returns iox.ErrWouldBlock when the ring is full, keeping saturation visible rather than blocking silently. Staged arguments owned by the slot (such as socket addresses, iovec arrays, and timespecs) remain valid until the kernel consumes the SQE, while caller data buffers must remain valid until the operation’s final completion arrives [3]. When completions arrive, Wait, WaitDirect, and WaitExtended decode batches into caller-provided slices (CQEView, DirectCQE, or ExtCQE), mapping -EAGAIN to iox.ErrWouldBlock so kernel retry signals use the same iox vocabulary as the rest of the stack.

Buffer paths, multishot streams, and zero-copy sends each have distinct ownership rules that uring keeps explicit:

  • Buffer handling across fixed, provided, bundle, and incremental paths: each io_uring buffer path answers a specific ownership question: who keeps an ordinary submitted slice valid until completion?, which index refers to a registered fixed buffer?, which BufID did the kernel pick from a provided buffer group?, and when is a provided buffer ring entry recycled with release ordering before advancing the ring tail? For receive bundles, BundleIterator steps through the buffers in one completion and recycles them explicitly; for incremental receive (IOU_PBUF_RING_INC), HasBufferMore (IORING_CQE_F_BUF_MORE) indicates that the kernel has only partially consumed the selected provided buffer and retains its remaining capacity for subsequent completions with the same BufID (distinct from request-level IORING_CQE_F_MORE), so the buffer is recycled only after kernel ownership has ended (!cqe.HasBufferMore()) and application users have released all delivered slices [3].
  • Multishot subscriptions (MultishotSubscription): a multishot accept or receive (AcceptMultishot, ReceiveMultishot) submits a single SQE that produces multiple CQEs marked with IORING_CQE_F_MORE (cqe.HasMore()). MultishotSubscription tracks active, cancelling, and stopped states, keeping the ExtSQE allocated across intermediate completions and returning it to the pool only when a final CQE arrives without MORE [3]. Requesting cancellation submits an async cancel while the subscription stays active until that final completion arrives.
  • Zero-copy send notifications (ZCTracker): SendZC and SendZCFixed post an initial send-result CQE and, when that initial CQE has IORING_CQE_F_MORE (cqe.HasMore()) set, a subsequent IORING_CQE_F_NOTIF (cqe.IsNotification()) CQE that signals when the kernel and NIC have finished reading the zero-copy pages [2, 3]. Whether a notification is expected is determined by the initial CQE’s IORING_CQE_F_MORE flag rather than whether its result indicates success or failure: even an errored send may still set MORE and generate a notification CQE, whereas a completion without MORE finishes immediately without one. ZCTracker keys buffer and ExtSQE lifetime on IORING_CQE_F_MORE and IORING_CQE_F_NOTIF (and defensively tolerates reordered application or synthetic test delivery), invoking OnNotification and releasing the ExtSQE only after kernel buffer ownership ends.
uring io_uring mechanics diagram
Figure 5. uring exposes submission encoding, completion reaping, buffer ring selection, and zero-copy notification facts.

4. Control and Protocol Layer: kont, cove, takt, and sess

4.1 kont: Suspended Computation

In asynchronous systems, evaluation frequently reaches a point where it cannot continue immediately because it is waiting on I/O, a kernel completion, or a protocol peer. Go’s goroutines are a strong general-purpose solution; in this stack, the suspension point itself is also represented as a value so another layer can store, inspect, route, resume, or discard it. A simple way to read kont is: two representations, one shared suspension point, and trampoline evaluation (Figure 6).

The first representation is Cont[R, A] (with the common alias Eff[A]), the continuation form that reads as ordinary sequential steps: perform an operation, receive a value, and continue. The second representation is Expr[A], which arranges the continuation chain into explicit frame nodes (ReturnFrame, BindFrame, MapFrame, ThenFrame, EffectFrame, and UnwindFrame) while step functions inside those frames (BindFrame.F, MapFrame.F, EffectFrame.Resume) remain ordinary Go closures [12]. Reify converts Cont to Expr lazily across effect boundaries, and Reflect converts Expr back to Cont [14, 38]. Effect operations implement the generic Op[O, A] interface (usually by embedding kont.Phantom[A]) and dispatch through Handler[H, R] without reflection, following the structure of algebraic effect handlers and freer monads [15–19]. Alongside suspension, kont includes standard effects built on the same operation and handler model: reader, state, and writer effects, structured error handling with Either, bracket resource cleanup, and delimited control with Shift and Reset [13].

Iterative trampoline evaluation walks frame chains in a loop rather than recursively traversing the managed chain: Handle interprets a Cont through an effect-dispatch loop, HandleExpr interprets an Expr through a frame-evaluation loop, Run and RunWith apply final continuations to Cont values without an effect handler, and RunPure evaluates an effect-free Expr (panicking if it encounters an effect) [38]. That loop serves both programmability and latency: it keeps running while local work can make progress and stops only when an external result is needed, avoiding a scheduler handoff on every local step. When evaluation stops at an external operation, Step and StepExpr return an affine Suspension[A] that can be used at most once: passing a matching completion to Resume returns either the final value or the next suspension, which the runtime retains instead of restarting the original program. Calling Resume on a consumed suspension panics, TryResume reports false, and repeated sequential Discard calls do not panic, releasing temporary continuation state while leaving external I/O ownership as a separate obligation. Ordinary constructors such as ExprPerform and ExprBind create unpooled frames, while the Acquire*Frame constructors provide pooled frames for callers that guarantee single-use affine evaluation, clearing and returning frames to internal pools upon consumption [38].

Evaluate until suspension diagram
Figure 6. The Expr path: evaluate frames until suspension, then resume the saved continuation from a matching completion.

4.2 cove: Context Evidence Around Suspension

Suspension creates a context problem: a computation may pause while one condition holds and wake up after the surrounding state has changed. Here, world means the runtime context that matters for a paused operation, such as whether a peer is still on the same connection generation, a match phase is still active, or send budget remains. If those assumptions live only in globals, side maps, or unwritten conventions, a handler can resume under state that looks valid locally but belongs to a new connection or match phase.

cove gives that context an explicit representation, drawing on comonadic context and coeffect systems that track what a computation requires from its environment [22–26]. It centers on five pieces: a value with context, a requirement over context, a suspension with context, an allowed transition from one world to the next, and a finite step budget for bounded checking:

  • Context views and requirements (View, Cmd, Req, ReqExpr, Rule, RuleExpr, Checked, Guarded): View[C, A] pairs a value with its context C (Extract, Ask, Extend), and Cmd composes functions that consume a whole view. Requirements come in two forms: closure predicates (Req[C]) and structured boolean trees (ReqExpr[C] with ExprAll, ExprAny, ExprNot, and ExprAtom, where leaf atoms hold Go functions). Rule and RuleExpr attach diagnostic names so a failed check reports which condition failed, and Checked or Guarded expose a View only when their requirement holds.
  • World transitions and bounded stepping (SuspensionView, IndexedSuspensionView, Preorder, StepIndex, ResumeTo, Relate): StepWith and StepExprWith run a kont computation until it completes or pauses, keeping its context attached in a SuspensionView[C, R]. To check how context changes while an operation is suspended, the caller defines a Preorder[W] (cove.Extends(leq, before, after)) that states which later context after is a valid successor of before [20], while StepWithIndex and StepExprWithIndex attach a StepIndex in an IndexedSuspensionView[C, R] counting how many pauses a check may take [21]. ResumeTo consumes one step of that counter and checks at runtime that leq.Extends(before, after) holds (panicking if the transition is not allowed), and Relate and CheckCompletedRelation check the final state when the bounded path finishes. Together, they check four conditions on resume: what world am I in now?, which next world is allowed?, which requirement must still hold?, and how many external steps remain?

4.3 takt: Effect Runner Across Blocking, Stepping, and Proactor Loops

Where iox classifies outcomes, kont defines suspension and resumption, and cove attaches context across suspensions, takt is the operational runner layer that answers when and how a suspended effect moves [6, 17, 19]. Its core design is one effect algebra with three execution modes: a kont.Eff[R] or kont.Expr[R] program can run to completion synchronously, step one operation at a time in a test, or run asynchronously through a proactor backend when paired with interpreters that share the same operation semantics:

  • Blocking execution (Exec, ExecExpr, ExecError, ExecErrorExpr): runs a computation to completion through Dispatcher[D Dispatcher[D]] (Dispatch(kont.Operation) (kont.Resumed, error)). A generic value handler keeps the concrete dispatcher type visible to the compiler, advancing on iox.IsProgress(err) (nil or ErrMore) and waiting on iox.ErrWouldBlock with iox.Backoff. The ExecError variants handle pure application Throw and Catch effects (Either[E, R]) eagerly before dispatching I/O operations.
  • Single-step advancement (Step, Advance, AdvanceSuspension, StepError, AdvanceError): evaluates until the first suspension (Step) and dispatches one suspended operation at a time through Dispatcher[D], resuming on nil or iox.ErrMore and returning the suspension unconsumed on iox.ErrWouldBlock or failure. Because AdvanceSuspension is generic over any SuspensionLike[S, R] carrier exposing Op() and Resume(kont.Resumed), it advances contextual suspensions such as cove.SuspensionView[C, R] directly without takt importing or owning cove’s context rules.
  • Proactor event loops (Loop[B, R] and SubscriptionLoop[B, A]): drive suspended computations asynchronously through Backend[B Backend[B]] (Submit(kont.Operation) (Token, error) and Poll([]Completion) (int, error), with CompletionMemory backed by HeapMemory or iobuf BoundedMemory slabs).

In the one-shot Loop[B, R], at most one affine kont.Suspension is tracked per admitted Token across 64 cache-line-padded shards, returning ErrLiveTokenReuse if a live token is reused. Backend.Submit is a terminal admission boundary for Loop: any non-nil error from Backend.Submit (including iox.ErrWouldBlock) disposes the suspension via Discard(), and a submission error when resubmitting a completion or submitting the next suspended step during Poll transitions the loop into a fatal state. On Poll, ErrWouldBlock from the poll call itself is treated as an idle tick, while iox.Classify(c.Err) on each completion drives the step: OutcomeOK and an operation’s OutcomeFailure resume the suspension with c.ResumeValue(), OutcomeWouldBlock resubmits the same suspension under a fresh token, and OutcomeMore on a completion is rejected with ErrUnsupportedMultishot because a one-shot suspension cannot own an active backend stream. On a fatal error (poison), the loop discards every pending suspension in its continuation table; calling Drain (which is idempotent) discards any remaining pending suspensions and releases the loop’s CompletionMemory slab once. Discarding a continuation abandons future computation and recycles kont frames; it does not, by itself, cancel an in-flight kernel operation or release buffers and contexts still owned by an external operation.

For streaming operations, SubscriptionLoop[B, A] serves as the stream counterpart to Loop over SubscriptionBackend[B, A]. Each active route is keyed by RouteID = Token + Generation (NewRouteID), returning ErrLiveRouteReuse on duplicate active routes and ignoring stale completions after a slot is reused provided every delivered StreamCompletion carries the generation of the submission that produced it rather than the generation currently occupying a recycled storage slot. StreamCompletion.More tracks route liveness independently of HasValue and EventErr: More == true emits an intermediate StreamEvent[A] (Final: false) and keeps the route active, More == false emits Final: true and retires the route, and Cancel marks the route as cancelling until the final completion or Drain retires it.

4.4 sess: Protocol Steps as Effects

sess represents protocol steps between two endpoints as kont effects: Send, Recv, SelectL, SelectR, Offer, Close, and recursive Loop and ExprLoop steps, building on session models of communication [27–31] (Figure 7). Because each protocol step is an effect operation, sending, receiving, choosing a branch, offering branches, or closing pauses the computation cleanly while keeping the rest of the protocol order visible in code.

sess.New connects two endpoints in memory over four bounded lfq.SPSC queues (one data queue and one binary choice queue in each direction) plus a shared atomic close counter. Branch selection is compact: left and right choices use preallocated signals, Offer reads the peer’s choice as a preallocated branch value, and full or empty queues return iox.ErrWouldBlock. Closure helpers (SendThen, RecvBind, SelectLThen, SelectRThen, OfferBranch, CloseDone) and pooled Expr helpers mirror each other above this transport, including ExprLoop recursion without growing the call stack, early exit on session errors, and endpoint delegation. Run and RunExpr step both endpoints on the calling goroutine without extra goroutines or Go channels, calling iox.Backoff only when neither side can advance.

sess is not a wire framing layer or network transport, and it does not statically check protocol duality: multiway choices are built by nesting binary choices, and matching client and server steps as well as avoiding sends after close remain the caller’s responsibility.

Computation representation layer diagram
Figure 7. Computation and protocol representations (kont, cove, takt, sess) above the runtime layer.

5. Examples, Completion Flow, and Higher Layers

5.1 How a Completion Flows End to End

A concrete way to see how the stack fits together is to trace one write from creation to resumption:

  1. Build the operation as a value: application code creates a writeOp struct and wraps it in a kont.Expr program (kont.ExprPerform). Nothing has run yet; the program is a value.
  2. Run to the suspension point: loop.SubmitExpr runs the kont evaluator until it reaches writeOp, saves the rest of the computation in a one-shot Suspension, and passes writeOp to backend.Submit.
  3. Submit with an identity and an owner: the backend borrows a pooled *uring.ExtSQE from the ring, retains the operation and its payload, packs its context with ctx := uring.PackExtended(ext).WithFD(w.FD), and returns takt.Token(ctx.Raw()) after calling ring.Write [3, 6], avoiding a separate map[takt.Token]writeOp table.
  4. Poll the CQE and classify with iox: when the kernel posts a completion, backend.Poll reaps the CQE via WaitExtended, recovers the takt.Token with takt.Token(uring.PackExtended(cqe.Ext).Raw()), records the byte count and error in writeDone while setting Completion.Err for takt, clears the backend’s pending write, and returns cqe.Ext to the ring pool. Inside takt.Loop, iox.Classify drives the next step: OutcomeOK and an operation’s OutcomeFailure resume the matching suspension, OutcomeWouldBlock resubmits the suspension, and OutcomeMore is rejected by the one-shot loop and handled by SubscriptionLoop.

Admission and completion remain separate boundaries. At the uring layer, an exhausted ExtSQE pool or full submission queue returns iox.ErrWouldBlock, whereas takt.Loop treats any non-nil error from backend.Submit as a terminal admission failure that calls susp.Discard() (and marks the loop fatal if a completion-driven resubmit or successor step fails during Poll). Because replaying a multi-step program from the beginning can duplicate earlier effects, and because takt.Advance resumes immediately when its Dispatcher returns nil, a runtime that needs retryable asynchronous admission retains the unconsumed *kont.Suspension in a bounded queue until admission succeeds or cancellation consumes it, then tracks that suspension under the accepted token and resumes only from the matching completion.

5.2 Bridging uring and takt

Listing 1 deliberately allows one outstanding write on an exclusive ring so the ownership contract stays visible: pending retains a typed pointer to the operation, including its byte slice, independently of the continuation table. Until the write’s terminal CQE is reaped, the caller keeps the backend reachable, leaves the operation and payload unchanged, keeps the buffer storage at a stable address, and keeps the descriptor open, since an integer completion token alone does not keep Go memory alive [35]. Because done lives inside writeOp, completion delivery passes &w.done without allocating a boxed result struct per CQE; a backend that supports multiple in-flight writes applies the same lifetime rule across bounded per-submission storage.

Listing 1. A one-write backend with explicit payload ownership and direct completion-token mapping.

type writeDone struct {
    N   int32
    Err error
}

type writeOp struct {
    kont.Phantom[*writeDone]
    FD   iofd.FD
    Buf  []byte
    done writeDone
}

type backend struct {
    ring    *uring.Uring
    cqes    [1]uring.ExtCQE
    pending *writeOp
}

func (b *backend) Submit(op kont.Operation) (takt.Token, error) {
    w, ok := op.(*writeOp)
    if !ok {
        return 0, uring.ErrInvalidParam
    }
    if b.pending != nil {
        return 0, iox.ErrWouldBlock
    }
    ext := b.ring.ExtSQE()
    if ext == nil {
        return 0, iox.ErrWouldBlock
    }
    ctx := uring.PackExtended(ext).WithFD(w.FD)
    b.pending = w
    if err := b.ring.Write(ctx, w.Buf); err != nil {
        b.pending = nil
        b.ring.PutExtSQE(ext)
        return 0, err
    }
    return takt.Token(ctx.Raw()), nil
}

func (b *backend) Poll(out []takt.Completion) (int, error) {
    if b.pending == nil || len(out) == 0 {
        return 0, iox.ErrWouldBlock
    }
    n, err := b.ring.WaitExtended(b.cqes[:])
    if err != nil || n == 0 {
        return 0, err
    }

    // This exclusive ring carries only this backend's ordinary writes.
    cqe := &b.cqes[0]
    w := b.pending
    w.done = writeDone{Err: cqe.Err()}
    if w.done.Err == nil {
        w.done.N = cqe.Res
    }
    out[0] = takt.Completion{
        Token: takt.Token(uring.PackExtended(cqe.Ext).Raw()),
        Value: &w.done,
        Err:   w.done.Err,
    }
    b.pending = nil
    b.ring.PutExtSQE(cqe.Ext)
    return 1, nil
}

Listing 2 separates ring ownership from computation lifetime. newBackend locks the calling goroutine to its OS thread before ring creation and explicitly selects single-issuer mode and success CQEs [1, 36]. On success, the caller owns that thread lock until close performs final teardown. All backend calls must stay serialized on that same goroutine.

writeOnce runs one nonempty payload and reports a short write without replaying it. Its deferred loop.Drain() releases logical computation state only. A polling failure leaves b.pending intact, and close refuses to tear down while that operation remains outstanding.

Listing 2. Creating the owner, driving one write, and allowing teardown only after physical retirement.

func newBackend() (*backend, error) {
    runtime.LockOSThread()
    ring, err := uring.New(func(opt *uring.Options) {
        opt.MultiIssuers = false
        opt.NotifySucceed = true
    })
    if err != nil {
        runtime.UnlockOSThread()
        return nil, err
    }
    if err := ring.Start(); err != nil {
        stopErr := ring.Stop() // No application I/O has been submitted.
        runtime.UnlockOSThread()
        return nil, errors.Join(err, stopErr)
    }
    return &backend{ring: ring}, nil
}

func writeOnce(b *backend, w *writeOp) (int32, error) {
    loop := takt.NewLoop[*backend, *writeDone](b)
    defer loop.Drain()

    program := kont.ExprPerform(w)
    if _, _, err := loop.SubmitExpr(program); err != nil {
        return 0, err
    }
    var written int32
    var backoff iox.Backoff
    for loop.Pending() > 0 {
        results, err := loop.Poll()
        if err != nil {
            return written, err
        }
        if len(results) == 0 {
            backoff.Wait()
            continue
        }
        backoff.Reset()
        for _, done := range results {
            written += done.N
            if done.Err != nil {
                return written, done.Err
            }
        }
    }
    if int64(written) != int64(len(w.Buf)) {
        return written, io.ErrShortWrite
    }
    return written, nil
}

func (b *backend) close() error {
    if b.pending != nil {
        return iox.ErrWouldBlock
    }
    err := b.ring.Stop()
    runtime.UnlockOSThread()
    return err
}

The caller constructs &writeOp{FD: fd, Buf: payload} and retains b across errors. If polling fails while a write is still pending, the owner must remain on the locked goroutine and recover enough to reap its terminal CQE before closing the ring or reusing the buffer; an error path must never stop the ring or unlock the OS thread unconditionally. This minimal example omits cancellation and does not bound recovery time. Because the ring accepts only these one-shot writes with NotifySucceed enabled, pending == nil establishes kernel quiescence here, whereas loop.Pending() == 0 reflects only the continuation table. Supporting cancellation, multishot streams, or zero-copy sends requires tracking their respective completions as well, since a cancellation CQE does not replace the original operation’s terminal observation [37]. Once pending is nil, close tears down the ring once and unlocks the thread.

For multishot kernel operations (AcceptMultishot, ReceiveMultishot), a companion takt.SubscriptionBackend and takt.SubscriptionLoop apply three rules beyond the one-shot bridge:

  1. Keep multishot routes active: a CQE with cqe.HasMore() sets StreamCompletion.More = true (which RouteOutcome() maps to iox.OutcomeMore), delivering an intermediate StreamEvent while keeping cqe.Ext alive; only the final CQE (!cqe.HasMore()) sets More = false (Final: true), retiring the route and returning cqe.Ext to the pool.
  2. Pass selected buffer details: when a multishot receive uses a provided buffer ring (cqe.HasBuffer()), StreamCompletion.Value carries the completion’s byte count, BufID, buffer group, and HasBufferMore flag so the consumer can read the delivered slice and recycle the buffer slot only after kernel ownership (!cqe.HasBufferMore()) and application reads have both finished.
  3. Separate routes with submission-bound generation numbers: on Subscribe, the backend pairs the SQEContext token with a generation counter via takt.NewRouteID(tok, gen). Because Linux returns only the submitted 64-bit user_data in each CQE [3], every delivered StreamCompletion must carry the generation of the submission that produced it (whether encoded in the submitted user_data, stored in per-submission metadata that stays live until the final CQE without IORING_CQE_F_MORE retires the slot, or captured before slot recycling) rather than reading the generation currently occupying a recycled storage slot.

5.3 Example: cove Around a Game Send

Consider a game server sending a snapshot to a player. The send requires an active match, a current connection, and remaining send budget. When the completion arrives later, what matters is not only whether the current context looks valid on its own, but whether it is a valid successor of the context where the send began: after a reconnect, Connected may be true again even though ConnGen changed.

Listing 3 shows this pause and resume check with cove, validating canSend when the operation suspends and checking cove.Extends(sameSendWorld, step.Ask(), after) before calling ResumeTo (sameSendWorld writes each invariant as a monotone implication so the relation is reflexive and transitive over all gameCtx values, while canSend establishes before.SendsLeft > 0). Because this example supplies a synthetic completion in memory, a runtime must check admission conditions before submitting a real send; rejecting a stale completion cannot undo bytes already transmitted.

Listing 3. Checking context before resuming a snapshot send with cove.Preorder and ResumeTo.

type gameCtx struct {
    Phase     string
    Connected bool
    ConnGen   uint64
    SendsLeft int
}

var canSend = cove.ExprAll(
    cove.ExprAtom(func(c gameCtx) bool { return c.Phase == "match-running" }),
    cove.ExprAtom(func(c gameCtx) bool { return c.Connected }),
    cove.ExprAtom(func(c gameCtx) bool { return c.SendsLeft > 0 }),
)

type sendDone struct{ Bytes int }

type sendSnapshot struct {
    kont.Phantom[sendDone]
    Conn   int
    Gen    uint64
    Packet []byte
}

var sameSendWorld = cove.Preorder[gameCtx](func(before, after gameCtx) bool {
    return (before.Phase != "match-running" || after.Phase == "match-running") &&
        before.ConnGen == after.ConnGen &&
        (!before.Connected || after.Connected) &&
        (before.SendsLeft < 0 || after.SendsLeft >= 0) &&
        after.SendsLeft <= before.SendsLeft
})

func resumeSnapshot(before, after gameCtx, conn int, packet []byte, completionBytes int) error {
    program := kont.ExprMap(
        kont.ExprPerform(sendSnapshot{Conn: conn, Gen: before.ConnGen, Packet: packet}),
        func(done sendDone) bool { return done.Bytes == len(packet) },
    )

    _, step := cove.StepExprWithIndex(before, cove.StepIndex(1), program)
    if !cove.NeedExpr(step.Ask(), canSend) {
        step.Discard()
        return errors.New("send is not valid in this context")
    }

    // In a full loop, after and completionBytes come from the completion handler.
    if !cove.Extends(sameSendWorld, step.Ask(), after) {
        step.Discard()
        return errors.New("stale send completion")
    }

    sent, finished := step.ResumeTo(sameSendWorld, sendDone{Bytes: completionBytes}, after)
    sentOK := cove.Relate[gameCtx, bool](
        sameSendWorld,
        func(w gameCtx, left cove.StepIndex, ok bool) bool {
            return ok && left == 0 && w.Phase == "match-running" && w.Connected && w.SendsLeft >= 0
        },
    )
    if !cove.CheckCompletedRelation(finished, sent, sentOK) {
        return errors.New("send trace did not satisfy relation")
    }
    return nil
}

5.4 Example: sess Protocol Shape

Listing 4 shows a compact game session protocol over bounded lfq.SPSC queues: the client sends Join, the server replies with MatchFound and offers two branches, and the client selects the left branch to send Ready, receive Tick, and close the session (with the right branch closing as cancelled).

Listing 4. Paired client and server session protocol running over bounded lfq.SPSC queues.

func runGameSession() (string, string) {
    client := sess.SendThen(
        "Join",
        sess.RecvBind(func(match string) kont.Eff[string] {
            return sess.SelectLThen(
                sess.SendThen(
                    "Ready",
                    sess.RecvBind(func(tick string) kont.Eff[string] {
                        return sess.CloseDone(tick)
                    }),
                ),
            )
        }),
    )

    server := sess.RecvBind(func(join string) kont.Eff[string] {
        return sess.SendThen(
            "MatchFound",
            sess.OfferBranch(
                func() kont.Eff[string] {
                    return sess.RecvBind(func(ready string) kont.Eff[string] {
                        return sess.SendThen("Tick", sess.CloseDone("started"))
                    })
                },
                func() kont.Eff[string] {
                    return sess.CloseDone("cancelled")
                },
            ),
        )
    })

    return sess.Run[string, string](client, server)
}

5.5 Building Connection Runtimes Above the Stack

uring and takt stop at submission and completion routing so service and protocol layers above them can stay thin and keep runtime state explicit:

  1. Retain the current suspension for each connection: write connection logic with kont.Eff and kont.Reify (which converts later steps on demand rather than prebuilding every future frame at connection setup [38]) or directly with kont.Expr constructors, call kont.StepExpr to obtain the first suspension, correlate it with the submitted operation, and invoke Resume on the matching completion while retaining the returned successor for the next operation. Re-entering the original expression on each completion can replay earlier effects or reuse consumed state, and early incoming data should wait in bounded connection queues with explicit buffer ownership.
  2. Keep handlers and middlewares shallow: build the middleware chain (func(Handler) Handler) before the poll loop starts, have each handler step process one event without retaining borrowed read buffers after the call returns, and keep repetition in the outer poll loop.
  3. Wait for active completions before closing the descriptor: when closing a connection, report disconnect once, cancel or wait for all active receive, send, and connect CQEs (including pending ZCTracker zero-copy notifications) while keeping descriptors and buffers valid, and close the iofd.FD only after those final completions arrive.
  4. Keep message framing and protocol codecs above the runtime: place stream framing (framer.Reader with bounded buffer limits) and application protocol codecs in middlewares above the connection runtime rather than mixing parser state into uring or takt.

6. Working with Coding Agents: Lift, Reduce, Verify, Compile

The workflow on this stack has four stages (Lift → Reduce → Verify → Compile, Figure 8), helping coding agents move cleanly between program rules and executable Go code:

  • Lift: express runtime and control rules as explicit Go values, including outcomes (iox), suspended computations (kont), context rules (cove), effect runners and completion tokens (takt), and protocol steps (sess).
  • Reduce: step that smaller representation directly in memory by reordering completions, returning iox.ErrWouldBlock, or changing context fields between pause and resume, rather than relying on full-system runs to hit a narrow timing window.
  • Verify: check the lifted representation and runtime rules in deterministic Go unit tests (StepExpr, cove.Extends, CheckCompletedRelation, or takt AdvanceSuspension and Loop steps). This workflow does not claim automatic whole-program verification; it keeps correctness rules visible and testable early.
  • Compile: run the same representations through the uring and takt runtime paths.

When handlers are written with kont.Cont (Eff) closures and converted at runtime with kont.Reify, a git diff still shows ordinary Go closures; Reify invokes the Cont to obtain a result or the current effect marker and constructs subsequent kont.Expr frames as each marker is resumed [38]. What helps coding agents is not removing closures from every source file, but turning suspended steps and context changes into values that can be inspected and stepped directly in unit tests.

Lift Reduce Verify Compile workflow diagram
Figure 8. The Lift, Reduce, Verify, Compile workflow across explicit runtime and control representations.

6.1 Example: Testing a Completion After Reconnect

Suppose a coding agent changes a snapshot sender so that a completion resumes whenever the peer is marked Connected. A test that checks only Connected passes even if the peer disconnected and reconnected while the write was active, or if the match already ended. Using gameCtx and resumeSnapshot from Listing 3, Listing 5 tests the resume path across three contexts: a valid completion on the same connection (SendsLeft decremented), a reconnected peer where Connected is true after ConnGen advances, and a match phase that ended while the write was active.

Listing 5. Testing the resume path across valid, reconnected, and ended match contexts.

func TestStaleSendAfterReconnect(t *testing.T) {
    before := gameCtx{Phase: "match-running", Connected: true, ConnGen: 12, SendsLeft: 2}
    packet := []byte("tick")

    after := before
    after.SendsLeft--
    if err := resumeSnapshot(before, after, 1, packet, len(packet)); err != nil {
        t.Fatalf("same connection and active match should resume: %v", err)
    }

    reconnected := after
    reconnected.ConnGen++
    if err := resumeSnapshot(before, reconnected, 1, packet, len(packet)); err == nil {
        t.Fatal("old send must not resume in the new connection generation")
    }

    ended := after
    ended.Phase = "post-match"
    if err := resumeSnapshot(before, ended, 1, packet, len(packet)); err == nil {
        t.Fatal("old send must not resume after the match phase ends")
    }
}

This test calls resumeSnapshot directly, accepting a valid progression on the same connection while rejecting both a new connection generation and an ended match phase, so any change that weakens the resume check to after.Connected fails immediately.


How does this relate to goroutines, net, and io?

Go’s goroutines and standard net and io packages are strong defaults and remain the right choice for most Go services. In general application code, hiding syscall counts, goroutine scheduling, internal buffering, and completion identity keeps code simple; under a tight real-time latency budget, those are often the details that need to be inspected and controlled. This stack targets paths where keeping non-blocking outcomes (iox), suspension points (kont), io_uring submission and buffer lifecycles (uring), and completion routing (takt) explicit in code is worth that extra detail.

Why use cove instead of an inline check?

When the only rule across a pause is that ConnGen has not changed, a simple before.ConnGen == after.ConnGen check is enough. cove helps when several context rules, such as connection generation, match phase, and send budget for each peer, need to be combined, given diagnostic names (RuleExpr), attached to kont suspensions (SuspensionView), and checked across world transitions (Preorder, StepIndex) in both runtime paths and unit tests [20–26].

How do kont, takt, and sess relate to effect handlers, proactors, and session types?

The Proactor pattern separates initiating an asynchronous operation with a completion token from dispatching its completion handler [6]. Defunctionalization and delimited control show how higher-order continuations can be represented as explicit frame data and converted between closure and frame forms [12–14], while algebraic effect handlers and freer monads separate requested operations from their interpretation [15–19]. kont and takt combine those ideas in Go 1.26: kont chooses affine one-shot suspension handles and represents suspended operations through generic interfaces and Expr frames (with optional pools for single-use paths) while keeping step functions as ordinary Go closures, and takt drives those suspensions across blocking, single-step, and proactor loops. Above them, sess draws on session types and effect encodings of sessions [27–31] to structure send, receive, choice, and loop steps over bounded lfq.SPSC queues.

How does stepping in unit tests relate to deterministic simulation testing?

Deterministic simulation testing runs an entire distributed state machine inside a seeded simulator with fault injection [32]. Stepping kont, cove, takt, or sess values in Go unit tests works at the unit level: it exercises individual pause, context transition, and resume steps directly in memory, complementing full-system simulation and integration testing.


8. Measuring Performance on Your Linux Environment

Rather than relying on fixed numbers from a single benchmark machine, each repository includes Go benchmark and allocation suites so you can measure latency, throughput, and heap behavior directly on your own Linux kernel, CPU topology, and workload.

8.1 Environment Preparation

  • Baseline: use Linux 6.18+ (uname -r) and Go 1.26+ (go version) so single-issuer rings, deferred task work (IORING_SETUP_SINGLE_ISSUER, IORING_SETUP_DEFER_TASKRUN), provided buffer rings, multishot operations, and zero-copy send notifications are supported, and verify that the target kernel supports the required ring features and opcodes.
  • Locked memory and CPU stability: ensure sufficient RLIMIT_MEMLOCK (ulimit -l) when registering fixed or provided buffer rings, and keep CPU frequency scaling and affinity steady (for example, recording the performance governor and taskset affinity alongside runtime.LockOSThread for single-issuer rings) when comparing microsecond latency across runs.

8.2 What Becomes Easier to Measure

Because the stack keeps runtime and control steps explicit, you can measure each layer independently before benchmarking a full server:

  • Continuation, context, runner, and session stepping (kont, cove, takt, sess): measure Cont vs. Expr evaluation (BenchmarkRunStateExprDirect, BenchmarkStepExprWith), single-step and loop dispatch (BenchmarkLoopSubmitPoll, BenchmarkExecErrorExpr), and session protocol steps (BenchmarkExprSendRecv, BenchmarkExprProtocol3Step), and verify the pure-expression allocation cases with TestExprAllocationsPure in kont/allocs_test.go.
  • Outcome classification and non-blocking engines (iox, lfq): measure outcome classification (BenchmarkClassify_WouldBlock), non-blocking Copy, CopyN, TeeReader, and TeeWriter paths (BenchmarkCopy_SlowPath, BenchmarkTeeReader), and bounded lock-free queue operations (BenchmarkSPSC_SingleOp, BenchmarkMPMC_SingleOp).
  • Linux io_uring submission, completion, and zero-copy paths (uring): measure SQEContext packing and CQEView decoding (BenchmarkPublicPerformanceSQEContextPackDirect, BenchmarkPublicPerformanceCQEViewAccessors), single and batched socket round trips (BenchmarkPublicPerformanceSocketIORoundTrip, BenchmarkPublicPerformanceSocketIOBatchRoundTrip), storage write and read cycles (BenchmarkPublicPerformanceStorageIOWriteRead), and normal vs. zero-copy sends (BenchmarkZeroCopyVsNormal, BenchmarkPublicPerformanceZeroCopyIO).

8.3 Running the Suites

Run the allocation checks and package benchmarks with -benchmem from a workspace or module checkout on Linux:

# Check the pure-expression allocation cases in kont
go test -v -run=TestExprAllocationsPure code.hybscloud.com/kont

# Measure outcome engines, lock-free queues, and continuation, context, runner, and session stepping
go test -run=^$ -bench=. -benchmem \
  code.hybscloud.com/iox \
  code.hybscloud.com/lfq \
  code.hybscloud.com/kont \
  code.hybscloud.com/cove \
  code.hybscloud.com/takt \
  code.hybscloud.com/sess

# Measure Linux io_uring context packing, socket round trips, and zero-copy sends
go test -run=^$ -bench=BenchmarkPublicPerformance -benchmem code.hybscloud.com/uring
go test -run=^$ -bench=BenchmarkZeroCopyVsNormal -benchtime=1s -benchmem code.hybscloud.com/uring

In the output, check allocs/op and B/op for each measured path first, separating setup and construction from steady-state execution (for example, pure expression evaluation, effectful stepping, and the loop and expression setup in Listings 1–2 have distinct allocation profiles). Then compare ns/op and MB/s across payload sizes (512B to 64KiB) and batch sizes (Batch16, Batch64) to see where batching, provided buffers, or SendZC help your workload.


Summary

The stack is built around one practical idea: do not hide the facts that decide latency and correctness.

  • At the bottom, runtime primitives (zcall, iofd, sock, framer, iobuf, lfq, spin, atomix, dwcas) keep systems facts explicit.
  • At the center, iox gives I/O observations precise progress and control meaning.
  • At the Linux completion layer, uring turns raw io_uring mechanics into explicit submission, buffer, and completion concepts.
  • At the computation and protocol layer, kont represents suspended computations, cove represents context checks, takt drives blocking, single-step, and proactor execution, and sess represents protocol steps.

Together, these layers keep performance facts visible while giving coding agents a clear local structure to inspect, test, and evolve.

Glossary

A short reference for the terms used in this article.

  • Suspended computation: a paused computation represented as a value, with its pending operation and a one-shot continuation.
  • Continuation: the rest of a computation, made explicit so it can be named, stored, and resumed.
  • Defunctionalization: representing higher-order control as data interpreted by an evaluator; here, Expr exposes continuation structure as frames while functions within those frames remain Go functions that may capture values.
  • Trampoline: an evaluation loop that reduces one step at a time instead of growing the Go call stack.
  • Affine use: a value may be used at most once; for example, a Suspension may be resumed once or discarded.
  • Effect and handler: an operation requested by a computation, and the dispatcher or runner that interprets that operation.
  • Coeffect: required context made explicit; where an effect describes what a computation requests, a coeffect describes what context it depends on.
  • World and preorder: a runtime context and a relation (Preorder) that states which later context is a valid successor.
  • Step index: a counter (StepIndex) bounding how many external pauses a check may take.
  • Proactor: an asynchronous model where a program submits an operation with a completion token first and dispatches the completion handler after the kernel finishes the transfer.
  • Multishot: one submitted io_uring operation that produces multiple completions marked with IORING_CQE_F_MORE before it ends.
  • Zero-copy notification: a completion (IORING_CQE_F_NOTIF) that tells the program when the kernel and NIC are finished reading a zero-copy buffer.
  • Provided buffer: a buffer selected by the kernel from a registered buffer group or ring, with the chosen BufID reported in the completion.
  • Backpressure: the signal (iox.ErrWouldBlock) that a bounded queue or ring is full; an empty queue or idle poll also returns ErrWouldBlock when no input is ready.
  • SPSC, MPSC, SPMC, MPMC: bounded lock-free queue shapes named by single or multiple producer and consumer counts.

References

The references below are grouped by the role they play in this article: runtime I/O and the completion model [1–6], bounded runtime pressure and lock-free queues [7–11], continuations, defunctionalization, and effects [12–19], context evidence and world movement [20–26], session types, protocol structure, and simulation testing [27–32], the adapter and ownership contracts used by the examples [33–37], and the continuation implementation [38].

  1. liburing contributors. 2026. io_uring_setup(2), Linux Programmer’s Manual. Manual; upstream source.
  2. liburing contributors. 2026. io_uring_prep_send_zc(3), liburing Manual. https://man7.org/linux/man-pages/man3/io_uring_prep_send_zc.3.html
  3. liburing contributors. 2026. io_uring(7), Linux Programmer’s Manual. Manual; upstream source.
  4. Jens Axboe. 2019. Efficient IO with io_uring. https://kernel.dk/io_uring.pdf
  5. liburing contributors. 2026. liburing Wiki. https://github.com/axboe/liburing/wiki
  6. Irfan Pyarali, Tim Harrison, Douglas C. Schmidt, and Thomas D. Jordan. 1997. Proactor: An Object Behavioral Pattern for Demultiplexing and Dispatching Handlers for Asynchronous Events. In Proceedings of the 4th Annual Pattern Languages of Programming Conference (PLoP ‘97). https://www.dre.vanderbilt.edu/~schmidt/PDF/Proactor.pdf
  7. Leslie Lamport. 1977. Proving the Correctness of Multiprocess Programs. IEEE Transactions on Software Engineering SE-3, 2 (March 1977), 125–143. https://doi.org/10.1109/TSE.1977.229904
  8. Adam Morrison and Yehuda Afek. 2013. Fast Concurrent Queues for x86 Processors. In Proceedings of the 18th ACM SIGPLAN Symposium on Principles and Practice of Parallel Programming (PPoPP ‘13), 103–112. https://doi.org/10.1145/2442516.2442527
  9. Ruslan Nikolaev. 2019. A Scalable, Portable, and Memory-Efficient Lock-Free FIFO Queue. In Proceedings of the 33rd International Symposium on Distributed Computing (DISC ‘19), LIPIcs 146, Article 28, 1–16. https://arxiv.org/abs/1908.04511
  10. Nikita Koval and Vitaly Aksenov. 2020. POSTER: Restricted Memory-Friendly Lock-Free Bounded Queues. In Proceedings of the 25th ACM SIGPLAN Symposium on Principles and Practice of Parallel Programming (PPoPP ‘20), 433–434. https://doi.org/10.1145/3332466.3374508
  11. Ruslan Nikolaev and Binoy Ravindran. 2022. wCQ: A Fast Wait-Free Queue with Bounded Memory Usage. In Proceedings of the 34th ACM Symposium on Parallelism in Algorithms and Architectures (SPAA ‘22), 307–319. https://arxiv.org/abs/2201.02179
  12. John C. Reynolds. 1972. Definitional Interpreters for Higher-Order Programming Languages. In Proceedings of the ACM Annual Conference (ACM ‘72), Vol. 2, 717–740. https://doi.org/10.1145/800194.805852
  13. Olivier Danvy and Andrzej Filinski. 1990. Abstracting Control. In Proceedings of the 1990 ACM Conference on LISP and Functional Programming (LFP ‘90), 151–160. https://doi.org/10.1145/91556.91622
  14. Andrzej Filinski. 1994. Representing Monads. In Proceedings of the 21st ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL ‘94), 446–457. https://doi.org/10.1145/174675.178047
  15. Gordon D. Plotkin and John Power. 2003. Algebraic Operations and Generic Effects. Applied Categorical Structures 11, 1 (February 2003), 69–94. https://doi.org/10.1023/A:1023064908962
  16. Gordon D. Plotkin and Matija Pretnar. 2009. Handlers of Algebraic Effects. In Proceedings of the 18th European Symposium on Programming (ESOP ‘09), LNCS 5502, 80–94. https://doi.org/10.1007/978-3-642-00590-9_7
  17. Gordon D. Plotkin and Matija Pretnar. 2013. Handling Algebraic Effects. Logical Methods in Computer Science 9, 4 (December 2013), Article 23, 1–36. https://arxiv.org/abs/1312.1399
  18. Oleg Kiselyov and Hiromi Ishii. 2015. Freer Monads, More Extensible Effects. In Proceedings of the 2015 ACM SIGPLAN Symposium on Haskell (Haskell ‘15), 94–105. https://doi.org/10.1145/2804302.2804319
  19. K. C. Sivaramakrishnan, Stephen Dolan, Leo White, Tom Kelly, Sadiq Jaffer, and Anil Madhavapeddy. 2021. Retrofitting Effect Handlers onto OCaml. In Proceedings of the 42nd ACM SIGPLAN International Conference on Programming Language Design and Implementation, 206–221. https://doi.org/10.1145/3453483.3454039
  20. Saul A. Kripke. 1963. Semantical Considerations on Modal Logic. Acta Philosophica Fennica 16, 83–94.
  21. Andrew W. Appel and David McAllester. 2001. An Indexed Model of Recursive Types for Foundational Proof-Carrying Code. ACM Transactions on Programming Languages and Systems 23, 5 (September 2001), 657–683. https://www.cs.princeton.edu/~appel/papers/indexed.pdf
  22. Tarmo Uustalu and Varmo Vene. 2008. Comonadic Notions of Computation. Electronic Notes in Theoretical Computer Science 203, 5 (June 2008), 263–284. https://doi.org/10.1016/j.entcs.2008.05.029
  23. Tomas Petricek, Dominic Orchard, and Alan Mycroft. 2014. Coeffects: A Calculus of Context-Dependent Computation. In Proceedings of the 19th ACM SIGPLAN International Conference on Functional Programming (ICFP ‘14), 123–135. https://tomasp.net/academic/papers/structural/coeffects-icfp.pdf
  24. Marco Gaboardi, Shin-ya Katsumata, Dominic Orchard, Flavien Breuvart, and Tarmo Uustalu. 2016. Combining Effects and Coeffects via Grading. In Proceedings of the 21st ACM SIGPLAN International Conference on Functional Programming (ICFP ‘16), 476–489. https://doi.org/10.1145/2951913.2951939
  25. Wenhao Tang, Leo White, Stephen Dolan, Daniel Hillerström, Sam Lindley, and Anton Lorenzen. 2025. Modal Effect Types. Proceedings of the ACM on Programming Languages 9, OOPSLA1 (April 2025), 1130–1157. https://arxiv.org/abs/2407.11816
  26. Wenhao Tang and Sam Lindley. 2026. Rows and Capabilities as Modal Effects. Proceedings of the ACM on Programming Languages 10, POPL (January 2026), 923–950. https://arxiv.org/abs/2507.10301
  27. Kohei Honda. 1993. Types for Dyadic Interaction. In Proceedings of the 4th International Conference on Concurrency Theory (CONCUR ‘93), LNCS 715, 509–523. https://doi.org/10.1007/3-540-57208-2_35
  28. Kohei Honda, Vasco T. Vasconcelos, and Makoto Kubo. 1998. Language Primitives and Type Discipline for Structured Communication-Based Programming. In Proceedings of the 7th European Symposium on Programming (ESOP ‘98), LNCS 1381, 122–138. https://doi.org/10.1007/BFb0053567
  29. Philip Wadler. 2014. Propositions as Sessions. Journal of Functional Programming 24, 2–3 (May 2014), 384–418. https://doi.org/10.1017/S095679681400001X
  30. Dominic A. Orchard and Nobuko Yoshida. 2016. Effects as Sessions, Sessions as Effects. In Proceedings of the 43rd ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL ‘16), 568–581. https://doi.org/10.1145/2837614.2837634
  31. Kohei Honda, Nobuko Yoshida, and Marco Carbone. 2016. Multiparty Asynchronous Session Types. Journal of the ACM 63, 1 (March 2016), Article 9, 1–67. https://www.doc.ic.ac.uk/~yoshida/multiparty/multiparty.pdf
  32. FoundationDB contributors. 2026. Simulation and Testing. FoundationDB Documentation, version 8.0.0. https://apple.github.io/foundationdb/testing.html

Available Packages

All listed packages are released under the MIT License: https://code.hybscloud.com/

Appendix: Package Quick Reference

This is a quick map from package to the names used above. It is a reading aid, not a full API list; the source remains the authority.

  • iox: Outcome, OutcomeOK, OutcomeWouldBlock, OutcomeMore, OutcomeFailure, ErrWouldBlock, ErrMore, ErrNoSeeker, Classify, IsProgress, IsWouldBlock, IsMore, IsSemantic, IsNonFailure, IsFailure, Copy, CopyN, TeeReader, TeeWriter, SemanticPolicy, PolicyReturn, PolicyRetry, ReturnPolicy, YieldPolicy, YieldOnWriteWouldBlockPolicy, Backoff.
  • uring: Uring, Options, New, Start, Stop, SQAvailable, CQPending, SQEContext, PackDirect, PackIndirect, PackExtended, IndirectSQE, ExtSQE, PutExtSQE, ScopedExtSQE, DirectCQE, CQEView, ExtCQE, HasMore, HasBuffer, HasBufferMore, IsNotification, BufID, Wait, WaitDirect, WaitExtended, Write, AcceptMultishot, ReceiveMultishot, SendZC, SendZCFixed, BundleIterator, MultishotSubscription, ZCTracker, OnNotification, ErrInvalidParam.
  • kont: Cont, Eff, Expr, Op, Operation, Resumed, Handler, Perform, ExprPerform, Map, ExprMap, Bind, ExprBind, Then, ExprThen, ReturnFrame, BindFrame, MapFrame, ThenFrame, EffectFrame, UnwindFrame, Reify, Reflect, Run, RunWith, RunPure, Handle, HandleExpr, Step, StepExpr, Suspension, Resume, TryResume, Discard, Phantom, Either, Throw, Catch, Shift, Reset.
  • cove: View, Extract, Ask, Extend, Cmd, Req, ReqExpr, ExprAll, ExprAny, ExprNot, ExprAtom, NeedExpr, Rule, RuleExpr, Checked, Guarded, SuspensionView, IndexedSuspensionView, StepWith, StepExprWith, StepWithIndex, StepExprWithIndex, Preorder, Extends, Relate, CheckCompletedRelation, ResumeTo, StepIndex.
  • takt: Dispatcher, Exec, ExecExpr, ExecError, ExecErrorExpr, Step, Advance, AdvanceSuspension, StepError, AdvanceError, SuspensionLike, Token, Completion, CompletionMemory, HeapMemory, BoundedMemory, Backend, Loop, NewLoop, Submit, SubmitExpr, Poll, Pending, Drain, RouteID, NewRouteID, StreamCompletion, RouteOutcome, StreamEvent, Subscription, SubscriptionBackend, SubscriptionLoop, Subscribe, Cancel, ErrLiveTokenReuse, ErrLiveRouteReuse, ErrUnsupportedMultishot.
  • sess: Send, Recv, SelectL, SelectR, Offer, Close, SendThen, RecvBind, SelectLThen, SelectRThen, OfferBranch, CloseDone, New, Run, RunExpr, Loop, ExprLoop.

Closing

For me, the central problem is not only making I/O faster, but making high-performance I/O more programmable.

In the era of agentic coding, building real-time communication systems requires both predictable low latency and clear program structure, so important runtime facts stay explicit in source code before they disappear into callbacks, side tables, or implicit runtime behavior.

Fast I/O is valuable; fast I/O with explicit program structure is easier to build, test, and evolve.

Thanks for reading.

Robin He, July 2026

Revised: November 2026 · Revision History: Change History