docs/internal/agenthub-relay-implementation.md

AgentHub relay implementation and circuit handoff

Current capacities and allocation/release interfaces are owned by the production capacity map. Older fixture-profile memory/cardinality proofs below describe those profiles only; they are not evidence of the maximum targets. Frozen circuit wire-direction budgets, codecs and ACK/recovery ordering remain unchanged.

The relay implements the transport defined by the frozen relay contract and its 67 independent literals. This page describes implementation ownership without changing those bytes or semantics. Routing is its input. Admission work follows owner acquisition; custom-context propagation and budget callbacks retain joined cancellation ownership. Circuit status and recovery are in the circuit status and the service recovery tests. Circuit authentication and remote application access remain outside the relay transport.

Composed transport evidence

Admission and cancellation ownership

Fresh entry and incoming attempts reserve the process owner slot and service budget before endpoint capture or route lookup. Only bounded syntax, exact-hop and duplicate classification precede incoming reservation. Nil new-mode directory remains a local composition denial before ownership. Existing-key malformed or duplicate proposals still poison their original assembly without another owner. Unknown endpoints are charged, denied and promptly released after watcher join. Transit retains one owner for both pairs. The directory/route guarded commit keeps the existing peer gate, store barrier, manager, directory, table lock order.

Directory selection is now a fixed-capacity, endpoint-ID-sorted index. Both SetLocal and peer snapshot Install build and reserve the candidate index before atomically publishing it with selected state and forwarding catalog. Replays do not replace it; failed construction/cancellation leaves the old index and state intact; Close clears and releases it. Full selected tuples, local publication pinning, lineage projection and conflict quarantine remain required. Capture and commit recheck allocate nothing and use at most eleven binary-search comparisons, even for a miss in the full 1,024-endpoint directory. No query adds negative-cache entries. Each array reserves 217,088 bytes on amd64, including 4 KiB metadata/rounding; construction separately reserves 1 MiB scratch. Replacement charges both generations. These use actual directory leases within unchanged service caps, not relay headroom or an uncharged map.

Relay cancellation derivations use detached standard parents, with caller deadline, values and synchronous Err preserved. The existing charged setup watcher observes original Done throughout semantic capture and paired commit, then joins before owner release or supervisor handoff. Assembly uses that same watcher role before the setup reader starts. Established supervisors observe original Done and service stop themselves. No custom-context propagation worker, per-link watcher or new worker allowance is added. Start caller cancellation still aborts after success, and Stop/Wait joins those entry lifecycles.

Before budget success, no watcher may start to bridge detached Done. The synchronous budget callback therefore receives the actual caller context, including its original Done, deadline and values. It still must perform bounded local reservation. Local stop and setup expiry are checked before and after callback return; late partial success is closed before storage/capability construction. No worker starts on budget failure. Ordinary and custom-context tests cancel while that callback waits on its received Done, at both entry and incoming boundaries. Separate late-success tests cover local Stop and setup expiry. The callback's Done is the caller's, not a merged local stop/expiry signal, which is acceptable only for bounded synchronous local work.

Durable directory, relay and peer regressions cover full-directory unknown queries, allocation-free manager-lock rechecks, index-reservation rollback, cancellable capture/commit lock waits, manager progress after cancellation, owner/budget precedence and custom contexts without AfterFunc. The custom-context test records propagation-worker call stacks rather than global goroutine counts. These regressions live with directory, relay and peer.

Existing transport evidence

service.TestServiceRelayAcceptanceTLSDiamondImmutableSnapshots uses signed stores, normal TCP/TLS peers and the production mux on two unequal diamond arms. The first attachment stays on A-B-E-D after A-C-D becomes preferred. A later attempt gets a fresh ID and the new snapshot. Both paths carry duplex bulk and opaque controls; resetting the old branch leaves the new branch usable.

The real A-B-C line tests cover loss of the transit suffix while entry still has its old snapshot, same-root service restart with a replacement physical link, and rejection of old entry and transit tokens. A captured entry candidate that disappears returns StaleCandidate even when no alternative remains. A transit with no matching requested suffix returns NoRoute. No attempt substitutes a suffix, retries or resolves a replacement link by root. Best-effort errors can be lost to RESET; lower-level RESET-gated tests prove the exact failure frames.

Eight concurrent line attachments consume eight pairs per link and 24 local owners across three services. A ninth pair returns Limit without damaging the existing eight. An unread bulk stream backpressures its own binding while its control lane, unrelated duplex streams and signed publication withdrawal and republishing continue. Withdrawal alone does not revoke an admitted attachment. Origin abort wakes blocked reads and writes with abortive errors. Capacity is reusable only after all three local owners join.

