docs/internal/agenthub-routing.md
AgentHub routing contract
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.
Routing is implemented in the composed Hub service. Literal fixtures are the byte authority for examples; this page owns semantics. Routing and relay preserve EzAgent JSONL, private EzHub JSONL, peer TLS, directory bytes and signed records.
Integration status
Production routing composition is implemented.
peers.Ready = s.startPeerSync reserves and
claims both required consumers, binds the exact route contribution, and activates
admission before scheduling either setup worker. One joined table maintenance
owner and live route engines serve the internal stable-root lookup. The peer
owner now synchronously invalidates the bound table at physical retirement.
The engine supervisor also owns admission maintenance, and route channel holds
release explicitly after worker joins and settlement. There is no additional
admission or route-settlement worker.
Real signed-store/TCP/TLS/mux service tests cover line and diamond initial exchange, exact selected paths, bounded alternatives, live selected-only split horizon and withdrawal, replacement END gating, stale L1 rejection, reversed head/root opener order, required-stream failure retiring its directory sibling, remote endpoint unavailability, unknown-root isolation, rollback and joined charges. The renewed composition proof fits 20 MiB data, 1,114,112 control bytes, 129 new workers and 161 timers without raising caps. Component-only or manually installed routes are not the topology evidence.
See test ownership, link dispatch, service composition and directory origin identity. The relay paired-lane contract and independent fixtures extend this boundary.
Owners and inputs
routing owns current RAM candidates, selection, export and immutable lookup.
peer owns the existing normal-link registry, exact-link admission, dispatch,
drain and joined lease release. service supplies stable roots, reserves
resources and composes the workers. Routing never dials, learns addresses,
creates trust, persists state or owns attachments. Relay owns setup;
circuits and recovery own reliable bytes. Remote gateway rows are available only
when the production endpoint composition supplies a selectable carrier.
Read the actual baseline owners in peer/channels.go, peer/manager.go,
mux/class.go, mux/config.go, service/budget.go,
service/directory_sync.go, peersync/channels.go, directory/learned.go
and store/projections.go before implementing this page.
A root is the 32-byte identity.ID of a verified stable authority genesis.
The service reads local AuthorityLineage().Trust.GenesisID, failing closed
if missing or inconsistent with verified lineage. HubStore.Root() is a
filesystem path, not this identity. Neighbor root is the admitted relationship's
verified genesis, currently ReadyLink.Genesis(). ReadyLink.Local() and
Remote() are authenticated heads, not roots. Supply both roots and both heads
explicitly on the new route claim. Successor heads and operational certificate
renewal never rename a route root. A directory endpoint's verified OriginRoot,
not Origin or contributor, is the lookup key. Unknown advertised origins use
route capacity but create no directory identity or trust decision.
File ownership is explicit:
| Owner | Files and decisions |
|---|---|
| Contract | This page and internal/agenthub/testdata/routing/ |
| Peer channels | peer/channels.go, dispatch and directory migration; preserve AHDS\x01 and head-based directory opener |
| Exact-link claim | Exact-link route claim and reservation types in peer, lifecycle barriers and regressions |
| Codec | routing/codec.go, bounded wire I/O and codec tests. Wire-only message types live here. |
| Table and types | Sole editor of routing/types.go, including public snapshots, tokens, errors and clock types; table.go and selection. Publish the shared declarations before the codec compiles. The codec must not create a competing shared type file. |
| Engine and service integration | Route runtime and composition, including reservations and mux sharing required below |
The codec may use identity.ID directly. It must not import peer or service.
The table does not import directory, gateway or circuit. No nil validator,
accept-all origin callback or relationship-ID fallback is an admissible default.
Channel setup and dispatch
Exactly one duplex route-control channel is claimed on each selected READY physical normal-peer link. The claim is separate from the directory claim and is consumed even if setup fails. Claim both synchronously on the same READY capability before scheduling either worker. Claims perform no channel I/O. Failure to obtain required capacity drains that exact link; do not leave a selected directory-only link indefinitely.
The side with the lexicographically smaller unsigned root opens. Equal roots are invalid normal routing neighbors and fail closed. Head ordering still chooses mux parity and the directory opener. Those orders may disagree with the route opener, including after head succession.
The application setup is exactly five bytes 41 48 52 54 01, or AHRT\x01.
The immutable peer class is ClassControl = 01. Thus the mux OPEN setup field
is exactly 01 41 48 52 54 01, six bytes, including its class byte. No suffix,
other class, second route channel, other version or non-designated opener is
valid. This page does not change mux OPEN framing, channel IDs, class bytes,
AHDS\x01, or directory control-then-bulk ordering.
One exact-link dispatcher alone consumes Session.Next. It recognizes reserved
identifiers and hands undecided proposal references to typed inboxes. Route
inbox capacity is one; directory capacity is two. All references remain part
of the existing eight pending OPENs and decision deadlines, not another
pending allowance or copied setup backlog. Unknown identifiers and wrong
classes get existing mux OpenErrorRejected = 1. Duplicate or wrong-opener
route proposals also reject and terminate that link's route owner. Full,
unclaimed or abandoned inboxes reject; failure of a required claimed consumer
then drains its link. Directory workers must never consume route proposals or
vice versa. Reserved identifiers cannot be opened through relationship-bound
generic channel APIs. Dispatch does not inspect route DATA.
Encoding
All integers are unsigned big-endian. Roots are raw 32-byte IDs, not text,
SPKI, certificates or addresses. Zero roots are invalid. No padding, extension,
optional field or trailing byte is legal. Each frame is a four-byte body length
followed by a one-byte version 01, a one-byte kind and the fields below. The
length excludes its own four bytes. Frames concatenate in the byte stream;
mux DATA boundaries have no meaning here.
| Kind | Byte | Fields after version and kind | Body bytes | Total bytes |
|---|---|---|---|---|
SYNC_BEGIN | 01 | sync ID u64, entry count u16 | 12 | 16 |
SYNC_ENTRY | 02 | sync ID u64, zero-based index u16, path | 13 + 32n | 17 + 32n |
SYNC_END | 03 | sync ID u64, entry count u16 | 12 | 16 |
ROUTE_SET | 04 | update ID u64, path | 11 + 32n | 15 + 32n |
ROUTE_WITHDRAW | 05 | update ID u64, origin root | 42 | 46 |
A path is a one-byte root count n followed by n roots. Wire n is 1 through
7. Maximum body is 237 bytes and maximum complete frame is 241 bytes. Enforce
kind-specific exact lengths, not just the global bound. Reserve a fixed parser
buffer before reading; a hostile length cannot cause a proportional allocation.
Unknown kinds or versions, bad arithmetic, oversized lengths, truncation or
extra fields terminate route control. There is no route ERROR frame. Existing
mux RESET is abortive, not a new route error-number namespace.
Path representations
A received path is origin first and authenticated immediate sender last. It
never contains the receiver. All roots are unique. Origin is the first root;
ROUTE_SET has no redundant origin field. Validate the sender against the
route claim's neighbor genesis, not the authenticated head. Reject local-root
inclusion, sender mismatch, zero roots, duplicates or more than seven incoming
roots. These are terminal protocol failures, not silently skipped routes.
The candidate retains this received path. The local full path appends the
receiver once, so it has at most eight Hubs. Entry-to-origin setup order is
exactly its reversal. For example, C advertises [C] to B, B retains [C],
forms [C,B], and advertises that to A. A retains [C,B], forms [C,B,A],
and a future attachment uses [A,B,C]. Count Hubs, not edges. A seven-root
received path is valid locally but its eight-root full path cannot be exported
to another neighbor because that would require nine Hubs. The self-route is
[localRoot], has zero edges, and has no next-hop admission token.
For each destination neighbor, export the selected local full path only if it has at most seven roots and does not contain that destination root. This is split horizon. Do not export an alternative merely because the selected path is ineligible for that neighbor. If a previously exported origin becomes ineligible or disappears, send a withdrawal. Always export the local self-route. There is no inferred direct candidate before a neighbor's initial export commits.
Synchronization and counters
Each direction on each physical link owns independent state. Sync IDs and update IDs are also independent of each other, directory IDs, mux channel IDs, store revisions and internal candidate revisions.
There is one initial export and no resnapshot protocol. Sync ID is exactly 1
on a fresh link. The sender captures one immutable split-horizon export,
sorted by ascending raw origin bytes, with 1 through 257 entries. It writes
SYNC_BEGIN(1,count), every SYNC_ENTRY(1,index,path) with consecutive indexes
0 through count-1, then SYNC_END(1,count). Include exactly one sender self-route
[senderRoot]. The same origin cannot occur twice. Receiver checks ordering,
count, indexes, roots and exact self-route. END must repeat BEGIN's count.
Only a successful END publishes reachability. Preflight the total origin and candidate capacity, then atomically install the complete staged contribution under the table lock. All entries receive the same monotonic commit time. There is no partial install and no discard-on-overflow subset. Missing END, missing self-route, a malformed entry, a count mismatch or staging exhaustion releases the stage and drains the offending exact link without publishing it. Other neighbors' candidates remain unchanged. No ACK is needed; each direction can finish independently, but setup is successful only after both local END write and incoming END commit. Readers and writers run concurrently.
Updates may follow the sender's END immediately. The receiver may process them after its incoming END even while its own writer finishes initial export. Before incoming END, any SET or WITHDRAW is a protocol failure. A second BEGIN, ENTRY or END after commit is a protocol failure even with an old sync ID. There is no stale-sync ignore policy and no mixing update IDs into sync IDs.
The first update ID is 1. Accepted updates must be exactly last + 1.
For a syntactically and topologically valid SET or WITHDRAW with
ID <= last, consume and ignore it, with no state change, notification or
expiry renewal. Duplicate content need not be retained to compare. Zero IDs
are invalid; stale malformed paths still fail validation. ID > last + 1
is a terminal gap. The receiver neither repairs nor accepts a later ID.
2^64-1 is a legal final update ID; it cannot wrap. Before another outbound
update is needed, drain with local Exhausted. New physical links reset both
directions to sync 1 and first update 1, even to the same neighbor genesis.
A failure or duplicate channel cannot restart counters on the old link.
Updates, selection and expiry
ROUTE_SET replaces the sole candidate for its origin and direct-neighbor
root, with exact physical-link provenance. A same-path fresh SET is a refresh
only while the existing candidate is still valid. It renews
expiresAt = acceptedAt + 60 seconds and leaves candidate revision and
selection unchanged. Before applying any update, remove expired candidates
at that acceptance time and recompute invalid selections under the same lock.
At acceptedAt >= expiresAt, even an identical SET recreates the candidate
with a new revision and competes as a new arrival. An old token never becomes
valid again because maintenance was late. A changed path replaces the old path and advances
its candidate revision. Do not retain a previous path because it was sticky.
WITHDRAW removes that neighbor's candidate if present. Withdrawal of an absent
origin still consumes its contiguous update ID. A neighbor withdrawing its
own root is a protocol failure. The local self-route cannot expire or be
withdrawn. A later fresh self SET must remain exactly [senderRoot].
Selection is sticky shortest, measured in edges of the full local path. Retain the selected neighbor while its candidate remains valid unless a strictly shorter candidate arrives. Equal or longer candidates cannot displace it. If the selected neighbor changes its path, first replace its path, then compare all valid candidates against that new length. A strictly shorter alternative wins; equal alternatives leave that neighbor selected. If selection is absent or invalid, choose shortest, then smallest next-hop root. Alternatives are ordered by length, then next-hop root. Export only the selected eligible path, never the alternatives. Route information grants reachability, not endpoint authorization.
Each sender schedules all currently eligible exports, including self, for a
fresh SET at least once per 20-second monotonic refresh interval. An initial
END counts as their first send. Changes can trigger SET or WITHDRAW earlier.
Receiver expires at now >= expiresAt, including a lookup at the boundary.
Only an accepted fresh SET or atomic initial commit renews candidates. Unknown
origins, PING, duplicates, WITHDRAW, incomplete frames and arbitrary traffic
cannot renew another candidate. Controlled clock injection is mandatory for
table and runtime tests. Store/security wall clocks do not drive route expiry.
Changes during an initial export and coalescing
Freeze the initial snapshot, not the whole table. Start recording dirty origins in the same table transaction that captures it. One bounded dirty/latest slot per origin and destination neighbor stores the current desired export or absence. A later change replaces that slot. Refreshes coalesce with changes. After END, reconcile snapshot against latest state and emit needed updates in ascending origin order. A change reverted before transmission needs no update. If snapshot exported a route that is now absent, reconciliation must send its withdrawal. A dirty slot is never dropped to make room.
Outside sync, retain one sent projection and one pending desired projection per origin and neighbor. Assign an update ID only when taking one immutable frame for the sole writer, not on enqueue. A failed or cancelled write is terminal, so assigned IDs cannot be skipped on a continuing session. Finish an in-flight frame before sending the newest state for that origin. There is no unbounded event queue or goroutine per event. After sync, scan pending origins in ascending order with a rotating start position, so a busy origin cannot starve another. Refresh due state survives coalescing until a current SET has been queued by that writer. Successful write means bounded mux-queue admission, not remote installation.
Origin slots with no candidates cannot be reused while any writer snapshot,
sent projection, pending withdrawal or in-flight frame references them. Pin
such tombstones within the same 257-origin bound. This prevents an unbounded
withdrawal backlog under origin churn. Release a sent pin only after its
withdrawal is fully queued, or after that writer joins on termination. A new
unknown origin that would exceed capacity fails locally as Limit, without
mutating the table, and terminates its contributing link. Capacity becomes
available when candidates expire or withdraw and all related pins settle.
Preserve the self slot. Do not evict live routes or required withdrawals.
Deadlines and failure ownership
| Operation | Absolute bound |
|---|---|
| Route OPEN or waiting for the designated opener | 10 seconds from successful claim |
| Initial exchange, both ENDs | 10 seconds from route OPEN commitment |
| Partial frame completion | 10 seconds from its first received byte |
| One complete frame write | 10 seconds from the first write attempt |
| Refresh cadence | 20 seconds, coalesced by origin |
| Candidate lifetime | 60 seconds from valid fresh acceptance |
The earliest applicable deadline wins. Deadlines never slide on byte progress. Idle waiting for a first byte has no route read deadline after initial sync; existing mux liveness still applies. There are no application keepalive frames. A nonresponsive writer cannot postpone a required withdrawal or refresh forever.
The closed local outcomes are Invalid, Protocol, Gap, Limit,
Exhausted, Timeout, Transport, Closed, StaleCandidate and
NoRoute. These are typed local results, not numeric route frames. Return
*Failure with exported Code Code and Scope Scope fields and
Error() string. Both enum types have underlying type uint8. Code constants
are CodeInvalid = 1, CodeProtocol = 2, CodeGap = 3, CodeLimit = 4,
CodeExhausted = 5, CodeTimeout = 6, CodeTransport = 7, CodeClosed = 8,
CodeStaleCandidate = 9 and CodeNoRoute = 10. Scope constants are
ScopeCall = 1, ScopeAdmission = 2, ScopeLink = 3 and ScopeTable = 4.
Zero and unknown values are invalid local construction, not success. These
numbers are local type constants only; they are never encoded on route wire.
The shorter outcome names below refer to these Code constants. Use errors.As
to inspect failures, never message matching. The codec returns link-scoped wire failures but makes no table
capacity or lifecycle decision. The caller carries the exact-link provenance.
| Code | Conditions and cleanup scope |
|---|---|
Invalid | Call-scoped malformed local input: nil required receiver/context, zero lookup root, zero/self admission token, out-of-range candidate index or missing required adapter/clock. Return without changing routes or draining a link. Invalid owner configuration fails startup before workers; never interpret remote malformed bytes as Invalid. |
Protocol | Link-scoped malformed wire, topology or sequence shape. Discard stage and drain that exact link. |
Gap | Link-scoped fresh update ID above the next expected ID. Drain that exact link. |
Limit | Call-scoped lookup-lease capacity, admission-scoped ticket capacity, or link-scoped route claim/parser/stage/table-origin/export capacity. The first two fail only that call/attempt; the last terminates its route runtime and drains that exact link without partial mutation. |
Exhausted | Link-scoped outbound wire update counter exhaustion drains that link. Table-scoped candidate/table revision exhaustion closes the daemon-wide table and fails service as specified below. Never infer scope from Code alone. |
Timeout | Admission-scoped setup ticket deadline fails only that admission. Link-scoped route setup, initial exchange, partial frame or write deadline drains that exact link. |
Transport | Link-scoped route channel EOF, RESET, truncation or mux/transport loss. Drain that exact link; no clean route EOF exists. |
Closed | Call-scoped operation on an explicitly released lookup lease. Table-scoped ordinary table/service shutdown. Admission-scoped caller cancellation, explicit Admission.Close or manager link cancellation. Link-scoped ordinary manager drain/removal/fork/shutdown cancels and joins runtime without asking for another replacement. |
StaleCandidate | Admission-scoped foreign table identity, replaced/withdrawn/expired candidate, mismatched revision or unusable exact link at reservation. Fail only the attempted reservation. An ordinarily closed manager may instead return admission-scoped Closed. |
NoRoute | Call-scoped absent, expired or unusable origin. Return a lookup lease with zero candidates and a captured change generation; no mutation or link drain. |
On an exhausted table, a valid lookup/reservation or existing lease read returns the latched table-scoped Exhausted, not ordinary Closed or NoRoute. Global closure is independent of per-link reconnect and cannot be cleared by it.
All unexpected link-scoped route-control termination, including EOF, RESET, truncation, gap, deadline or capacity failure, drains the exact physical link. No clean route-control FIN exists. It does not revoke or remove durable Peer trust. Manager replacement follows bounded normal-peer policy, with no route retry loop. Ordinary manager drain/removal/fork/shutdown instead cancels the route owner without requesting another replacement. Mark link unusable and invalidate its candidates synchronously at the admission barrier, before background cleanup. Stale L1 messages, deadlines, tokens, callbacks and release functions cannot change L2 candidates or release L2 reservations.
On termination: stop admission and invalidation first; cancel read/write and
wake blocked dispatch and timers; abort/reset route channel; join its reader,
writer and supervisor; discard stage and export pins; wait for channel
Settled() or transport failure; release channel hold, claim and runtime budget
exactly once. Never release a hold merely at Done(). Removal and shutdown
join acquired route owners. Existing admitted relay channels may retain the
manager's separate five-second drain policy; stopping routing neither moves
nor silently recovers an attachment. RESET or transport loss is not end-to-end EOF.
Closed pair extension
The accepted source in types.go, table.go and view.go is the base API
authority. Admission remains a channel-free ten-second managed ticket, not a
relay opener. The relay contract
assigns the additions to routing/types.go/table.go: Table.ReservePair,
PairSpec, PairOwnerCapability, its neutral trusted issuer,
PairAdmissionAdapter, PairAdmission and bounded lane interfaces.
The extension reserves both relay lanes at the SAME exact candidate/link
validation point, including the directory guard, and can open only those
prevalidated setups on that physical link. PairSpec carries a required neutral
owner capability and incident role. Relay allocates one local attempt-owner
before any pair; peer validates the trusted issuer/service scope and reserves
only pair-local ticket/link/mux liabilities. Both transit pairs retain the same
owner and budget lease through joins/settlement. Neither routing nor peer
allocates a second relay owner or calls a service budget. Missing paired support
or a zero/foreign/released owner capability fails closed.
A generic opener after Reserve is not a permitted prerequisite shortcut.
Routing does not own attachments or circuit buffers. Its optional paired
adapter consumes the same provenance and setup-ticket supervision as the base admission.
Successful relay setup transfers the managed pair hold to its established owner
before retiring the setup deadline. Route preference/expiry afterward cannot
move the attachment. No new route-control frame or token/revision wire field is
introduced. The shared routing additions and relay/owner.go have one owner;
shared relay types live only in relay/types.go, and service/budget/shutdown
composition lives in the service. No codec owner creates competing type files.
Typed lookup and exact admission boundary
The following describes the implemented source-level boundary in
routing/types.go. Root aliases
identity.ID. Path is a value with Count uint8 and Roots [8]Root in
entry-to-origin order; unused positions must be zero. Lookup storage is an
independently owned public-only immutable lease, not a detached allocation.
No SPKI bundles, private descriptors,
addresses, TLS, mux session or mutable table reference escapes.
Table.Lookup(origin Root) (*LookupLease, error)nonblockingly reserves one of 32 process-wide lookup slots before copying under the table lock. If all are held, return nil and call-scoped Limit. On success return a lease; for NoRoute also return a lease, with no candidates, plus call-scoped NoRoute. The caller must close every non-nil lease, including the NoRoute result. Other errors return nil. NoRoute still captures Origin, Revision and Changed under the same lock, so absent routes can be watched without an origin slot.- A
LookupLeaseexposesOrigin() Root,Revision() uint64,CandidateCount() uint8,Candidate(index uint8) (CandidateView, error),Changed() <-chan struct{},Err() errorand idempotentClose() error. Internally it owns one fixed inline 32-candidate snapshot, not a slice or another per-read allocation. Candidate index 0 is selected; indexes 1 through count-1 are alternatives in the specified order. Count is at most 32. EachCandidateViewis a fixed value with exportedPath Path,NextHop Root,CandidateRevision uint64andToken AdmissionTokenfields. Self has one candidate with its one-root path, zero next hop, zero token and no alternatives. No method returns the complete snapshot, a detached slice or an address into the inline array. Candidate returns one fixed value with no heap-owned path/slice. A caller must not materialize an uncharged copied snapshot collection; the later attempt owner retains chosen values within its own bounded attempt storage, not as route-allocated results. The complete CandidateView must fit a 384-byte charge, so 32 values cost at most 12,288 bytes and leave 4,096 bytes of its 16 KiB slot for metadata, lease handles and lifetime synchronization. No admission hold is stored in a lookup slot. - Origin, Revision, CandidateCount and Changed are constant metadata readable
after release. Candidate validates lease lifetime before its index and
returns Closed after explicit release/ordinary table close, or the latched
Exhausted after global exhaustion.
Err()is nil while usable, including NoRoute, and returns that same terminal cause afterward. Close releases the payload and count slot exactly once, cannot change a later lease using that slot, and returns nil even if already released. It invalidates future reads, not a fixed token copied before release. Tokens are validated at Reserve. Normal routing changes do not invalidate the historical lease payload; Changed wakes the caller to relookup, and Reserve always checks current state. Candidate reads serialize with Close and table revocation. A read winning before revocation can return historical data; a read after revocation cannot touch freed or reused storage. Neither read nor release calls peer or takes admission locks. Service shutdown cannot require callers to release leases before it can revoke their payloads. - Table and candidate revisions are independent
uint64counters with the daemon-wide exhaustion lifecycle below. They are not wire counters. AdmissionTokenis opaque and contains table identity, origin, candidate revision and an opaque exact physical-link capability. It does not own a channel or keep a dead link admissible. It cannot be constructed from a relationship ID or reused in another table. Lookup of an alternative supplies its own token, not the selected route's token.Table.Reserve(ctx context.Context, token AdmissionToken) (*Admission, error)performs the exact candidate/link reservation for a future fresh attachment.Admissionexposes only the immutablePath() Path,NextHop() Root,Done() <-chan struct{},Err() errorand idempotentClose() error. These are the complete base methods. There is no channel-opening, channel-reservation or hold-transfer method, generic or otherwise. The base admission supplies only the opaque exact-link hold used internally at the joint admission boundary. The closed paired-lane operation, its setup family, capacity and rollback/transfer rules extend this boundary using this same exact candidate/link linearization, not a relationship-ID opener after a prior check. Base admission grants no endpoint permission. A self route needs origin-local handling; Reserve with its zero token returns call-scoped Invalid.Changedis a shared receive-only channel generation captured atomically with the snapshot. Close it on selection/path/alternative eligibility or link-usability changes, not identical refreshes. Replace it once per mutation batch. It is a wake-up hint, not a per-subscriber queue or retained event history. Callers relookup; no subscription goroutine is created.
Daemon-wide revision exhaustion
Table revision starts at 1 for the self-only table. Advance it once for each
atomic externally observable selection/path/alternative change batch,
including initial commit, withdrawal, expiry and link invalidation. Identical
valid refreshes and ignored stale IDs do not advance it. Candidate serial
starts at 0; each new/recreated/changed-path candidate gets the next value,
beginning at 1, unique across all origins and links in this table. Self uses
candidate revision 0 and has no admission token. Both counters are uint64;
2^64-1 is the last allocatable value, with no wrap or reuse.
Preflight all revision allocations needed for a transaction, including a whole initial install, before publishing any part. If either counter lacks the required values, return table-scoped Exhausted and close the daemon-wide table in that same table-lock transaction. Do not partially install or drain only the triggering neighbor. An expiry, withdrawal or link invalidation that cannot allocate its revision takes this global closure path instead of retaining stale reachability. Closure uses an already allocated closed/cause flag, not another revision, new generation, notification queue or allocation.
Global closure synchronously makes every candidate, including self, unusable,
invalidates every token through the table identity's closed flag, closes the
current Changed generation once, and closes Table.Done() <-chan struct{}.
It creates no replacement Changed generation. Table.Err() error returns the
latched table-scoped Exhausted. Valid future Lookup/Reserve calls fail with it,
even if a physical link remains alive. Existing LookupLease.Candidate/Err
check this flag too; closing a lookup lease still releases its payload.
Already copied candidate values are historical data, never proof of admission.
The closed flag immediately prevents all new ticket use. After releasing
admission/table locks, the owner marks all still-live Admissions failed with
table-scoped Exhausted and closes their Done signals through the bounded peer
ticket owner. No table-to-peer lock acquisition or callback occurs inside the
table transaction. The failure's first table-close notification
uses the service's fatal-failure path, outside all admission/table locks. It
cancels the service, rather than scheduling reconnect or constructing a fresh
table. In the baseline this is service.fail, which cancels and closes
listeners; the ordinary service shutdown owner performs the joins. No worker
calls service.Wait or joins itself from a failure callback. Route claims,
dispatch, timers, channels and exact-link holds join under the ordinary
shutdown/Settled barriers, then stages, projections, lookup payloads and
global reservations release exactly once. Global close revokes outstanding
lookup leases and reclaims their payload slots without waiting for caller
cooperation; late Close is harmless. Service.Wait reports the fatal cause.
There is no same-process restart or automatic fresh table identity. Only a new service instance after explicit restart gets a new opaque table identity and fresh counters, with every link requiring initial synchronization. Do not persist counters or route state. Normal service shutdown closes the table with table-scoped Closed and uses the same fail-closed invalidation and joined release, without inventing an Exhausted outcome. This lifecycle is distinct from wire update exhaustion, which drains one exact link and resets its wire counters on replacement while this daemon-wide table remains live.
The clock boundary is Clock.Now() time.Time and
Clock.NewTimer(time.Duration) Timer; a Timer has C() <-chan time.Time,
Reset(time.Duration) and Stop(). Production Now retains Go's monotonic
component; the test clock advances only by explicit test action. An earlier
expiry or refresh deadline wakes the existing timer owner, never allocates
another timer per candidate. Reset drains obsolete delivery before rearming.
Admission tickets are owned by peer, not an attachment registry in routing. Reserve internally acquires a ticket through the token's exact-link adapter, before entering admission locks. No caller ticket API or relationship lookup is needed. Bounds are 32 process-wide and at most 8 per exact link, charged to that link's runtime allowance. Its ten-second setup deadline begins at ticket acquisition and closes Admission.Done on expiry or link cancellation. A failed candidate check releases it immediately; Close is idempotent. Relay transfers it into its own bounded setup/attachment owner or closes it; routing does not retain unbounded Admissions. The base admission has no transfer method. Route-control and directory claims use separate leases and cannot consume these optional tickets. Ticket Limit, setup deadline and caller cancellation fail that admission only; they are not route-control termination and do not themselves drain the link.
Admission.Err is nil until terminal. Set its cause before closing Done: admission-scoped Timeout at the ticket deadline, admission-scoped Closed for caller cancellation, explicit Close or manager link cancellation, or table-scoped Exhausted for global exhaustion and table-scoped Closed for ordinary table shutdown. Latch the first terminal event; later causes cannot overwrite it. After Done, Err returns the immutable cause and owned hold/ticket capacity releases exactly once outside admission locks. Close always returns nil and closes Done if it was still live. Path and NextHop remain fixed metadata, not authorization to open a channel. StaleCandidate is a Reserve failure before Admission exists, not an asynchronous rewrite of an admission that already linearized. Table shutdown still forbids new admission even if a prior Admission.Err latched another cause.
Admission checks table identity, exact candidate revision, expiry, path and exact link being READY, selected for its relationship, not draining, and still store-admitted under current head/relationship barriers. Merely changing which candidate is selected does not invalidate an unchanged valid alternative's token. Path replacement, withdrawal, expiry or link replacement does. A caller must compare and keep the chosen immutable path, never ask a relay to select a new suffix. Relay adds paired-lane reservation to this same exact admission; it must not reopen by genesis after the check.
Reservation linearizes when exact-link hold and candidate validation both succeed under the existing peer gate/store admission barrier, manager mutex, then routing table mutex, in that order. The opaque peer-to-routing adapter must perform the concrete candidate check; a missing adapter fails closed. No network I/O, callbacks into service, budget allocation, channel wait or join runs while these locks are held. Pre-reserve local resource capacity before entering them, release it on a failed check. Routing code never acquires peer or store locks while holding the table lock. Link invalidation uses the same manager-to-table order and wakes workers only after releasing locks. Candidate updates against an exact link use that order too. Clock reads cannot call peer. Budget locks are acquired and released before admission, never nested inside it. Notifications close locally and observers run outside locks.
If L1 becomes unusable before that linearization, the token fails as
StaleCandidate or Closed, even if L2 has the same roots, heads and path.
If admission wins first, the resulting hold remains bound to L1; later route
changes affect future attempts only. L1 drain can still abort setup or later
transport. It cannot substitute L2. Table cleanup may lag, but lookup filters
expired and synchronously marked unusable links before returning values.
Finite resources and byte proof
These are the routing limits, independent of directory cardinality. Zero never means unlimited. Lower aggregate service capacity may reject an otherwise valid request. Increasing these limits requires a new proof.
| Owner | Bound |
|---|---|
| Origin slots, including self and pinned tombstones | 257 |
| Contributing selected links and live route runtime claims, including draining owners until joined | 32 |
| Remote candidates | 256 × 32 = 8,192, one per origin and neighbor root |
| Full local path | 8 roots, 256 bytes of root storage |
| Initial stage, immutable export, sent projection, pending/dirty state | Each at most 257 records per link |
| Parser and encoded writer | One 241-byte frame each per link; one frame in flight |
| Route proposals | One reference per link, charged within mux's existing 8 pending OPENs |
| Route workers | Three per claim, supervisor, reader, writer; at most 96 |
| Typed proposal dispatcher | One additional joined worker per exact link; at most 32, charged to route runtime headroom, shared with directory |
| Table maintenance | One worker and one nearest-expiry timer, no timer per candidate |
| Runtime timers | At most five per claim for setup/initial, partial read, write, refresh and nearest admission-ticket expiry; at most 160 |
| LookupLease payload | Fixed inline storage for at most 32 candidate values, at most 16 KiB per live lease including handle/slot metadata |
| Outstanding lookup leases, including construction and NoRoute results | 32 process-wide; payload remains charged until Close or table revocation, not merely until Lookup returns |
New worker total is at most 129, including table maintenance. Existing mux workers are not counted again. The route supervisor manages the bounded admission-ticket deadline set through one nearest-deadline timer and one coalesced wake signal. No ticket creates a goroutine or individual timer. The dispatcher uses mux's existing OPEN decision timeout, not another timer, and joins before runtime charge release. Ticket expiry and cancellation release peer holds outside table and manager locks. A route owner cannot join while an unconsumed ticket still retains its runtime charge.
Use bounded indexed/slab storage rather than unaccounted Go map growth or a
whole-table clone per update. A candidate slot charge is 384 bytes: 256 path
bytes plus at most 128 for roots/provenance, timestamps, revisions, indexing
and alignment. The implementation must demonstrate actual retained layout
fits this charge, or stop and revise the proof before allocation. Remote table
storage is 8192 × 384 = 3,145,728 bytes. Origin/index metadata is
257 × 128 = 32,896. Two selected projection arrays, allowing old/new overlap,
are 2 × 257 × 384 = 197,376. Subtotal is 3,376,000 bytes. A 4 MiB global
DataBudget reservation leaves 818,304 bytes for fixed indexing, free lists,
self and owner metadata. Updates and initial installs preflight then mutate
under one lock; no hidden second 4 MiB table clone is permitted.
Each initial stage, frozen export, sent and pending projection is at most
257 × 256 = 65,792 bytes. These projections need only seven-root wire paths,
224 bytes, plus 32 bytes of indexing/revision/occupancy metadata. Thus four
simultaneous arrays cost 263,168 bytes per link. Add parser and encoded frame,
2 × 241 = 482, an in-flight immutable projection of 256 bytes, and one
16 KiB supervisor/writer batch workspace. Subtotal is 280,290 bytes. Reserve
512 KiB DataBudget per runtime before claim or worker allocation, leaving
243,998 bytes for runtime structs, dispatcher references, bounded stacks and
join/deadline owners. Initial staging transfers into preallocated table slots;
it never creates another decoded path copy. Dirty reconciliation reuses the
pending array. Do not concatenate the whole initial byte stream for writing.
Within the global DataBudget headroom, reserve 32 × 16 KiB = 524,288 bytes
for all retained lookup lease payloads using a fixed slot pool. A held lease
keeps its slot occupied even when no call is running. The 33rd sequential
Lookup fails with call-scoped Limit if the first 32 results were retained.
Closing one permits one further result. NoRoute results consume slots too.
Do not allocate a separate construction workspace or detached Alternatives
slice: construct directly in the acquired slot under the table lock. That leaves
294,016 bytes of the 4 MiB charge for the other fixed indexing and owner
metadata above. Every live or constructing route-owned returned snapshot is
within this 524,288-byte and 32-lease bound. Metadata and single-candidate
fixed-value reads require no route-owned heap allocation. Callers may retain
leases indefinitely within this bound; they cannot obtain another uncharged
snapshot payload by releasing its slot. Closed handles cannot read a reused
slot. Chosen paths copied into Admissions are covered by the existing 32-ticket
bound and runtime headroom; relay attempt buffers have their own proof.
The implemented lookup-handle and slot-lifetime regressions check concrete sizes
and reuse safety at this boundary. Payload reclamation on global close does not
depend on callers noticing Changed.
Reserve a further 32 KiB ControlBudget per runtime and 64 KiB global control
workspace. It is not a second lookup payload store. Proposed service resources
are routing_memory,
Count 1 / Bytes 4 MiB; routing_runtime, Count 32 / Bytes 16 MiB / PerKey 1 /
KeyBytes 512 KiB keyed by exact physical link identity; routing_control,
Count 33 / Bytes 1,114,112 with global and per-link parts. Reserve both classes
atomically; no fallback if a resource entry is missing. These are internal
budget additions for other owners; routing does not change them.
Total extra DataBudget is 4 MiB + 32 × 512 KiB = 20 MiB. Total extra
ControlBudget is 64 KiB + 32 × 32 KiB = 1,114,112, or 1.0625 MiB. Actual
baseline service caps are 512 MiB data and 16 MiB control; directory caps
are 384 MiB data and 12 MiB control, peer mux 32 × 6 MiB = 192 MiB data.
Those maxima already cannot all coexist. Do not claim simultaneous maximum
capacity. Shared Budget.Reserve must atomically reject combinations over
the aggregate cap. Directory control plus route control plus 32 private
control connections at 64 KiB is 15.0625 MiB, below 16 MiB; control-frame
leases and other consumers still contend for the remainder. No control cap
or PeerMuxBytes increase is authorized by this proof.
A maximum initial wire export is 16 + 49 + 256 × 241 + 16 = 61,777 bytes.
A maximum refresh sweep is 47 + 256 × 239 = 61,231 bytes. The mandatory
self path is one root, not seven. These are streamed,
not retained as another buffer. All route channel receive and outbound copies
are already within the existing peer mux charge. Baseline peer mux limits are
32 active and 32 terminal channels, 8 pending OPENs, 4 KiB setup, 32 KiB pending
setup aggregate, 64 KiB receive credit per channel, 2 MiB aggregate receive,
2 MiB outbound, 128 KiB outbound per channel, 64 control frames / 64 KiB
protocol-control queue, and a separate 64 KiB control-class DATA reserve.
Do not double-count that reserve as additional route memory.
Three baseline active channels are directory control, directory bulk and routing control. Gate every optional consumer, both control and bulk, until all three required channels commit. Only the typed directory and route claims may admit channels during this phase. Failed setup drains the link without opening that gate. Afterward, retain two control admission slots and two pending decision slots against bulk, with 8 KiB of pending setup headroom inside the existing 32 KiB. The current one-slot rule is insufficient, and class-only protection cannot replace the initial optional-consumer gate. Within the existing 64 KiB control-class DATA reserve, protect at least 1 KiB for routing and 16 KiB for directory against other control consumers. Each stream can make partial bounded queue progress; a 64 KiB directory control frame need not be queued in one operation. Retain fair control-channel rotation and existing eight-priority-frame bulk turn. Control shares and admission are internal rules, not new class bytes. Relay must partition optional circuit control without consuming these shares and prove its channels, pending attempts and terminal records separately. The arithmetic ceiling of 14 two-lane attachments is not a capacity promise.
Hand-worked examples
Fixture root labels are nonzero synthetic IDs, not signed identities. In the
line A-B-C, establish B-C first. C's initial [C] gives B full [C,B].
Then B's initial export to A is sorted [B], [C,B]. At A, neither candidate
exists at BEGIN or either ENTRY. END installs both at one timestamp. Lookup C
returns [A,B,C]. line.refresh is update 1 for [C,B]; line.withdraw is
update 2 for C. A loses C on withdrawal, not B. If instead A receives
line.gap as its first update, ID 2 is a gap and drains A-B. Its B and C
candidates disappear immediately. line.refresh repeated after acceptance
is ignored without extending C's lifetime. Fixtures include both duplex
initial streams and exact channel setup bytes.
In the diamond A-B-D and A-C-D, B and C first learn D. B's initial to A
contains [B], [D,B]; C's contains [C], [D,C]. Install both before initial
selection for D, or install B first. A selects B because B sorts below C.
Full route is [D,B,A]; lookup returns [A,B,D] and alternative [A,C,D].
If C arrived first and was already selected, equal B would not displace it.
A exports D to C as [D,B,A] but sends no D to B. When B withdraws D, C wins;
A's previous export to C needs a withdrawal and its export to B becomes
[D,C,A]. The fixture has actual SET and WITHDRAW bytes for this transition.
C must not advertise [D,B,A,C] back to A because A is in it. A one-root
[D] advertised directly by D is shorter and displaces either diamond route.
For exact-link replacement, A's old token for B/L1 names the old D candidate. L1 drain invalidates it synchronously. A-B/L2's initial stream can have identical bytes and sync 1 again, but supplies a new capability and candidate revision. Delivering an L1 update 1 or Close after L2 commit cannot affect L2. Old-token reserve fails. New lookup is required. An admission that won before L1 drain remains L1-bound and may fail with that transport, never move to L2.
The fixture README gives per-frame and concatenated transcript byte counts, seven-root boundary bytes and failure cases. An independent reviewer can reconstruct installs, counters and path reversal without running Go.
Route table API
internal/agenthub/routing implements the RAM table and immutable lookup
boundary. Service composition wires the codec into the route runtime. Codec types and
workers remain separate owners. No literal fixture or wire rule changes here.
NewTable(local, clock, adapter) requires an explicit monotonic clock and an
AdmissionAdapter. RegisterLink(root, Provenance) allocates one of 32 runtime
slots. Provenance.Usable() is a lock-free, nonblocking check of the exact
physical link, irrevocably false after invalidation. CommitInitial(handle, []IncomingPath) borrows one bounded, sorted stage and atomically publishes it.
Set(handle, id, path) and Withdraw(handle, id, root) validate topology even
for stale IDs and implement the directional sequence check. All three calls
run under the peer admission barrier and manager mutex before the table mutex.
The table does not acquire peer locks or resolve relationship IDs.
IncomingPath stores at most seven roots in origin-to-sender order and excludes
the receiver. The retained candidate uses that representation. Lookup's Path
is entry-to-origin and includes the receiver, with up to eight roots. Both are
fixed values with zero unused roots. Candidate tokens retain only an opaque
table identity and exact-link handle, not the mutable table or candidate slab.
The maintenance owner calls Expire() and uses NextExpiry() with one nearest
expiry timer. Lookup also removes expired and synchronously marked unusable
candidates, so maintenance lag cannot revive a stale token or return an already
unusable link. MarkUnusable(handle) synchronously invalidates that exact
contribution. ReleaseLink(handle) is only for the joined runtime and cannot
release or mutate a replacement's slot. Table closure revokes all lookup pool
payloads without waiting for callers. The process-wide pool has 32 slots shared
by construction, live results and NoRoute results across tables.
Export(origin, destination) returns only the selected eligible path. A false
result means absence and requires withdrawal if previously sent.
CaptureExport(handle, *ExportSnapshot) captures a sorted immutable projection
and establishes origin pins in the same transaction. Each active writer owns
at most one bit per origin, not an unbounded reference count. New or changed
candidate contributions pin affected origins for active writers. Runtime scans
with ScanExports(handle, *ExportSnapshot) on a shared Changed generation.
Both capture and scan include Revision and Changed atomically. Capture contains
eligible paths only; scan also contains pinned absences so a writer can settle
an origin that appeared and disappeared before it observed it. ExportRecord
has Origin, Count and a six-root Tail. Count zero is a local absence;
Incoming() then returns the all-zero path, never a malformed wire path.
Runtime must release a pin with ReleaseOrigin only after snapshot, pending,
sent and in-flight references are gone. Ineligible entries captured by a scan
must also be reconciled and released. ReleaseExports releases that writer's
pins after join. Pins never replace the runtime's sent or pending projection
accounting.
AdmissionAdapter.ReserveRoute(ctx, provenance, table, validate) is the peer
integration hook. It reserves a bounded peer ticket before taking locks, then
invokes validate under peer gate, store barrier and manager mutex. Validation
acquires only the table mutex and captures the immutable candidate path at the
joint hold/validation linearization point. Failure releases the ticket. The
peer ticket owner must honor caller cancellation, the ten-second deadline,
link cancellation and Table.Done/Err, latch causes before Done, and release
holds outside locks. Table closure immediately prohibits validation; the
bounded ticket owner settles already admitted tickets afterward. The service
owner observes table-scoped Exhausted and invokes fatal service cancellation
outside locks. Routing itself creates no admission goroutine or timer and
exposes no channel-opening operation.
Table storage uses 256 by 32 fixed candidate slots, 257 origin metadata slots and 32 exact-link runtime slots. Durable tests check the actual retained sizes against the frozen 384-byte candidate/view, 128-byte origin, 4 MiB table, 16 KiB lookup slot including handle, and 256-byte export-record charges. The service must reserve those global and per-runtime allowances before allocation; this package does not allocate budgets or start workers.
Bounded sweep and observation implementation
The preceding 32-link layout describes the original sizing. The current
compiled guardrails are MaxOrigins = 257, including self and pinned
unreachable origins, and MaxLinks = 256 exact physical links. The candidate
matrix is therefore 256 by 256; MaxCandidates = 32 still bounds returned
lookup/candidate alternatives, not occupied matrix cells. Route observations
retain the existing MaxRoutePageRows = 16 page guardrail. These are existing
supported bounds, not new targets introduced by the optimization.
Table.candidateOrigins is a fixed origin bitmap for each exact link. Bit
i-1 is set exactly when remote origin slot i has a candidate with nonzero
revision. Expired and unusable candidates remain indexed until the ordinary
sweep clears their cells. Initial commit and replacing/new SET set the bit;
WITHDRAW and sweep clear it. Same-path refresh preserves occupancy. The index
is maintained under the table mutex after the existing revision preflight.
Joined release and late callbacks retain their exact-link checks, so a retired
link cannot clear a replacement's index.
Both sweep passes inspect indexed cells instead of every empty matrix cell. The second pass still rechecks expiry and provenance usability, including lock-free retirement published after the first pass. Fallback selection, exporter pins, tombstones and observation/revision advancement keep their existing behavior. This also reduces the shared sweep work performed by export writers; no writer scheduling, refresh timing or maintenance is suppressed.
Route listing sorts only used origin-slot indices by root, computes the total and continuation position, then projects candidate values for the returned page. Off-page routes need no value projection. This remains a live read under one table lock, not a retained sample or cursor cache. Old-sample continuation and detail rejection are unchanged.
The index adds 256 × 256 / 8 = 8,192 retained bytes per table, with no growing
map, lease, timer or worker. It fits the existing 24 MiB retained-table test
guardrail and the service's existing 128 MiB global routing DATA reservation,
which also covers lookup storage and ticket ownership. No reservation or limit
is increased. On 64-bit builds, route ordering scratch is a 2,056-byte array of
257 slot indices instead of the full array of route values. Durable layout,
index-mutation, maximum-page, stale-sample and overflow tests check these
implementation bounds; they do not establish maximum live-service traversal
completion under continuous churn.
Routing frame codec API
routing/codec.go and frame_io.go implement the frozen frame bytes without
peer or service imports. Message is a fixed wire-only value with Kind, ID,
Count, Index, Path IncomingPath and Origin Root. ID is the sync ID for
sync kinds and the update ID otherwise. EncodeFrame(*FrameBuffer, Message)
returns the encoded length; DecodeFrame([]byte) accepts exactly one complete
frame. Encoding invalid local field combinations returns call-scoped Invalid.
Decoding malformed wire shape returns link-scoped Protocol; truncation returns
link-scoped Transport. Neither function retains raw bytes or allocates a
successful decode copy. A returned message owns fixed root values.
Syntax includes version, kind, exact length, nonzero IDs, sync ID 1, counts 1 through 257, indexes below 257, and wire path counts 1 through 7. Unused local fields and path roots must be zero. Root validity, uniqueness, receiver exclusion, sender identity and self-withdrawal remain table validation. Initial exchange ordering, index relative to BEGIN, repeated sync, stale updates and gaps require state outside the codec. In particular, decoding a stale ID does not authorize skipping topology validation.
ReadFrame(ReadStream, *FrameBuffer, initialDeadline) reads no more than one
frame, regardless of mux DATA boundaries. WriteFrame(WriteStream, *FrameBuffer, Message, initialDeadline) handles bounded short writes. The
interfaces require only I/O and the respective deadline setter. The sole reader
and writer each own a separate reserved 241-byte buffer and stream deadline.
The runtime must reserve those 482 bytes before allocating either buffer. A
length prefix cannot allocate storage; its bound is checked before conversion,
addition or body read. Message values are transient, not a retained frame queue.
Pass the initial-exchange absolute deadline on every call until synchronization finishes, then zero. The first received byte starts a fixed ten-second read completion deadline; the first write attempt starts the write deadline. The earlier initial deadline wins. Progress never slides either bound. Idle reading after sync has no route deadline. Helpers clear their deadline on return; setter failures, EOF and other I/O loss are link-scoped Transport, while deadline expiry is link-scoped Timeout. Helpers start no workers or timers and acquire no locks. They do not reset channels, mutate tables or release runtime resources. Any wire/I/O failure is terminal for the caller's exact-link route owner, which must perform the cancellation, drain, join and settlement described above. During ordinary manager drain, preserve the latched Closed cause rather than turning cancelled I/O into a replacement-triggering unexpected failure.
Route engine API
routing/engine.go implements the stream runtime without importing peer or
service. RunEngine(ctx, EngineConfig) error is the caller-joined supervisor;
it creates one reader and one ordered writer. Invoke it once per registered
exact-link handle and claimed stream, never to retry a failed physical epoch.
EngineStream combines the codec's read/write deadline interfaces with
Abort() error and Settled() <-chan struct{}. Abort must interrupt both I/O
directions without joining them. Settled includes channel-accounting settlement
on transport loss, not merely channel Done.
EngineConfig requires Table *Table, Link *LinkHandle, Clock Clock,
Stream EngineStream, Barrier EngineBarrier, InitialDeadline time.Time,
and Reserve func(dataBytes, controlBytes int64) (release func(), err error).
Its optional Ready chan<- struct{} must be fresh and exclusively owned by
this invocation; the engine closes it after the outgoing END and incoming
atomic commit both succeed before the absolute initial deadline. Completion
notices are accounted before failure cleanup and again after both worker joins,
so an immediate post-sync failure cannot hide a successful exchange. Ready
closes exactly once for two timely completions; the subsequent failure remains
the runtime's return value. Late or missing completions do not close Ready.
The deadline is OPEN commitment plus ten seconds, not runtime launch plus ten
seconds. Controlled-clock regressions separately prove that post-commitment
scheduling cannot restart it and that legitimate pre-commitment setup time does
not consume the initial-exchange allowance.
Clock is the table's monotonic clock and the stream's deadline time domain.
EngineBarrier.Apply(func() error) error executes candidate mutations exactly
once, synchronously under peer gate, store barrier, manager mutex, then the
table mutex acquired by the callback. An unusable gate returns link-scoped
Closed without invoking the callback. Callback errors, including table-scoped
Exhausted, pass through unchanged. The runtime rejects skipped or repeated
successful callback invocation rather than publishing a second mutation.
EngineBarrier.Invalidate(error) error stops exact-link admission and calls
Table.MarkUnusable under the existing lifecycle barrier before returning.
Production required-owner failure drains that exact physical link; ordinary
closure of an already retired link is idempotent. Neither method joins workers, performs channel I/O,
or acquires budget locks under the admission barrier.
Standalone Reserve acquires 512 KiB data and 32 KiB control before engine
arrays, buffers, timers or workers. Production instead reserves both charges
before READY claims and transfers the real release to exact-link finalization
through RegisterRouteRelease. Its engine Reserve returns a nonnil no-op
release; engine return cannot release capacity while the dispatcher or managed
holds remain live. Rejection leaves no partial reservation and yields link-scoped
Limit. Invalid configuration starts no workers and leaves ownership with the
caller. Failure invalidates first, cancels workers, aborts the stream, joins
reader/writer, waits for Settled, explicitly releases the route channel hold,
and releases export pins and the registered table link. The caller closes the
claim after the joined return. Global Exhausted remains fatal through cleanup.
Later ordinary table shutdown cannot overwrite a latched link-scoped Closed.
The reader uses one fixed 257-path stage, validates relative indexes, sorted
unique origins, topology and matching BEGIN/END, then borrows the stage for
CommitInitial. No entry is published before END. SET/WITHDRAW are accepted
only after commit; topology, contiguous/stale IDs and atomic capacity/revision
preflight remain the table's authority. A repeated sync is terminal. Incoming
updates can proceed while the outgoing initial stream is still blocked.
The writer owns fixed frozen, sent and pending arrays, not an event queue. Capture and table pin ownership begin in one transaction. After its immutable END, it scans latest exports and pinned absences. The table's shared Changed generation is a bounded wake signal; the pending records hold desired state. It rescans between immutable in-flight frames, coalesces reverted changes and refreshes, and rotates its ascending origin scan after each send. Each sent record retains its last successful queue-admission time, so refresh due state survives intervening changes. IDs are assigned only when taking the next frame; the final uint64 value is legal and another required send fails link-scoped Exhausted without wrapping. Required withdrawals keep their sent pin until fully queued. Unobserved absent records release their pins after their last pending reference is cleared. Failed writes terminate instead of retrying or skipping an ID. No stream I/O occurs under the table or admission locks.
RunMaintenance(ctx, table, clock) error is a separate caller-joined global
worker with one nearest-expiry timer and an atomic expiry/watch plan. The
service owns exactly one instance per table and handles returned table-scoped
Exhausted through its fatal path outside locks. It is not started per link.
Each engine has an initial timer, a writer refresh/change timer and one reusable
nearest admission-ticket timer. Frame deadlines remain in the stream. No timer
or goroutine is created per route, update or admission ticket. Cancellation uses a
detached standard context source and supervisor propagation, avoiding a hidden
unjoined propagation worker for custom caller contexts.
Measured linux/amd64 retained layout is 225 bytes per stage path, 256 bytes per sent record including its timestamp, 57,856 bytes per export snapshot, and 239,984 bytes for the complete engine including its two 241-byte buffers. The four projection arrays total 239,329 bytes, below their 263,168-byte charge. The engine plus the reserved 16 KiB transient workspace is 256,368 bytes, leaving 267,920 bytes within the 512 KiB runtime charge for bounded worker stacks, timers, contexts, joins and composition headroom. Tests reject layouts exceeding the frozen per-record, per-projection and runtime charges. No second table, growing map, retained raw transcript or per-update queue is allocated. The existing 32 registered-link bound includes draining runtimes until join.
Controlled-clock/stream tests cover atomic duplex initial exchange, frozen snapshot races, reversion and unobserved tombstones, update storms, fair latest state/refresh reconciliation, full-capacity pinned withdrawals, independent writers, stale/final counters, stage rejection, capacity/global exhaustion, blocked first/partial reads and writes, cancellation, transport failure, ordinary table shutdown, delayed settlement and nearest-expiry maintenance. Service/peer adapters, pre-claim reservation, OPEN setup, composed admission supervision and outside-lock fatal delivery are implemented as described below.
Production composition and resource proof
service/routing_sync.go is the composition owner. Startup atomically reserves
the configured routing_memory global DATA workspace and 64 KiB global
routing_control charge before lineage verification or table construction. It verifies the signed local
AuthorityLineage and checks its genesis and pinned head. The verified genesis is
the table root; no filesystem path or authenticated successor head is used as
that root. One joined RunMaintenance call owns global expiry/watch planning.
The internal lookupRoute returns the existing bounded LookupLease and requires
caller Close. It neither projects remote availability nor allocates trust.
READY reserves routing_runtime at 512 KiB data and routing_control at 32 KiB
control atomically before claims or workers. The effective configuration owns
runtime count/aggregate bytes; each exact link has PerKey 1 and KeyBytes 512 KiB. The immutable ReadyLink.Done() channel identity
is the exact-physical-link key, including through drain and finalization. It is
not the relationship ID, a READY wrapper address or a mutable head. The manager
owns the registered release until dispatcher and managed holds join, outside
locks. Before successful registration the caller owns rollback. Every required
failure calls READY Drain, even before either claim exists.
Directory and route claims, exact BindTable and admission Activate all succeed synchronously before either setup worker is scheduled. The route lease is the engine barrier. A small maintenance adapter embeds that already-activated lease and makes only the engine's activation call a no-op. It delegates Wake, Done, Step and Shutdown to the exact lease. No separate ServeAdmissions or settlement worker is launched. Setup uses the claim's SetupDeadline; initial exchange uses immutable channel CommitmentTime plus SetupTimeout. The setup context's timer is canceled before runtime starts. Engine Reserve returns a nonnil no-op release because exact finalization, not engine return, owns the real charge.
The engine joins reader and writer, aborts the stream, awaits Settled and releases the explicit route channel hold. Service setup rollback does the same before closing the claim. Route Close also returns a bound table slot when setup never started an engine. Global maintenance returns without locks before service fatal delivery. Service shutdown joins peers and all workers, closes the table, then releases global capacity. Table-scoped failure stays fatal; there is no new table identity on reconnect. Direct endpoint preparation and gateway remote unavailability are unchanged.
Concrete retained layouts and storage
Measurements below are linux/amd64 value layouts on the integration toolchain,
not allocator-size or whole-process RSS claims. Private layouts come from the
API owner's TestRetainedLayoutCharges, TestComposedRouteLayouts,
TestRouteFixedMetadataCharges, TestTypedDispatchFixedMetadataBound and
TestEngineLayoutAndReserveBeforeWorkers. Service's
TestServiceRouteGlobalReservationAndConcreteLayouts measures the composition
and budget values; TestServiceRouteBudgetFullOwnershipAndAtomicRejection
checks actual bounded map/slice ownership and atomic rejection at 32 charges.
| Owner/value | Actual bytes and bound |
|---|---|
| Table | 2,173,368; fixed 256 × 32 candidate slots, 257 origins, 32 links |
| Candidate / origin slot / CandidateView | 264 / 40 / 360, below 384 / 128 / 384 charges |
| Table plus 32 handles and identity | 2,175,944 |
| Global lookup pool including 32 lease handles | 371,208; one slot plus handle is 11,600, below 16 KiB |
| Export snapshot | 57,856; fixed 257 records, each at most 256 |
| Engine | 239,984, including fixed stage/frozen/pending/sent arrays and both 241-byte frame buffers |
| Stage path / sent record | 225 / 256; four arrays total 239,329 |
| Admission wait / supervisor select cases | 160 / 1,400 for 25 fixed cases |
| Peer Channel / Link / RouteLease / RouteIdentity / provenance | 32 / 552 / 168 / 128 / 16 |
| Ticket / global manager ticket slots / Admission | 96 / 256 for 32 pointers / 312; at most 32 tickets globally and eight per link |
| Typed dispatch metadata | 376; inbox 56, proposal 32, consumer lease 40; at most three retained proposal references within existing mux pending OPENs |
| Service route owner / already-active maintenance adapter | 56 / 8; no map or slice of sessions, no second manager or attachment registry |
| Reservation / BudgetLease / usage / keyed key | 56 / 48 / 16 / 32 |
| Budget lease parts | Two entries with len = cap = 2, 112-byte backing array per global or per-link reservation |
| Local authority verification values | AuthorityKey 88, VerifiedRecord 616; at most 65 lineage records/keys, 1,560 bytes of temporary frame-slice headers |
Global data uses 2,175,944 for the table owner, 371,208 for all lookup storage, and conservatively allows two additional 57,856-byte projections even though service retains neither. Adding the 56-byte service owner gives 2,662,920, leaving 1,531,384 within 4 MiB. Reserve 512 KiB of that remainder for shared budget-map growth and 256 KiB for retained local lineage/startup values. This still leaves 744,952 for global stack, timer, identity/channel metadata and allocator rounding. The startup verification phase runs before table construction and before listeners/peer workers start. It has at most 65 signed authority frames and keys, not directory-sized state. The temporary frame slice has 65 × 24 = 1,560 bytes of headers; frames alias the already cloned trust records rather than cloning again. Verification maps, prefix-key arrays and parsed/signature working values are bounded by that lineage and verification work. They are startup scratch, not a retained table or per-link owner.
Routing arrays, exporters, lookup payloads, ticket slots, dispatcher inboxes and supervisor wait cases all use fixed inline storage. The service owner itself adds no growing map or Alternatives slice. Budget is the only new composition map/slice storage. At full route occupancy, it has three routing resource entries, 32 exact-link keyed entries and two-part leases. Logical entries are 32 bytes for resource usage, 48 for keyed usage, and 48 for a resource limit. Exact-link key strings need at most 18 printable bytes on this toolchain, conservatively 32 allocated bytes each. Reserve admission's transient delta maps have at most two resource entries and one keyed entry per route call. The service's shared budget has 24 resource limits and at most 784 active keyed entries across all default keyed resources, including the 32 routing entries. The 512 KiB global data envelope conservatively covers the shared map entries, key strings, bucket/group overhead and old/new growth overlap, not just map headers. Closed leases clear their parts slices and remove live keyed entries; bounded map capacity can remain until service teardown. Repeated epochs cannot grow the maximum live cardinality. No route transcript or update queue is retained.
Per-link engine plus the 16 KiB transient workspace is 256,368. Adding the 1,400-byte supervisor cases, 160-byte admission wait, all listed lease/identity, channel/link/dispatch metadata, eight tickets and eight Admission values, and the 160-byte two-part BudgetLease gives a conservative 262,624-byte subtotal. This even includes baseline Link fields again. The remaining 261,664 bytes in 512 KiB cover bounded call stacks, context/timer objects, frame-I/O transients, reflection select scratch, finalizer closure, setup key and allocator rounding. The separate 32 KiB per-link control envelope covers dispatch/ticket/control bookkeeping; the 64 KiB global control envelope covers shared ticket metadata and global maintenance control. Neither is an extra route payload pool. Mux channel buffers and copies remain inside the unchanged 6 MiB peer-mux charge.
Workers, timers and aggregate charges
| Owner | New workers | Routing timers |
|---|---|---|
| Per exact link | One service setup/runtime supervisor, one reader, one ordered writer and one peer dispatcher, total four | Initial exchange, writer refresh/change and one reusable nearest-ticket timer; up to two stream frame-completion/write deadline owners, total five |
| Global table | One joined maintenance owner | One nearest-expiry timer |
| Admission tickets and route channel holds | Zero additional workers | Zero per-ticket/hold timers |
At 32 links this is 32 × 4 + 1 = 129 new workers and a conservative
32 × 5 + 1 = 161 timers. The setup deadline owner is canceled before the
runtime timers start, not hidden as a sixth concurrent routing timer. The
existing directory and optional-channel settlement workers, mux workers,
transport/drain owners and Go runtime machinery remain baseline. None is
removed, renamed or counted as a route replacement worker. The initial timer
stops after successful exchange, and the ticket timer stops while idle.
The real reservations are 4 MiB + 32 × 512 KiB = 20 MiB data and
64 KiB + 32 × 32 KiB = 1,114,112 control bytes. Resource limits and shared
aggregate caps reject the 33rd runtime, duplicate exact-link keys and
incompatible aggregate combinations atomically. Frozen constants and mux caps
were not increased. As before, directory and peer-mux maxima cannot all coexist
under 512 MiB data; no simultaneous-maximum claim is made.
Real line and diamond tests prove route exchange through signed normal-peer TLS and the production mux, selected paths and live selected-only exports, live WITHDRAW after branch loss, bounded alternatives and retained direct-only listing. Successor replacement tests hold both L2 initial ENDs and exercise stale L1 claims/mutations/failure/close with different directory/route OPEN parity. Unknown-origin SET, required-stream failure, READY rollback, delayed reader join and reentrant table-fatal tests cover the remaining service boundary. These regressions live in routing, peer and service. Circuit bootstrap and fixed-attachment sessions, retained recovery, production remote application access, authorization and restricted pairing build on this composition; see the circuit status. Package, shipped-process and deployment-host checks cover different behavior; selection follows the test policy.
Consumer extensions
Table.RecheckCandidate is used for exact production selection barriers, and
Table.ReserveRestricted serves the restricted pairing consumer. See remote selection
and routed pairing
for current composition.
Routing stays a RAM path projection, not a trust decision or a carrier. The production service contract requires a bounded exact-token RecheckCandidate operation for pending gateway ready/tunnel admission. It compares the captured candidate's origin, path, revision, token identity, expiry and exact physical-link provenance using the existing ReservePair validation, but creates no ticket/hold and does no I/O. A current selected candidate with the same root is not a substitute for that token. Rechecks do not renew the sixty-second candidate expiry.
The restricted pairing carrier requires a separate typed ReserveRestricted path to the existing eligible mux. Its single-channel capability is not a relay pair or a relationship-ID opener. Use the existing peer/store/table admission order, candidate complete-suffix check and stable-root lookup. A transferred channel hold outlives the setup admission ticket, stays tied to the exact physical link and releases only after joined native settlement. Both extensions are present on the current joined source. There is no new on-wire polling, export field, route family, address, trust or endpoint publication. Selected refresh remains twenty seconds; expiry remains sixty seconds. No route change triggers a pairing check or extends any carrier or reliable-session deadline.
Production topology evidence
Routing consumes an eligible exact READY link regardless of which neighbor
initiated TCP. TestProductionTopologyOutboundOnlyOriginOneAndTwoRelays now
proves fresh authorization and application traffic toward an origin with no
listener/address over its outbound connection. The relay has no reverse dial
address. TestProductionLifecycleDiamondPeerRemovalRetainsApplication composes
local selected-peer removal with production application recovery over an
alternate, not a relay-chosen suffix.
The current bounded lookup/candidate/revision/change projection is a private backend input, not an EzHub route inventory operation. Eligibility, live READY links, directory publication and route availability must remain separate in any later local view. See service backend owners and service tests for composition and regressions. Deployment-host NAT/firewall compatibility is a separate scope from package or terminal checks.