docs/internal/agenthub-relay.md

AgentHub relay attachment contract

This page defines relay v1. The contract and independent literals preceded the implementation; the transport is implemented, and its evidence and resource limitations are recorded in the implementation handoff. Relay literals are the byte authority. This page owns semantics and the circuit-facing boundary, not remote gateway readiness.

A route success establishes one attachment over an immutable path. It does not establish circuit TLS, endpoint TLS, client authentication, an ACL decision, an application socket, or application success. Mux OPEN_OK accepts one hop-local lane only. It cannot report complete route success.

Current owners

Routing owns RAM reachability and candidate provenance. Peer owns the existing physical-link registry, store admission barriers and channel holds. Relay owns attempts, lane pairs, downstream-first setup and immutable forwarding. Entry and origin circuit owners (bootstrap, fixed sessions and recovery) own reliable bytes, circuit identity, authentication, ciphertext retention, ACKs, close and recovery. No relay retains replay data, interprets circuit secrets, substitutes a route suffix, dials a peer, or opens an endpoint. Only the production endpoint composition provides remote gateway availability.

MechanismOwner
Frozen attachment values and bytesrelay/types.go, codec.go, independent literals
Signed directory admissionrelay/validate.go, directory's verified projection
Pair-capacity and hop-local channel holdsmux/pair.go, peer/relay.go, relay/channels.go
Attempt lifetime, immutable forwarding and downstream-first setuprelay/owner.go, binding.go, setup.go
Production origin dispatch and joined service shutdownservice/relay.go, endpoint_carrier.go, routed_pairing.go

Lower packages must not import relay to implement admission. Routing's paired extension declares neutral bounded lane interfaces in routing/types.go; peer implements them. Relay adapts those interfaces and never exposes a mux session, TLS connection, relationship-ID opener or admission callback to circuit callers. These package boundaries are implemented. Current capacities and allocation/release ownership are in the production capacity map.

Existing routing boundary and its closed extension

Read routing/types.go, routing/table.go, routing/view.go, peer/routes.go, peer/route_runtime.go and peer/channels.go as the accepted source. Actual Table.Reserve(ctx, AdmissionToken) calls AdmissionAdapter.ReserveRoute(ctx, provenance, table, validate). The peer pre-reserves one of 32 process-wide tickets, at most eight per exact link, then calls validate exactly once under peer gate, store identity barrier and manager mutex. Validation acquires the routing table mutex, checks table identity, exact link, candidate revision and expiry, and captures Path and NextHop. The ticket takes one managed hold and expires after ten seconds. Its supervisor is the route engine, not a goroutine per ticket.

Actual Admission exposes Path, NextHop, Done, Err and Close only. RouteLease opens required AHRT control, not relay channels. Provenance only exposes lock-free Usable. CandidateView.Token is opaque. No channel opening or hold transfer belongs to the routing ticket. In particular, Reserve followed by generic Manager.OpenChannel(nextHop, ...) is forbidden. It would repeat the exact-link replacement race.

The relay owner adds the following closed paired extension without changing route v1 bytes:

  • Table.ReservePair(ctx, token, PairSpec) (*PairAdmission, error). PairSpec owns bounded copies of control and bulk application setup and the absolute local setup deadline. Only the two relay v1 setups specified below are legal; they must be identical except for lane byte. PairSpec.Owner is a required opaque routing.PairOwnerCapability; PairSpec.Role is the local-only Incoming or Outgoing incident role. Neither is a wire field. One capability covers both incident pairs at a transit. It also carries a required local admission guard, not a wire field. The guard may only validate the directory snapshot and invoke table validation under the lock order below.
  • A separate PairAdmissionAdapter.ReserveRoutePair operation on the existing adapter receives the exact provenance, table, pair specification and table validator. Missing support fails closed. The original channel-free Reserve remains channel-free; it is not upgraded into a generic opener.
  • Relay alone allocates and charges one attempt-owner before any pair admission, as specified below. The adapter never allocates another relay owner, calls a service budget, or releases that owner. Before admission locks, it validates the supplied capability against the trusted issuer/scope installed by the typed relay claim and takes its unused incident-role slot. It then reserves only a ticket, both channel/window slots, both pending OPEN slots, both setup charges, control share and bounded terminal capacity. A failed pre-reservation releases those pair-local reservations and its incident claim, changes no candidate/peer state and emits no OPEN. Relay keeps the same owner for rollback. The outgoing ticket uses the existing 32/eight ticket pool during setup, not another allowance. The incoming pair uses its assembly supervisor, not a second outgoing route ticket.
  • Under peer gate -> store identity barrier -> manager mutex -> directory admission mutex -> table mutex, the adapter validates the same selected physical link and candidate revision, exact path suffix and local directory snapshot. It also checks the capability's irrevocable live bit and that its incident claim is still owned by this reservation. In that SAME transaction it commits the closed pair reservation and its managed hold. This is the admission linearization point. No generic channel admission follows a prior check. The validator is synchronous, called once and never retained; it does not allocate capacity, do I/O, join, or call the origin/circuit handler.
  • PairAdmission exposes immutable Path, NextHop and Done/Err, plus OpenPair(ctx) and Close. OpenPair is single-use and can open only the prevalidated control/bulk setups on that exact physical link. It returns a managed LanePair, including any partially opened pair on failure so the transaction can abort and settle it. It cannot accept arbitrary setup, class, link or relationship arguments. A route change after linearization does not revoke or move this pair. Peer retirement can cancel it. Unlike ordinary shutdown, exact selected-link retirement/replacement before this commit reports StaleCandidate. The paired adapter classifies that case under its manager barrier; it must not mistake routing's admission-scoped Closed for whole-manager shutdown. Caller cancellation or whole-manager shutdown remains Cancelled. The original channel-free Reserve semantics are unchanged.
  • Successful setup transfers the same holds and reservations from the setup ticket to the pair owner atomically. The ten-second ticket is then retired; it must not expire an established attachment. Cancellation racing transfer has one winner and leaves either a live pair owner or a rollback owner, never neither. Closing an old ticket cannot release a transferred pair or replacement link. The relay attempt-owner and its budget lease do not change during this pair-local transfer. Both incident claims remain with that owner through pair settlement. Transfer is internal to peer/relay, not a circuit API.

The narrow lane interface supplies Read, Write, CloseWrite, Abort, read/write deadlines, Done, Err, Settled and CommitmentTime. Pair release is idempotent and permitted only after all lane I/O owners join and both lanes settle. Do not add a public ReleaseHold shortcut for circuit callers.

Incoming pair admission uses the same peer/store barrier on the exact incoming link, with both slots pre-reserved and the same required owner capability in an Incoming PairSpec. It has no outgoing candidate to validate. Transit validates its outgoing suffix through ReservePair separately. Never hold two neighbors' peer gates at once. Incoming OPEN_OK can therefore precede outgoing admission; only the explicit response below announces route success.

Single attempt-owner allocation authority

relay/owner.go implements the package-global fixed 32-slot allocator. Each entry, transit or origin consumes exactly one slot for its local attempt, not one per lane, pair, ticket or phase. A -> B -> C therefore consumes three owners in one process hosting all three Hubs, with incident pair counts 1, 2, 1. If each Hub is a separate process, each local allocator consumes one owner. The second pair at B must carry B's original owner capability. It cannot mint a second owner or release the incoming one to make capacity available.

The internal ReserveAttempt(ctx, metadata, ReserveAttemptBudget) operation is the sole allocator entry. ReserveAttemptBudget has the neutral callback type func(context.Context) (AttemptBudgetLease, error); AttemptBudgetLease exposes idempotent Close() error, matching the existing service BudgetLease. It is injected by service and returns a lease charged with 96 KiB data and 8 KiB control. Relay first claims a global slot without allocating attempt storage, unlocks the pool, calls that callback, and only on success initializes charged storage and issues its capability. Callback failure returns the slot without launching workers or admitting pairs. Cancellation at any step unwinds both resources. The injected callback must honor context cancellation and perform only bounded local budget reservation, not external I/O or an independent callback worker. The pool mutex is never held across a budget callback, peer admission or join. No peer-to-service import or budget callback under admission locks is allowed. Tests supply a bounded reservation callback, never an uncharged nil fallback.