Clean line FIN tests drain 256 KiB in each direction before EOF, deliver trailing controls, and join both endpoint attachments and the origin acquisition. RESET, cancellation, removal and verified authority fork are never clean EOF. Service shutdown is covered at entry, transit and origin, including a still-pending cancellation-responsive origin callback. Lower-level tests cover every OPEN/admission/publication race, late acceptance, malformed association, frame truncation, directional abort propagation and settlement-held rollback.

Entry-local setup cancellation and timeout retain a usable downstream control lane for one bounded ATTACHMENT_ABORT write and physical flush before RESET. The real-mux TestSetupEntryLocalFailureEmitsAbortBeforeReset pauses complete downstream OK before entry publication and checks the frozen abort.cancel.A bytes with only the random attempt substituted. Timeout changes its failure code to Timeout and preserves position zero. Received downstream errors/aborts are not echoed. Exhausted control credit or an already failed/untransferred lane can still force the bounded RESET fallback; notification is best-effort. Ownership remains charged until both lanes settle.

New-mode setup with a nil directory returns local-only Invalid before reserving an owner or pair. Entry emits no OPEN. Incoming dispatch rejects the sender's OPEN with no OPEN_OK or relay response, without allocating an assembly. Nil directory remains supported for reattach, which fabricates no publication evidence.

These controls are synthetic opaque octets. They prove lane placement and bounded scheduling/pressure isolation, not fixed-session ACK authentication. mux.TestPairRequiredRepairRefreshAndWithdrawalProgress provides continuous runnable-control and route refresh/withdrawal scheduling evidence. The composed service test proves signed directory and relay-control progress under stalled bulk; it does not claim to force route refresh intervals or delivery through a stalled socket.

Resource evidence and accepted accounting standard

The production limits remain 32 process-wide local owners, eight incident pairs and three opening assemblies per exact link, six proposal references, one supervisor plus at most four pumps, and at most five relay timers per owner. Each owner retains its 96 KiB data and 8 KiB control lease through termination, borrowed-control release, worker/acquisition joins and both incident settlements. The fixed pool/issuer has a separate 64 KiB process-lifetime allowance. Incoming setup is decoded once in charged per-link scratch, not cloned into a backlog. The mux proof is 5,313,176 bytes within the unchanged 6 MiB charge, including an explicit 8 KiB dispatch/parser allowance.

Service PeerMuxBytes is an alias of mux.PeerMemoryReservationBytes, so the production reservation and mux proof use the same charge. Aggregate and per-key caps are unchanged.

Integration removed unused setup arrays and duplicate transit bulk buffers. attemptStorage is now 38,008 value bytes; the combined setup/binding value inventory is 44,128 bytes. These are value layouts, not complete runtime totals. The Go 1.25 amd64 allocation ledger includes rounded objects, contexts and child maps, channels, timer records, goroutine records, wait records, closures and errors. The corrected ledger includes twelve context objects and twenty-eight select/wait records. Its non-stack model is 79,360 bytes per owner, leaving 27,136 bytes for all five stacks. Rounded fixed pool/issuer inventory is 51,488 bytes within 65,536. Private-runtime layout checks and allocation-site guards require review when the implementation or toolchain changes; they do not prove a heap ceiling.

relay.TestRelayRuntimeMaxOwnersAndLinkPressure runs 32 transit owners and 64 incident pairs over real mux links, both packed at eight pairs per link and spread across 32 local links. It observes 160 workers, duplex traffic and required stream progress, then holds settlement through mixed active/terminating and all-terminating phases. The 33rd owner is rejected before its budget callback. TestRelayRuntimeMaxSetupOwners observes 96 setup workers and holds all 32 rollback owners charged until final settlement. Lease and pair release are exactly once; old releases cannot affect refilled generations.

The frozen contract uses a structural bound: concrete storage/copy layouts and bounded owner/worker/timer/settlement evidence. The mux proof uses the same live-owner standard and excludes allocator arenas, unreclaimed GC garbage and caller-retained retired handles. Neither proof is an absolute process RSS or total Go-runtime allocation ceiling.

Heap/stack snapshots after GC are diagnostics only. Go permits dynamic stack growth, and the synchronous origin callback runs on the relay supervisor with no stack-depth limit in its contract. Five 4 KiB stacks fit the ledger model; five 8 KiB stacks exceed the combined charge by 13.5 KiB. Timer callback overlap, compiler escapes, allocator arenas and unreclaimed garbage cannot be bounded by these tests. More measurements cannot establish a hard total-runtime ceiling under the current API.

The runtime ledger supports the accepted structural proof. A hard total Go-runtime ceiling would require a separate reviewed contract/design change; measurements alone cannot establish it. No caps or frozen ownership semantics were changed, and circuit owners must separately charge their own workers, TLS, ciphertext and retained recovery state.