routing.PairOwnerCapability is a neutral opaque value with no public field constructor, not a caller-implemented accept-all interface. Its trusted issuer is created once by the relay allocator. The neutral issuer/factory declarations live in routing/types.go; issuance is confined to that trusted allocator after the slot and service lease have been obtained. Peer's typed relay claim pins the issuer and the owning service/manager scope before dispatch starts. A capability binds that scope, a non-reused slot generation, immutable attempt/endpoint/mode/path metadata, local path position and two fixed incident-role slots. Incoming setups name that local position; Outgoing setups name the next receiver at local position plus one. Peer rejects zero, foreign-scope, released or mismatched capabilities. It claims the requested incident role before admission locks; no third incident pair or duplicate claim is legal. The neutral issuer's bounded identity/role metadata is included in the fixed pool proof, not another owner or peer-link registry.

Capability cancellation is an irrevocable lock-free live-bit change observed at the pair commit barrier. It forbids new incident claims and commits but does not release capacity. Pair-role claim/release synchronization happens outside peer/store/directory/table locks; only nonblocking liveness/identity checks occur under admission locks. Cancellation immediately after the commit belongs to that committed pair's rollback owner. Claims retain the originating generation through settlement; a late release cannot free a reused slot.

Only relay releases the attempt-owner: first abort pending work as necessary, join its supervisor, pumps and any origin acquisition, settle both incident pairs and release their claims, then retire the capability, clear storage, release the per-service lease and return the global slot exactly once. Entry success or origin acceptance transfers use of that SAME owner to Attachment; it does not allocate or release an owner. A borrowed ControlMessage keeps its owner charged until its release. No service shutdown can free another service's slot, lease or still-live capability.

Directory admission

Existing LearnedDirectory.Endpoints() returns independently owned public views but copies keys, evidence and all endpoint rows. EndpointView.OriginRoot is the binding's stable genesis; Origin is an authority head. Use OriginRoot. The directory may add a fixed-size EndpointAdmissionView containing ID, OriginRoot, BindingGeneration, Published and Conflict plus a usable-selected-binding flag. No SPKI, private descriptor, ACL, address or socket enters relay setup.

For new, entry, every transit and origin require a current verified selected binding for this endpoint, nonzero binding generation, publication, no conflict, and OriginRoot == path[last]. A lookup captures that local view. A narrow WithEndpointAdmission(ctx, capturedView, validate) callback rechecks the exact view under the directory mutex at paired admission and invokes only the table validator. At origin it rechecks before committing the origin offer. Directory replacement/withdrawal before this point fails the attempt. A later withdrawal does not by itself kill an admitted attachment or working circuit. Each Hub validates its own current view; no binding generation is added to the wire.

No caller holds the directory/table mutex while acquiring a peer/store barrier. The callback runs inside peer admission in the order above, and directory code must never call peer while holding its mutex. Origin retained-state checks and all external callbacks occur outside these locks. A separate origin-owned commit barrier handles cancellation versus retained-state acquisition.

For reattach, validate all transport metadata and route provenance, but do not require a current published endpoint row or synthesize a binding. Remembered origin permits an attempt only. The origin retained-state owner must find and authenticate still-live matching circuit state before resuming any endpoint stream. A missing handler, missing/dead endpoint or retained state, or failed authentication denies it. Recovery cannot dial a new AF_UNIX socket, recreate an endpoint, or replace the existing endpoint TLS session. Publication withdrawal alone neither authorizes recovery nor prohibits all attempts.

Setup bytes and lane association

All integers are unsigned big-endian. IDs are raw binary, not hex text. The application setup on both lanes has this exact layout:

FieldBytesRule
Magic/version541 48 52 41 01, AHRA\x01
Lane101 control, 02 bulk
Attempt16Fresh nonzero random ID generated by entry
Endpoint32Nonzero identity.ID
Mode101 new, 02 reattach
Position1Receiver's zero-based index in the full path
Path count n12 through 8 Hubs
Full path32nEntry first, origin last, unique nonzero stable roots
Opaque setup length q20 through 512
Opaque circuit setupqUninterpreted bytes copied unchanged at every hop

Application setup is exactly 59 + 32n + q bytes, at most 827. The mandatory peer mux class byte precedes it: 01 for control, 02 for bulk. The full mux OPEN setup is at most 828 bytes. No padding, optional field, negotiation, trailing bytes, other version, lane, mode or count is legal. In particular, there is no circuit ID, candidate revision, endpoint generation, address, client identity, secret format or timeout timestamp field added by a codec. The opaque slot belongs to later circuit bootstrap/recovery. Empty is legal transport syntax, not an instruction to an origin handler to accept it.

Entry draws 16 bytes from the existing cryptographic random source and rejects zero and collisions with its active or terminating IDs. It never reuses an ID for a retry. Random-source failure fails locally before sending. A transit keys association by exact incoming physical link plus attempt. Two different links cannot contribute lanes to one pair. Identical IDs from different entry paths are not circuit authentication and are separate bounded owners.

On A -> B -> C, A sends both setups with full [A,B,C], position 1. B sends both with the same attempt, endpoint, mode, path and opaque bytes, position 2. B validates its stable root at index 1 and A from the actual incoming peer capability at index 0. C validates C at index 2 and B at index 1. Authenticate stable genesis, not the link's authority head or claimed bytes alone. Position must be in 1 through n-1; root at that position must be local. A loop, wrong predecessor, self-hop or inconsistent position is a protocol error.

At each transit, look up path[last] and choose only a candidate whose complete local entry-to-origin CandidateView.Path equals the requested suffix starting at the local position. An eligible retained alternative may match. Selection preference alone does not authorize another suffix. Reserve its opaque token and revalidate that suffix within ReservePair. No match returns NoRoute; a previously captured token that has expired, changed or lost its exact link returns StaleCandidate. Never resolve a replacement physical link by root.

Assembly and dispatcher

READY composition claims a typed relay consumer alongside required directory and route consumers before workers start. Relay is optional traffic, gated until all three required channels commit. One exact-link dispatcher remains the sole Session.Next caller. It recognizes reserved AHRA prefixes; generic APIs reject them. It dispatches proposal references, not copied pending setups. Unknown versions/classes/shape reject with existing OpenErrorRejected = 1. Malformed mux class framing retains the mux's existing fatal disposition.

The opener sends control first and waits for its hop-local OPEN_OK, then sends bulk. The receiver reserves the sibling and accepts control without waiting for bulk, so serial opening cannot deadlock. A bulk-first proposal, duplicate lane, second attempt with the same key while it is active/terminating, wrong class, or metadata mismatch fails that attempt and resets any accepted sibling. It does not steal directory/route proposals or drain an otherwise healthy link. For a second setup whose lane differs, all other application bytes must match exactly. Association cannot rely only on the 16-byte attempt ID.

The link inbox retains at most six relay proposal references, within the same eight mux pending OPENs. At most three pair assemblies per link may be pending at once, and at most eight pairs per link may be owned in all phases. The first proposal invokes relay's sole attempt allocator, then reserves its complete incoming pair with that owner capability before acceptance. The assembly reuses that owner for its second lane and any downstream pair. A full/unclaimed inbox rejects without an extra backlog. Dispatcher validates only bounded setup and association metadata; it must not call a circuit handler or block on network I/O. Slow consumers do not impede required dispatch or another link.

Control-lane frames and complete route response

Control DATA is a framed byte stream, independent of mux DATA boundaries. Each message has a four-byte body length followed by version 01, kind, attempt and the kind-specific fields. The length excludes its own four bytes.

KindByteFields after version/kindBody bytesTotal bytes
ROUTE_OK01attempt[16], opaque response length u16, response[q]20 + q24 + q
ROUTE_ERROR02attempt[16], failure code u8, failing position u82024
CIRCUIT_CONTROL03attempt[16], opaque length u16, payload[r]20 + r24 + r
ATTACHMENT_ABORT04attempt[16], failure code u8, failing position u82024

ROUTE_OK q is 0 through 512. CIRCUIT_CONTROL r is 1 through 1024. Maximum body is 1044, maximum complete frame 1048. Kind-specific lengths are exact; reserve fixed parser storage before accepting a length. Zero/unknown version, kind, failure code, attempt, bad position, excess length or trailing fields fail the attachment as Protocol. An incomplete declared frame caused by EOF, RESET or link loss is Transport; a complete frame with inconsistent fields or length is Protocol. Reject an invalid declared length immediately as Protocol, without reading its body. Opaque bytes may contain any octet. They are not parsed, authenticated, compressed or reclassified by relay. The attempt must match this pair. Failure position is 0 through n-1 and identifies the detecting Hub; intermediates forward it unchanged.

Failure codeByteMeaning
Denied01Origin handler absent/refused or current new-endpoint admission fails
NoRoute02No candidate matches the requested exact suffix
StaleCandidate03Captured candidate or exact link lost admission before commit
Limit04Finite owner/pair/buffer capacity unavailable
Timeout05Assembly/setup/frame/write deadline
Protocol06Relay syntax, association or state violation
Transport07Link/lane RESET, truncation or unexpected loss
Cancelled08Caller cancellation or ordinary owner shutdown

These are relay response codes, not routing Code numbers or mux RESET codes. Local errors use *relay.Failure with these codes plus Invalid = 9 for malformed local calls; Invalid is never sent. A local failure also contains the failing position and, if relevant, the underlying typed routing cause. Mapping is explicit: routing NoRoute -> NoRoute; StaleCandidate -> StaleCandidate; Limit -> Limit; Timeout -> Timeout; Closed -> Cancelled for ordinary cancellation, otherwise Transport; Protocol/Gap -> Protocol; Exhausted -> Limit; Transport -> Transport; Invalid -> local-only Invalid. Invalid is a caller/construction bug, never a remote wire response. If an already accepted attempt must unwind because of that bug, abort/reset it without encoding Invalid. Preserve table-scoped fatal handling in service, not just its relay mapping.

Exactly one terminal setup response travels downstream to upstream on each accepted control lane. ROUTE_OK is sent only after downstream ROUTE_OK, both downstream and upstream lanes exist, and the local immutable forwarding binding is installed. At origin it requires both lanes and an accepted origin offer. The origin's bounded opaque response is forwarded unchanged. One lane's OPEN_OK, pair assembly, ticket reservation or origin callback entry is not route success. A response write succeeds at mux queue admission, not remote observation. Entry publishes an attachment only after it parses a valid OK and owns both lanes with no latched cancellation/error.

On failure before OK, send ROUTE_ERROR if the upstream control lane is usable. If it is not usable, RESET/transport error is the result; never manufacture OK. No second setup response is legal. CIRCUIT_CONTROL is legal only after OK in that direction. The origin may queue it after its OK; the entry may send it after receiving OK. Transit must preserve this ordering, including a coalesced OK followed by control, while it finishes its upstream publication. A sender must not send circuit bulk before its own OK boundary. Nevertheless, valid bulk may arrive before the receiver processes OK: separate lanes and reader scheduling have no cross-lane ordering. Gate bulk delivery/forwarding until valid local route success. Leave such bytes in the existing bounded mux receive window without reading them into a second queue; abort and discard on setup failure. Arrival before observed OK alone is not a detectable sender violation and must not fail valid traffic. Control before OK on the same control stream remains Protocol. No setup ACK or cross-lane ordering field is added. Circuit bootstrap uses the opaque setup and response slots without adding relay transport fields.

ATTACHMENT_ABORT is legal during setup or operation and is always abortive. It cancels the local transaction, propagates best-effort to the other side and starts lane RESET. It is not authenticated circuit close. No ACK, retry, heartbeat, route refresh or recovery message is added to relay v1. Circuit bootstrap and session protocols use opaque fields and own their transcript, ACK and HMAC formats.

Downstream transaction, deadlines and rollback

Entry snapshots one path, allocates a fresh attempt ID and calls ReserveAttempt once before outgoing pair admission. A transit's first incoming proposal calls the same allocator once, assembles its incoming pair, validates the request and reserves the exact outgoing suffix using that owner's Outgoing role. Origin uses its one incoming owner and accepts or refuses an offer outside admission locks. Setup proceeds downstream first; success publication unwinds upstream. No transit retry or path substitution is allowed. A future entry recovery owner may start another attempt with a new ID and a newly selected path.

The entry's entire attempt has an absolute ten-second deadline starting before its first pair reservation. Every receiver has an absolute ten-second assembly and setup deadline from its first proposal; pair acceptance, bulk arrival, callback start or downstream OK never restarts it. An outbound ticket uses the earlier of its inherited local attempt deadline and the routing ten-second ticket limit. A frame completion or complete-frame write gets at most ten seconds from first byte/first write, also capped by setup deadline while setup is pending. Idle established control reads have no relay deadline; existing mux liveness applies. No arbitrary traffic extends any deadline.

There is no synchronized clock or transmitted deadline. Receivers cannot know the entry's remaining time. Entry cancellation/timeout aborts its pair and propagates downstream through control/reset. A delayed success must roll back when its upstream pair is cancelled. A relay may still be finishing rollback after entry's deadline, but it cannot publish a usable orphan or extend the entry's attempt. All pending work remains charged until joined settlement.

Commit boundaryCancellation/failure owner
Before paired admissionRelease pre-reservations, no OPEN and no hold
Reservation committed, no lane acceptedTicket owns cancellation; cancel queued OPEN without reusing channel ID; settle any late acceptance
Control accepted, bulk missingAssembly owner resets control, rejects pending bulk and settles both reservations
Incoming pair exists, downstream pendingTransaction aborts downstream, reports upstream error when possible, joins and settles partial pairs
Origin accepts before upstream OKOrigin offer stays revocable; upstream failure aborts the offer and both lanes; retained-state owner must undo its attachment acquisition
Downstream OK, upstream publication pendingTransaction owns both pairs and offer until publication handoff; cancellation wins over an unobserved OK
Entry receives OK and publishesOwnership moves once to Attachment; subsequent loss terminates it, not a new setup result

A callback must return on cancellation under the origin interface requirements below. A return racing cancellation cannot resurrect its offer. Late OPEN_OK, OK responses and bulk proposals reset/settle under the original owner. Do not release an ID/slot at Done and then let a late completion target a replacement. A failure response is best-effort before abort; it is not an acknowledged rollback barrier. Peer mux ordered RESET and Settled provide the hop settlement boundary. Mux decision/terminal deadlines remain 30 seconds; peer drain remains five seconds. A terminal timeout fails only that exact physical mux and releases holds through its joined failure, not by eviction.

Immutable forwarding, FIN and settlement

A binding fixes incoming/outgoing exact links, pair handles and metadata for its lifetime. Route expiry, withdrawal, a shorter path or a new preferred link changes future attempts only. Peer removal/fork/drain can terminate the actual links under the existing manager policy. No relay migrates a binding.

Relay forwards bulk in FIFO order with one bounded writer per direction. Partial writes retain only the unadmitted suffix in that direction's fixed buffer. Forward complete opaque control messages in FIFO order on control lanes, never on bulk. There is no ordering promise between lanes; the circuit owner must express required cross-lane ordering in its opaque protocol. Pair identity and trusted immediate peers do not authenticate an end-to-end circuit.