Stable API for circuit and later consumers

Circuit owners use relay.Entry.Start(ctx, EntryRequest) with one immutable candidate, endpoint, mode and at most 512 opaque setup bytes. It returns only following complete route OK. The context remains the lifecycle parent after success. service.startRelay is package-internal; there is no gateway, admin, debug or JSONL entry point. The relay installs a fail-closed origin handler until a consumer is supplied. Missing origin handling or a nil circuit consumer denies rather than opening a local endpoint.

Attachment.Metadata() is a value containing attempt, endpoint, full path, mode and stable origin. ReadyAt() records local Ready publication with its monotonic component, is zero beforehand and never changes afterward. Circuit bootstrap uses this timestamp for its original absolute deadline even if its worker starts late. It adds one charged time value, no wire field, worker or timer; the older layout figures above describe that earlier source. Response() returns a bounded opaque value. Bulk() is a bounded duplex byte stream. Control uses SendControl and ReceiveControl with whole 1 through 1024-byte messages. Release the one borrowed ControlMessage before receiving another; storage remains charged until release. Released invalid wrappers do not retain the binding. Input to SendControl may be reused after it returns. There is FIFO ordering within each direction/lane, no cross-lane ordering promise and no payload authentication by relay.

Bulk CloseWrite drains that direction. CloseWriteControl is legal locally only after bulk CloseWrite and orders accepted controls before its FIN. Reverse bulk and controls continue. Done and Err report the terminal cause; Abort is idempotent and abortive, and Wait joins settlement. Circuit owners keep the handle until Wait. Attachment EOF is not authenticated circuit/application EOF.

Established parser, frame-completion deadline and local I/O failures report the binding's detecting path position in both Err and Wait. Received ATTACHMENT_ABORT retains its original code and position. The transit-B and origin-C cases in relay.TestBindingEstablishedFailurePositions cover both paths, including a received position-zero abort and exactly-once release.

OriginHandler.Admit runs synchronously outside admission locks and must return promptly on cancellation. The offer is borrowed for that call only; TakeAttachment transfers a single revocable, Ready-gated handle to the returned acquisition. Return either fully unwound zero acceptance or an abortable/joinable acquisition and at most 512 response bytes. Acquisition Wait must not wait for the relay supervisor or Attachment.Wait. Ready allows quarantined bootstrap, not resumed endpoint traffic. New requires current conflict-free publication; reattach creates no publication evidence and grants no authorization.

Errors returned by origin Admit or acquisition Wait are local callback failures. Relay keeps an allowed code and typed routing cause, but stamps the origin's position. Unknown callback codes become local-only Invalid and are not encoded. Received ROUTE_ERROR and ATTACHMENT_ABORT retain their remote code and position. The RESET-gated A-B-C callback regression checks position-zero Denied and Limit, an out-of-range callback position, and a contrasting received position-zero failure. Acquisition-Wait and invalid-code tests check joined release and no invalid wire response.

Admission lock order remains peer gate, store identity barrier, manager, directory admission, routing table. Pool/budget operations, role synchronization, origin callbacks, I/O and joins occur outside those locks. A transit owns one capability and lease for both pairs. Route preferences change future attempts only; link removal/fork/drain can terminate the fixed links.

At the peer paired-admission barrier, an uncertain/unavailable trust store still notifies the fatal service owner with the original store.ErrUncertain. Relay receives typed routing Transport, not an endpoint Denied. Cancellation already present before notification keeps its Closed/Cancelled mapping; cancellation caused by the fatal notification does not replace Transport. Exact-link retirement remains StaleCandidate and directory admission refusal remains Denied. Peer and managed-relay regressions check no commit/OPEN_OK, no outgoing OPEN, original fatal notification and released claims, tickets, holds and owner charges.

  • Circuit bootstrap owns temporary entry-to-origin circuit TLS bootstrap, endpoint/attempt/ version/limit/nonce binding, exporter-derived material, and the exact TLS-to-segment transition with buffered read-ahead ownership. Bootstrap authentication stays above the attachment, not inside relay.
  • The fixed session consumes that authenticated framing handoff and owns reliable ciphertext queues with separately charged buffers, authenticated ACK/control bytes, liveness and close. Relay's trusted immediate peer and attempt ID are insufficient. Bootstrap authentication must precede the reliable session.
  • Recovery owns live retained endpoint state, authenticated reattachment, ciphertext retention, fresh-candidate selection and recovery timing. Do not recreate an endpoint socket or TLS session. Authenticate before paused bytes resume; publication withdrawal alone neither authorizes nor forbids attempts.
  • Remote gateway selection is enabled only by the production endpoint composition of those owners; direct endpoint preparation is unchanged.