Bulk FIN is directional. Drain every accepted byte before CloseWrite on the corresponding outgoing bulk direction. Continue reverse bulk and both control directions. One bulk FIN must not close control. A sender may finish its own controls and half-close control only after it has finished its bulk direction and all accepted controls. Receiving control FIN before the corresponding bulk FIN is observed is not by itself Protocol, because lanes can reorder. Record that control half-close and keep draining the bulk direction. A transit defers forwarding control FIN until the corresponding bulk FIN has actually drained across the binding. Source-side misuse of CloseWriteControl before bulk CloseWrite fails locally as Invalid, rather than relying on arrival order to infer a remote violation. Clean attachment retirement needs both bulk FINs, both control FINs, drained buffers and settled channels. This is attachment EOF, not proof of clean circuit/application EOF; later circuit owners authenticate their own close.

RESET, ATTACHMENT_ABORT, cancellation, transport failure, setup failure or EOF inside a control frame aborts the entire attachment. Propagate abort/reset to both lanes on both sides, wake blocked reads/writes, stop accepting controls, and join setup, origin and all pump owners outside locks. Do not convert loss into clean EOF. Hold pair/owner/control-share/budget capacity through all lane Settled() barriers or exact-link failure and all worker joins. Then release once. An origin's retained circuit state is separately circuit-owned and may outlive this failed attachment; relay cannot delete, recover or replay it.

Circuit-facing entry and origin API

relay/types.go publishes these declarations before consumers compile; service composition follows the relay owner. Their semantic requirements are frozen here; implementation may use concrete private handles, not expose raw mux or mutable metadata.

  • Entry.Start(ctx, EntryRequest) (*Attachment, error) accepts endpoint, mode, an immutable candidate value/token and at most 512 opaque setup bytes. It generates the attempt ID, validates new publication, enforces the chosen path and deadline, and returns only after complete route OK. Return failure with no usable attachment. It performs no retry, TLS or endpoint opening.
  • Attachment metadata is a value containing attempt[16], endpoint, full routing.Path, mode and origin root. Position remains hop-local. Callers receive at most 512 opaque origin-response bytes. They cannot change a path or replace lanes. An attachment belongs to one entry or origin circuit owner.
  • Attachment.Bulk() supplies the bounded duplex byte stream with directional CloseWrite; SendControl(ctx, []byte) error and ReceiveControl(ctx) (*ControlMessage, error) preserve complete opaque messages of 1 through 1024 bytes. ControlMessage.Bytes() borrows the bounded payload until idempotent Release(); the caller may hold only one message and must release it before another ReceiveControl. Use after release is invalid, and a late release cannot free a newer delivery. SendControl copies or admits the complete payload before returning, so the caller may reuse its input afterward. Abort wakes blocked send/receive, but borrowed storage stays charged until released and its owner joins. No unbounded channel of controls, detached decode copies or concurrent writer goroutines are allowed.
  • Attachment.Done()/Err() report terminal cause. Abort() is idempotent abortive termination; Wait() joins settlement. CloseWriteControl() orders FIN after accepted controls and the caller's bulk FIN. Circuit owners keep the attachment owned until Wait. The Start context remains its lifecycle parent after success; cancelling it aborts the attachment.
  • OriginHandler.Admit(ctx, OriginRequest, *OriginOffer) (OriginAcceptance, error) is invoked once outside all directory/table/peer locks. OriginRequest is an immutable metadata value and bounded opaque setup. It contains public new admission evidence when mode is new, never an invented reattach publication. Offer supplies the same bounded lanes without any raw peer connection. Admit is synchronous in the charged attempt supervisor. It MUST respond to ctx.Done and return promptly when cancellation or the absolute setup deadline closes that context. Every blocking operation must use that context or be woken by its cancellation; uninterruptible I/O, detached work and waiting for the offer's ready barrier inside Admit are forbidden. The barrier cannot open until Admit has returned acceptance. No independent callback worker is added to hide a nonresponsive handler. A nonresponsive implementation violates this supported interface and can strand shutdown; service composition must test cancellation of blocked Admit and reject such an implementation, not claim forced termination of arbitrary in-process code. OriginOffer is borrowed only for the call: Admit must not retain or use it after return. OriginOffer.TakeAttachment() (*Attachment, error) is single-use and returns an owned provisional Attachment for the returned acquisition, not a second attempt-owner. That handle remains revocable and bulk/control delivery is gated by ready. Only the acquisition may retain the handle after return; a retained pointer to the borrowed offer is not the lifecycle API.
  • OriginAcceptance carries at most 512 opaque response bytes and an owned, closeable origin acquisition. The provisional attachment is revocable until route setup publication and remains tied to its attempt after it. The borrowed OriginOffer itself expires on Admit return. Handler may acquire future circuit state and arrange bounded bootstrap work, but may not send bulk/control before the offer's ready barrier. Relay closes and joins that acquisition on cancellation, denial or failed publication. The acquisition's Abort/Wait must wake and join handler-owned work, with no I/O under locks. Handler invocation uses the attempt owner, not an extra uncharged worker. Every return, including error/cancellation, is either zero acceptance with all locally acquired resources already unwound, or acceptance containing the acquisition that relay can immediately Abort and Wait. A zero acceptance must not abandon a taken provisional attachment or retained-state hold. Relay first checks ctx and latched owner cancellation after the call returns; on any error, timeout, malformed acceptance or cancellation it aborts/joins every returned acquisition before releasing pairs and the attempt-owner. Acquisition Abort must wake its blocking work and Wait must join it without depending on successful OK publication. The acquisition, not OriginOffer, retains the ready-gated attachment handle on success. Any extra future circuit workers are separately bounded/charged by that owner, never relay callback workers omitted from the five-worker proof. Acquisition Wait joins only handler-owned work and releases its circuit-state acquisition. It must not wait for Attachment.Wait or the relay supervisor, which is currently joining that acquisition. Handler cleanup must not free the relay attempt-owner or incident pair claims. Relay retains the abort authority for a taken handle even if Admit returns malformed/zero acceptance. It can revoke that handle, but cannot recover an undisclosed circuit-state hold, which is why zero acceptance requires complete handler-local cleanup.
  • Optional OriginSettlement.ReleaseAfterSettlement() is a bounded local idempotent release hook, not another join owner. Relay invokes it exactly once after acquisition.Wait, pumps/users, borrowed-control release and both lane settlements/pair release, before returning the attempt charge. Binding rollback uses the same terminal run; partial/empty rollback invokes it after any partial pair settlement. It performs no I/O, wait, worker creation or relay reentry. This internal circuit-bootstrap prerequisite changes no setup bytes or JSONL contract.

For new, the origin checks current local endpoint existence/public admission and the handler explicitly admits quarantined circuit bootstrap. Relay does not accept the client, perform TLS, ACL checks or an application open. Circuit bootstrap establishes circuit possession/control integrity only; endpoint TLS/ACL application authorization and remote application composition remain separate. For reattach, before returning acceptance the handler must locate and acquire still-live matching retained circuit state, including the existing live endpoint connection. Missing/dead state rejects before OK. This acquisition is revocable and is not authorization to resume its bytes. Attachment.ReadyAt() is the immutable local Ready publication time, including its monotonic component, and is zero before that publication. Both entry and origin attachments record it immediately before opening the barrier. Circuit bootstrap derives its absolute deadline from it, not from later worker execution. It is never transmitted and adds no relay timer or worker.

The origin offer's ready barrier opens after local OK publication; it allows only circuit-owned quarantined bootstrap traffic until the retained-state owner has authenticated this new attachment against that live matching circuit. Authentication may use the opaque setup/response or later bounded bulk/control bootstrap as the circuit contract specifies. It must finish before any paused endpoint bytes resume. Mode, attempt ID and immediate peer alone never satisfy it. OriginAcceptance means ownership of this acquired, possibly quarantined attachment, not authenticated recovery success. If authentication already finished before OK, the same owner may release quarantine after the ready barrier. Otherwise it keeps endpoint traffic paused and aborts the attachment on authentication failure. Route OK establishes an attachment only in both cases. No transcript, ACK, HMAC or extra transport field is prescribed here.

A nil/missing origin handler returns Denied. A fail-closed handler with no circuit consumer denies new and reattach. No accept-all origin, direct-handler fallback, recovery-state placeholder or AF_UNIX dial is legal. Tests may inject a bounded internal fake via service construction, not a new network/debug/JSONL API. Circuit cryptography, TLS transcript, authenticated ACK/control encoding, HMAC, retained recovery buffers and timers are not relay concerns. The circuit owner implements fixed DATA/control, acceptance-based cumulative ACKs, liveness and authenticated final-cursor close above this unchanged transport. Relay still does not interpret them or convert lane FIN into circuit EOF. Actual service ACK capture, pressure and session join evidence is distinct from the relay's synthetic controls. Origin Session.Wait joins circuit work only; this supervisor then settles both lanes and invokes OriginSettlement. Entry Session.Wait instead joins its local Attachment.Wait synchronously. Circuit and relay reservations remain separately charged. No recovery or application consumer is installed.

Finite resources and count/byte proof

These limits are local failure containment, not network DDoS protection. Reserve before allocation/workers. Established, assembling and terminating owners all count until join/settlement. Capacities are ceilings, not guaranteed throughput. The process-wide slot allocator is shared by service instances, like routing tickets. Actual service.Start creates an independent Budget per service; neither DefaultBudgetLimits nor its maps create a process-wide budget. The global pool and the service leases therefore have separate accounting and lifetimes below.

Owner/resourceBound
Relay attempt/binding owners, all roles combined32 process-wide
Pairs incident on one exact link, incoming plus outgoing8
Simultaneous assembling/opening pairs per link3
Relay incoming proposal references per link6, part of the mux's 8 pending
Setup ticketsExisting 32 globally/eight per link, not doubled
Channels per attachment at transit4, two per incident link
Active channels with eight pairs on a link3 required + 16 relay = 19 <= 32
Control queue share per incident pair4096 bytes, maximum per relay control lane
Opaque setup/response512 bytes each
Opaque control / encoded parser1024 / 1048 bytes
Bulk pump buffer per direction16 KiB, one admitted/in-flight slice only
Control frame buffer per direction1048 bytes, no second outbound queue
Workers per ownerAt most 5: one joined setup/lifecycle supervisor and four directional pumps
Relay timers per ownerAt most 5: setup plus four non-sliding active frame/write deadlines

Pair reservation accounts jointly for outgoing/incoming pending, active and terminal records. Keep two pending slots and 8 KiB setup protected for required consumers. Relay may use at most six pending slots, as three whole pairs. Two 828-byte setups cost 1656 bytes/pair; three pairs cost 4968. With the required 8192 reserve this is 13,160 <= 32,768 pending setup bytes. Pending state belongs to mux, not a duplicated dispatcher backlog. A reservation occupies its sibling capacity until assembly succeeds or settles. Opposite openers use the same counters. Refuse a pair unless both lane slots/windows and terminal liabilities fit; cannot half-admit then hope capacity becomes available.

Keep 32 active and 32 terminal mux bounds and 64 KiB initial receive windows. Use a conservative combined pending/active/terminal/reserved channel liability ceiling of 32 for new relay admission, including sibling slots. Existing rejected OPEN records may consume terminal capacity; admission then fails locally. Never evict terminal records or sacrifice required consumers to admit a pair. A malicious peer exhausting unavoidable protocol terminal records retains the mux's existing exact-session failure policy.

Within the existing 64 KiB outbound control DATA partition, protect directory 16 KiB, routing 1 KiB, and each owned relay control lane 4 KiB. Eight lanes use 32 KiB; all protected shares total 49 KiB, leaving 15 KiB common for required control writers. Relay cannot exceed its 4 KiB cap or borrow another lane's unused share. One maximum control message is 1048 bytes; three cost 3144, and a maximum route OK plus those three costs 3680 <= 4096. Slow control consumers backpressure only their owner; no unlimited queue is introduced. Native control, mapped-control and bulk scheduler bounds from the link contract remain intact. Rotating runnable control channels must service each eligible lane, including directory/route, rather than allow one relay to consume all mapped turns.

Mux already charges receive windows, outbound payload, pending setups, native controls and physical frame/parser staging to 6 MiB per link. This contract does not raise PeerMuxBytes, receive/outbound aggregates or fragment size. Required 19-channel steady occupancy needs at most 19 * 64 KiB = 1,245,184 receive bytes, within 2 MiB. Queued bulk retains the existing 2 MiB minus 64 KiB cap. The one physical frame in flight remains covered by the mux charge, not an extra pump allocation. The mux must prove the extended reservation metadata fits existing mux headroom with concrete layout tests before claiming the unchanged charge.

Relay adds a fixed reservation per global owner, including transit's two pairs:

Storage within one ownerConservative bytes
Two directional bulk buffers32,768
Two directional complete-control buffers2,096
Four bounded setup copies, plus request and response opaque storage4 * 827 + 2 * 512 = 4,332
Parser/response scratch for two incident controls2 * 1048 = 2,096
One caller-delivered control retained until consumption1,048
Metadata, immutable paths, pair handles, slots, wait sets and cancellation bookkeeping16,384
Total explicitly bounded bytes58,724
Reserved data per owner, including alignment/copy slack96 KiB
Reserved control per owner, including lifecycle metadata8 KiB

One 64 KiB process-global structural control allowance covers the fixed 32-slot allocator/index, neutral issuer/generation/incident-role metadata and bounded synchronization bookkeeping. It is package-global storage owned by relay/owner.go, initialized once before any relay runtime uses it and retained until process exit. Initialization creates no workers, timers or per-service registry. This is NOT a lease in an arbitrary service's Budget. No service is the sponsor, and stopping the first/last service neither releases nor resets the allocator, issuer or generations. Only vacated slots become available for later attempts. No attempt storage survives slot release; the fixed empty allocator remains. Generation exhaustion denies new issuance as local Limit without recycling identities or affecting already owned slots.

Service composition adds ResourceRelayMemory, count 32 and 3 MiB data, and ResourceRelayControl, count 32 and 256 KiB control, to EACH service's existing budget declarations. ReserveAttemptBudget atomically charges one count and 96 KiB data plus one count and 8 KiB control in that service before attempt allocation. Across service instances, the process-global 32-slot allocator limits the sum to 3 MiB data and 256 KiB service-charged control; independently, each service's smaller configured budgets can reject an attempt. A service releases only its own attempt leases after joins/settlement, before closing its budget. It cannot release the global fixed storage or another service's attempts. Add the separate 64 KiB structural allowance once for a total relay control bound of 320 KiB, not 320 KiB per service. No startup service-budget lease for that fixed allowance is created, transferred between services or released at service shutdown.

Pair/assembly references and incident metadata belong to each charged owner and the existing bounded peer/mux records, not an additional global per-link registry. Idle READY relay-claim metadata must fit the existing peer/mux charge and the mux layout proof. Tests must include two services sharing the slot pool, failure of either budget callback, and stopping one service while the other's owner remains live. They must demonstrate exactly one lease per local attempt, including a transit with two pairs, and reuse only after final settlement. Maximum new workers are 160 and timers 160. The existing dispatcher and route maintenance supervision are reused, not duplicated. Circuit owners reserve worker, retained-ciphertext and TLS budgets separately before allocation.

For one service at all 32 peer links, mux charges 192 MiB; routing adds 20 MiB data and 1,114,112 control bytes. If that service owns all 32 relay slots, relay adds 3 MiB data and 262,144 service-charged control bytes. These owners therefore charge 215 MiB data and 1,376,256 control bytes to its 512 MiB/16 MiB aggregate caps. Count the separate 65,536 structural bytes once in the process memory proof for 1,441,792 total control bytes attributable to those owners. For multiple services, mux/routing budgets remain per-service and their sums are not bounded by one service's caps; only relay slots and fixed relay metadata are process-wide. Other existing owners still compete for their own service's caps. This is a structural bound, not an RSS result or promise that all configured maxima fit simultaneously. Capacity rejection is supported. Concrete implementation layout, copy and worker tests must remain within these reservations; do not silently raise caps or add per-message/per-ticket workers to make the proof pass.

Hand-worked line and failure examples