See focused-check policy for validation selection and the service tests for composed behavior.

Circuit origin settlement composition

Acquisitions may implement optional OriginSettlement.ReleaseAfterSettlement(). The relay supervisor invokes it exactly once after acquisition.Wait, pumps, local I/O users, borrowed-control release, and both incident lane settlements and pair release. Binding rollback uses the same terminal run path. Empty/partial setup rollback invokes it after its acquisition and partial pairs join. The callback precedes release of the relay attempt charge and must do only bounded local idempotent release, with no I/O, waiting, worker or relay reentry.

TestOriginSettlementAllTerminalPathsAfterBothLanesAndAcquisition covers clean established FIN, established abort, failed OK publication and partial/empty rollback with real mux lanes. Existing acquisitions without the optional method are unchanged. Origin circuit Wait never calls Attachment.Wait; entry circuit Wait synchronously joins it. Service holds its endpoint lease until circuit work and this settlement gate have both completed. Without a circuit consumer the installed fail-closed handler denies new and reattach.

An additional ownership-test correction runs the settlement terminal-path matrix with standard and custom parents, including failed OK publication. It asserts typed cancellation and cached repeated/concurrent Wait outcomes instead of discarding them. The custom parent checks for hidden propagation workers. Composed origin shutdown tests additionally hold a real borrowed control message while acquisition/circuit Wait completes, then verify the service remains charged and Close remains blocked until relay settlement joins. These are added evidence, not production changes or a new transport. Failed publication remains the same real-mux component boundary; no service TCP forced-write fault is claimed.

Fixed session handoff

An authorized review correction adds two internal Go methods without changing relay frames, wire lifecycle, public EzAgent or private ezhubapi JSONL. Attachment.TrySendTerminalControlAndAbort(ctx, payload) validates context and 1 through 1024 opaque bytes, samples lane liveness, and requires a published, non-transit, non-closing, non-terminal endpoint. It makes one nonwaiting receive of the existing send permit under the binding lock. On success it copies into the existing charged control buffer, seals the binding's abort state and returns. The caller must Abort on failure. It never waits for Ready, slot capacity or physical delivery. The existing sole relay writer sends this opaque control, then the unchanged ATTACHMENT_ABORT, and flushes under one shared existing abortForwardTimeout, one second, before ordered mux RESET. No second buffer, transport, worker or timer is added. Busy ordinary slots fall back immediately; an admitted terminal payload on a physically stalled lane still uses the existing forwarding deadline and settlement bounds. Copy admission does not guarantee physical delivery or remote consumption. Tests gate physical RESET only while observing exact delivered bytes, because mux RESET still discards queued DATA.

CloseWriteControlContext(ctx) has the existing bulk-close precondition and FIN ordering, but cancellation wakes a close waiting behind the sole writer. CloseWriteControl() remains its Background-context compatibility wrapper. Neither close cancellation nor terminal opaque payload introduces a new wire meaning or authenticates application EOF. All I/O and owner cancellation remain outside the binding lock; frame projection/copy and permit admission are bounded local operations under it. Existing acquisition, pump, user, borrow and incident settlement joins retain the same single relay owner/charge.

circuit.NewSessionStarter and Start now consume the real bootstrap input, including its private settlement-role anchor. Session uses one control reader and writer above whole-message SendControl/ReceiveControl, always releases a borrow before state application, and uses independent bulk workers. Cumulative ACKs authenticate receive acceptance, not execution. FIN/final ACK/FIN_ACK prove circuit half-close; relay lane EOF or RESET cannot substitute. Entry joins its local attachment settlement; origin returns from circuit Wait so relay can join its acquisition without a cycle. Capacity reuse still needs both gates.

The fixed-session service evidence adds signed/TLS one-relay and two-relay 32 MiB duplex transfers, actual ACK wire/MAC capture, RX backpressure with reverse controls, signed directory updates and an unrelated real session on shared mux links. Unequal-diamond route advertisements change preference while the old session's full path/attempt remains fixed. Local removal, verified fork, transit socket loss through shutdown and exact physical replacement terminate it. No TCP forced-write fault or recovery is claimed. Settlement probes distinguish local entry completion from origin acquisition settlement; remote settlement is not an entry-local gate. Component settlement and borrowed-control tests remain separate evidence owners.

Resource charges remain separate: 96 KiB/8 KiB relay per local attempt, 13 MiB/ 64 KiB per circuit endpoint and 4 MiB proof, within unchanged aggregate service caps. The eight circuit workers include six session workers and two surrounding acquisition/invocation owners; no relay worker or settlement waiter is hidden in that count. Retained recovery implements attachment-only retirement and retained-state recovery, and production endpoint consumers provide remote availability. Relay itself still opens no endpoint socket.