Fixture labels A/B/C are roots ending in 01/02/03, endpoint ends in 11. The attempt is 000000000000000000000000000000a1. Opaque bytes cafe and response beef are transport-only test octets, not crypto, ACK or authentication bytes.

  1. A has candidate [A,B,C] on exact A-B link L1. It reserves both lanes at candidate validation, opens new.AB.control, then new.AB.bulk. B's OPEN_OKs prove local pair acceptance only. B matches suffix [B,C] on exact B-C L3, reserves and opens new.BC.control then new.BC.bulk. C validates its origin position/current endpoint and its handler accepts. C sends ok. B installs its immutable binding, forwards ok to A, and A publishes its attachment. Only now can circuit bootstrap/data/control proceed. control.sample is a bounded opaque message and authenticates nothing by itself.
  2. C has no origin handler, the endpoint is withdrawn before C admission, or the handler refuses. Both B-C lanes may have OPEN_OK. C emits error.denied.C, never ok. B forwards that unchanged, aborts outgoing/incoming pairs, joins and settles. A receives Denied, owns no attachment, and cannot claim TLS, ACL, AF_UNIX or application success. An error lost during reset is Transport, not success. No direct endpoint preparer is invoked.
  3. B captures exact [B,C], revision r on L3. Before ReservePair, C's candidate changes or L3 retires and L4 replaces it. Validation returns StaleCandidate, emits no OPEN on L4 and reports error.stale.B upstream. If L3 was admitted before retirement, its pair remains on L3 and then may terminate under peer drain. B cannot use a preferred alternative or rewrite A's path. Only A's later fresh attempt can choose another candidate.
  4. A remembers endpoint and C for a retained circuit while publication is withdrawn. It may attempt reattach.AB.control/reattach.AB.bulk over a valid current route, forwarded using the BC reattach literals. C has no live matching retained state. It returns error.denied.C; no endpoint socket is dialed and no old TLS stream is replaced. A continues to own recovery policy under circuit ownership; relay implements no timer or retry loop.
  5. C returns ok while A times out before receiving it. A sends/causes abort.cancel.A and RESET. B's rollback owner cancels both pairs; C's revocable offer aborts and joins its acquisition. Late OK cannot transfer ownership back to A or leak an origin attachment. All slots remain charged through settlement. Unrelated attachments and required consumers continue.

Validation and exclusions

The corpus contains actual bytes before any relay codec exists, with positive, negative and boundary cases. Check length arithmetic and association independently of a production encoder. Relay regressions cover fragmentation and coalescing, late acceptance, every commit-boundary cancellation, exact-link replacement, publication races, retained-state denial, both-lane FIN ordering, reset/transport loss, count pressure and concurrent required-control progress.

The relay implements the frozen structural/live-owner contract. Relay changed no dependency, SQLite schema, public/private JSONL, signed-record bytes, pairing behavior, stored route, address source or route UI, and froze no circuit transcript, ACK/HMAC encoding, retained state or recovery loop.

Current status: circuit bootstrap, fixed sessions, retained lifetime, authenticated single-attempt replacement, exact replay/live sequencing, entry-only lookup/retry/pacing and real signed/TLS service recovery topologies build on this transport, as do production endpoint consumers, remote availability and restricted routed pairing. The circuit contract describes the current composition boundary. The private contract is frozen in local control. Relay and service tests own transport and composed runtime regressions.

Retained acquisition contract

The circuit recovery design defines ModeReattach's circuit-owned opaque Setup, response and recovery controls. Relay setup, ROUTE_OK, ATTACHMENT_ABORT, RESET, lanes, finite limits and immutable metadata are unchanged. There is no new relay frame or circuit_closed notification. NewRecoveringOriginHandler implements this contract, with real relay admission/quarantine tests for internal consumers. Production installs the endpoint consumer; nil-consumer denial remains.

Before returning acceptance, OriginHandler.Admit must acquire an actual matching live retained circuit owner from a bounded registry. The authenticated 144-byte Setup selects the original session and binds the requested endpoint/entry/origin and full replacement path. It does not need an Attempt from the entry because Entry.Start generates that value internally. Later ATTACH controls bind the actual fresh Attempt, generation and both nonces. Admit cannot wait for Ready or send circuit traffic; its taken attachment and owner hold go into a revocable Acquisition which relay can Abort/Wait even if OK publication fails.

The earlier phrase "including the existing live endpoint connection" means the original retained byte edge and its owning lifecycle, not proof that inner TLS has completed or an application is open. Recovery before inner TLS completion is required. There is no new bootstrap, consumer call, TLS transplant, endpoint dial or local direct fallback. Missing/dead state denies before relay OK.

Ready releases only quarantine traffic. ATTACH_OK is a challenge, not proof of receipt or an installed live session. Only a valid ATTACH_CONFIRM allows origin to retire the old attachment. Authenticated snapshots, bounded replay completion and LIVE/LIVE_OK then release the new attachment's live bytes under the circuit owner's fixed deadlines. SendControl and physical writes never prove receipt. The relay sees opaque messages of at most 232 bytes, within its unchanged 1,024-byte control ceiling, and does not enforce these end-to-end phases.

Neighbor loss retires each affected binding. Forward existing ATTACHMENT_ABORT best effort toward surviving usable sides, then settle that immutable attempt. No local replacement suffix is selected. Delivery can be lost through RESET; circuit liveness must detect silence independently. A failure is scoped to the actual physical attachment/Attempt. Late old reports or RESET cannot terminate a replacement session. Failure is never authenticated FIN or application EOF.

Recovery separates acquisition Wait from shared terminal Session.Wait. Origin acquisition Wait joins only its attempt-local work. Its retained candidate hold stays charged until OriginSettlement, after relay joins and incident-pair settlement. Wait cannot join the shared session consumer or Attachment.Wait, since relay is joining it. Relay settlement and OriginSettlement remain per-attempt. The retained endpoint lease stays charged until terminal circuit work AND every incident attempt settle. At most old plus one candidate attachment can belong to a retained endpoint; candidate reuse waits for its worker/borrow/settlement joins. Relay charges and its 32-owner process ceiling do not change. The real service tests cover canceled publication after Offer.Take, competing candidates, retained consumer continuity, and an original acquisition's delayed relay callbacks and result arriving after authenticated replacement. The newer candidate hold and attachment survive while the old attempt settles exactly once. The circuit implementation and service recovery tests own these boundaries. The automatic line/diamond and delayed-cleanup tests consume these same unchanged relay APIs. The relay still reports failure best effort and never selects a replacement. The circuit's entry supervisor owns routing notifications, and its attachment token admits results only from the current physical attempt. Focused race selection follows the test policy.

Restricted pairing carrier

This is a separate Hub-targeted carrier. It does not use relay.EntryRequest, AHRA, OriginOffer, a circuit Session or endpoint publication. The reviewed contract is implemented in restrictedpairing, peer and routing, with service composition described below. Literal positives, negatives and state traces in internal/agenthub/testdata/carrier remain the parser and boundary test inputs. AHRA, mux framing, class values, approved bootstrap/data and pairingwire bytes stay unchanged.

The only endpoint of this carrier is a local dedicated pairing TLS accept owner for the exact target Hub. It accepts no ALPN besides ez-agent-hub-pairing/1, no endpoint ID, profile, socket, command, mux or arbitrary destination. It does not return a peer transport or a general Hub tunnel. Pairing activation grants eligibility under the existing ceremony; it cannot promote this carrier into normal peer TLS. Outbound routed normal-peer transport is outside this carrier.

Use one ClassBulk channel per incident link. Required AHDS/AHRT channels and relay pairs keep their existing budgets and dispatch owners. Do not call Manager.OpenChannel by relationship ID, create a dummy endpoint, acquire a PairOwnerCapability with fabricated endpoint metadata, or open a second peer Session. This carrier's byte/frame queues share the existing optional bulk mux allowances; it receives no new control DATA partition or mux limits.

The peer/routing owner adds these closed internal APIs alongside the existing route and relay claims:

  • ReadyLink.ClaimRestrictedPairing(ctx, routeLease, issuer, scope) returns an exact-link RestrictedPairingLease. Claim synchronously in READY before dispatch starts. The route lease must belong to the same Manager/Link and supply local/neighbor stable roots and authenticated heads. A process-local restricted owner issuer/scope is pinned once per manager, distinct from relay's pair issuer. Claim performs no channel I/O and grants no generic opener.
  • The sole peer.Manager.dispatch recognizes reserved AHRP prefixes and transfers undecided proposal references to that lease. Its inbox holds at most two references, within the existing eight mux pending OPENs. Unknown version, wrong class, full/unclaimed inbox or malformed shape rejects with existing OpenErrorRejected=1. It does not drain healthy required channels merely for a restricted-carrier rejection. Generic channel APIs reject all AHRP prefixes. No second Session.Next reader, copied setup backlog or network work in dispatch.
  • A RestrictedOwnerCapability is minted only by the carrier's 16-slot allocator after global slot AND service byte/count budget success. It binds issuer, service scope, generation, local position, nonce, target root/head and full path. Incident incoming/outgoing claims are each single-use. Cancel forbids admission immediately; Retire requires claim release and all user joins. Stale generations cannot release a later occupant. These are separate neutral types, not an extension that grants arbitrary PairOwner rights.
  • routing.Table.ReserveRestricted(ctx, candidate.Token, spec) invokes a typed peer restricted-admission adapter. The spec is value-owned, contains the owner capability, exact complete suffix, fixed setup and absolute local setup deadline. The table applies the same origin/path/revision/expiry/provenance validation used by ReservePair, under peer gate -> store identity barrier -> manager mutex -> table mutex. The peer checks issuer/scope, ownership, READY, required-channel commitment, eligibility and exact physical link. A successful ticket has one OpenAndTransfer(ctx) operation returning a managed channel. It never exports the mux Session or a root-based opener. The ten-second setup ticket transfers to the active exact-link channel hold, not an active ten-second route lifetime. Failure aborts/joins and releases the ticket.
  • RestrictedPairingLease.ReserveIncoming(ctx, proposal, spec) is the matching exact incoming-link operation. It validates local position/predecessor against the authenticated route lease and capability before Accept. A nonnil partial owner returned with error must be aborted/joined/released outside locks. No proposal can be settled by a lease for a replacement link with the same root.
  • Managed channels expose only bounded Read/Write/deadlines/CloseWrite, Abort, Done/Err and Release. Release seals new I/O, waits for in-flight calls to join and native Channel.Settled, then releases the exact Link.owned and channelWorkers hold and the capability claim. A single carrier supervisor owns incident channel settlement; no detached leasedChannel waiter. Late OPEN_OK after cancellation follows mux's existing RESET settlement.

Admission never dials. It may use only a currently authenticated eligible READY normal-peer link whose local/remote heads, request and roots still pass WithPeerConnectionIdentityBound. Removal, fork, manager stop or physical-link replacement closes that link's restricted admissions at the same barrier as routing/relay retirement. Byte progress does not refresh eligibility. Required startup traffic retains priority. Full carrier capacity rejects this attempt, not another leaf/link's work.

Exact setup bytes and target binding

The application OPEN setup is exactly 87 + 32n bytes; mux class 02 precedes it. Integers are unsigned big-endian; IDs are raw 32-byte identity.ID values.

OffsetBytesValue
0541 48 52 50 01, AHRP version 1
516Fresh nonzero random carrier nonce
2132Target stable authority genesis root
5332Exact target authority head ID chosen by the caller's identity checks
851Receiver position p, 1 through n-1
861Path count n, 2 through 8
8732nFull entry-to-target path of distinct nonzero stable roots

The minimum application setup is 151 bytes; maximum 343; full mux setup is 152..344. No suffix, padding, optional fields, mode switch, address, endpoint, application name, invitation selector, proof, Q, timeout timestamp, hop exporter or circuit ID is legal. Nonce is unique among active/settling owners, never reused for a fresh check. Target root must equal the last path root. Head need not equal root, but the target must verify its current local authority head matches before acceptance. Setup head/generation is no substitute for signed Context. Relays treat those public IDs as immutable routing constraints, not trust evidence.

At each receiver, local stable root must equal path[p] and authenticated incoming neighbor root must equal path[p-1]. A transit looks up target root and selects only a retained candidate whose COMPLETE path equals path[p..n-1]. Reserve that exact candidate and physical link. Forward identical nonce, target root/head, count and path, incrementing only receiver position. No replacement suffix, route retry, local endpoint lookup or target-head inference from a relay is permitted. Expired token is a failed attempt. A later pairing check gets a fresh route/nonce/TLS connection, never transparent replay.

At target, service compares setup root against local verified AuthorityLineage Trust.GenesisID and head against the fresh local TLS provider before OK. The actual end-to-end TLS client independently verifies the target again before joining-certificate, selector or proof disclosure. A relay may forge transport OK; it cannot authorize disclosure or assign a target generation. Entry keeps all independently supplied CandidateCheck values, not just the fingerprint.

Bounded carrier frames and state machine

Inside each ClassBulk channel, each application frame is U32BE body length followed by exactly one kind and its specified fields. No additional magic, negotiation, sequence number or extensible JSON exists. The frame limit is 16,389 bytes including the prefix; validate the length before allocation. A frame may cross mux DATA fragments; a mux DATA fragment is not a carrier frame.

KindBody lengthFields after kind
1 OK8116-byte nonce, 32-byte target root, 32-byte target head
2 FAIL2Code: 1 rejected, 2 limit, 3 timeout, 4 transport
3 TLS2..163851..16384 opaque pairing TLS bytes
4 FIN1None

There is no free-form failure text, detector position, invitation existence or partial acceptance result. FAIL is best effort, at most one, before OK; after OK reset the channel on terminal failure. Unknown codes/kinds, zero-length TLS, extra fields, trailing bytes, truncated body, oversize prefix or illegal state terminate this carrier only. Native malformed mux framing still has its existing link-fatal classification.

States are RESERVED -> WAIT_OK -> TLS -> DRAINING -> SETTLED, with abort from any state. A target may send exactly one OK once its bounded TLS accept owner and capacity are reserved. It does not wait for TLS ClientHello before OK. A transit reserves incoming, admits/opens downstream, and waits for downstream OK before forwarding that exact OK upstream. It validates nonce/root/head and rechecks both exact incident links and deadline before forwarding. It never fabricates OK on downstream OPEN_OK. Entry validates the same fields before returning its restricted net.Conn to hoptls.

Before OK travels upstream, only downstream-to-upstream OK or FAIL is legal; TLS in either direction or FIN is a protocol failure. After OK, only TLS and one FIN per direction are legal. A sender FIN follows all its admitted TLS frames, then native mux CloseWrite. The receiver requires FIN before native EOF and no later frame. Native EOF without FIN is truncation. FIN is carrier half-close, never approval, application EOF, peer eligibility or reliable circuit FIN. Drain both directions, join users, then native mux settlement. A blocked peer gets reset at the absolute lifetime deadline. Neither relay nor adapter interprets TLS application records. The target TLS role/engine rejects endpoint TLS, peer TLS, mux or arbitrary application bytes even when they fit these transport bounds.

The entry/target net.Conn adapter strips/emits TLS frames and implements local per-direction deadlines; deadlines never alter the shared peer syscall. One fixed receive staging area tracks partial frame/Read offsets, and one fixed send staging area splits writes into at most 16 KiB payloads. Use two fixed joined pumps and bounded API queues inside the reserved four 17 KiB slots. API deadlines apply to queue admission/delivery, with the same absolute, resettable, generation-checked timeout and accepted-prefix semantics as the Session adapter. The frame writer finishes every already-admitted complete frame after an API timeout; an unaccepted caller suffix is never sent later. A deadline must not leave a half-written frame followed by a new prefix. The native mux write deadline is capped by carrier lifetime/caller terminal cancellation, not replaced by an API queue deadline. Write success means bounded frame admission, not physical delivery. Write continues bounded admission until all input is accepted or returns the accepted prefix with a nonnil error; it never returns (n < len(p), nil). No goroutine per call.

Close is the idempotent, joined graceful full-close path used by ordinary pairing TLS completion. It seals API writes, drains every admitted TLS frame including queued close_notify, emits one carrier FIN, then invokes native mux CloseWrite. CloseWrite alone seals only that direction and leaves reads live. Full Close wakes API reads with net.ErrClosed and uses the fixed receive pump to drain/discard unread TLS frames until the peer's FIN/native EOF. It does not interpret close_notify or grant another target. Concurrent/repeated Close calls join the same completion and do not send another FIN. Raw Close joins its pumps, admitted raw API calls and native channel settlement, but NEVER the pairing-engine invocation that is calling TLS Close. It marks the raw edge joined and returns. The carrier supervisor subsequently joins that engine user and releases exact-link claims/holds/budgets. The raw edge does not call a supervisor Wait that depends on itself. API write deadlines do not abandon admitted frames during graceful close.

DRAINING retains the absolute 300-second lifetime from first reservation, plus any earlier caller or pairing deadline. It has no renewed setup deadline and no fresh close allowance. At expiry, cancellation, truncation or terminal failure, Abort() error is the idempotent nonwaiting path: reset both incident channels, wake every blocked I/O, and release nothing. Close/Wait then join and return the failed outcome. Native settlement keeps its existing mux bound and charge after a reset. It is not ordinary graceful completion. Preserve the terminal context through a normal engine/TLS Close so a completed ceremony's cleanup does not itself discard admitted output. Keep cancellation watchers active to abort a genuinely canceled caller during that drain.

The pairing engine owns ordinary TLS close and exact request state. Its normal join/serve defers call TLS Close today; the raw adapter must therefore use this graceful Close path. Composition's cancellation/failure actions use the narrow Abort capability documented in the link contract, not an ordinary Close that could block until lifetime expiry. Carrier failure is an interrupted ceremony, not authority to retry an operation. Neither close path promotes this carrier.

Deadlines, bytes, counts and settlement

These are hard local ceilings, not advertised negotiation values:

ResourceLimit
Active or settling owners across service instances in one process16
Active or settling restricted channels on one exact physical link4
Undecided restricted proposals per exact link2, within mux's 8 pending OPENs
Incident links per owner2 at transit, 1 at entry/target
Workers per owner5, including supervisor, pumps and cancellation bridge
Reusable timers per owner3, setup/lifetime and two directional API deadlines
Setup deadline10 seconds absolute from local first reservation/proposal
Whole carrier lifetime300 seconds absolute from local first reservation/proposal
Cumulative TLS payload per direction1,048,576 bytes
TLS frames per direction4,096
Control frames per carrierOne OK OR one FAIL, and at most two FIN
DATA budget per owner128 KiB fixed working storage
Control budget per owner16 KiB metadata/queues/worker and timer bookkeeping

Use a single supervisor timer for the earliest active phase bound. In WAIT_OK, that is setup/lifetime/caller. Once the validated OK commits the local transition to TLS, disable the setup bound and reset that same timer to the ORIGINAL lifetime/caller bound. This does not reset the lifetime anchor. TLS and DRAINING never compare payload progress against an expired setup deadline. Setups, frames, idle periods and route refresh never extend any bound. Every local transition samples monotonic time; equality expires before admission. Entry's single ten-second establishment context bounds the entire path, not ten seconds per hop from the caller's perspective. Target does not inherit an untrusted wire timestamp. On entry timeout/cancellation reset propagates incident cleanup; each other owner still has its own absolute ceilings. Existing pairing engine handshake, frame, five-minute initial-connection, approval cutoff and retention deadlines may be earlier and always win. The carrier may interrupt a ceremony; it never extends a ceremony deadline or schedules a later attempt.

Before copying a TLS frame, charge its complete payload and count against the direction's counters with overflow-safe subtraction. Before writing, charge once at admission; partial delivery does not double-count or refund lifetime quota. Transit counts each forwarded direction once, not once per incident link. The maximum framed TLS bytes in one direction are 1,048,576 + 5*4,096 = 1,069,056; add one 85-byte OK on the reverse direction and one five-byte FIN per direction. Counter exhaustion resets, never allocates more storage. One maximum frame is 16,389 bytes. Four fixed 17 KiB frame/staging slots and bounded metadata fit the 128 KiB DATA reservation with room for partial writes; no additional pipeline or detached retained-frame copy is allowed. Across sixteen owners that is 2 MiB DATA and 256 KiB control, at most 80 workers and 48 timers. Each mux's receive credit, send queue, pending setup, terminal RESET and physical in-flight storage remain separately pre-reserved and counted; this figure does not include or increase them. No peer-wide high-capacity gate is implied by these structural ceilings.

All phases, including blocked FAIL/OK, cancellation before/after OPEN_OK, held administrator decisions and late native settlement, retain the owner's charges. Abort seals admissions and resets both incident channels. Join supervisor, TLS/engine user, pumps and borrowed frame users before releasing native channels, link holds, capability claims, then service budgets and global slot. Do not hold peer/store/table locks during a join. An unanswered mux terminal barrier retains its exact-link hold until native settlement or link failure under the existing mux deadline. An old reset/result cannot release or reset a replacement link, nonce, capability generation or unrelated carrier.

Restricted carrier implementation

restrictedpairing.Setup is the single entry/transit/target supervisor. Entry mints a nonce and captures one complete candidate; transit requires the exact retained suffix and forwards the same target OK. Target rechecks its verified local genesis and fresh pairing credential head and reserves pairing TLS and scheduler capacity before OK. None of these route checks grants trust.

The separate process-global 16-slot allocator issues neutral restricted-owner capabilities only after service budget success. Each exact link permits four restricted reservations/channels. READY claims and AHRP dispatch share the existing sole peer dispatcher; generic openers cannot open AHRP. Incoming rollback and late OPEN_OK retain native settlement references. Removal, fork, replacement and shutdown retire only the original link's admissions and holds.

The raw net.Conn adapter has four fixed TLS frame slots, two joined pumps, serialized per-direction API calls and reusable directional deadline timers. An API timeout reports the accepted write prefix without admitting its suffix. It never changes the shared peer socket deadline or splits an admitted frame. Each direction enforces the frozen 1 MiB/4096-frame quota. One supervisor timer bounds local setup to ten seconds, then retains the original 300-second lifetime or earlier caller deadline. READY retires setup expiry, not the lifetime bound. Cancellation is checked directly at API and native payload admission as well as by the joined watcher.

CloseWrite drains admitted output before carrier FIN and native half-close. Close joins raw API calls, pumps and native settlement but deliberately does not join the engine calling it. Entry's outer engine owner calls Release after that engine returns. Target's supervisor joins Serve before releasing its reservation. Abort interrupts immediately without releasing capacity. Stop joins every owner, including the explicit entry-user release boundary. The 128 KiB data and 16 KiB control charges remain held through these joins.

Restricted-pairing and service tests separate literal/owner proofs from real service TLS and ceremony proofs. This carrier has no recovery session, endpoint consumer, arbitrary destination or normal-peer promotion. A later exact pairing check acquires a new carrier and fresh TLS.

Restricted pairing quota principal

Restricted pairing target admission carries the authenticated immediate incoming READY neighbor as local Request.IngressRoot evidence. The caller cannot supply that principal through setup bytes. A valid immediate predecessor does not prove earlier path membership or the claimed entry in Path.Roots[0]. Pre-TLS pairing connection and handshake quotas, and retained scheduler entry accounting, use this verified ingress neighbor. They do not consume a claimed victim's quota or permit fabricated-prefix rotation to evade ingress limits. Both reservations precede target credential work and remain charged until their joined owners retire. This accounting is separate from the endpoint circuit's authenticated entry/session binding and adds no wire field or trust grant.