docs/internal/agenthub-circuit.md
AgentHub circuit v1
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.
Status and boundary
Production composes signed bootstrap, fixed DATA/ACK sessions, authenticated attachment replacement, ciphertext replay, automatic entry-only retry and endpoint application consumers. The private contract is implemented. Circuit and service tests own component and composed runtime regressions. The test guide describes validation selection and isolation, not historical acceptance results.
The relay handoff is the transport input. Literal fixtures and the DATA/control sections below own frozen bytes. The recovery design owns quarantine, replay/live sequencing and fixed grace. Bootstrap and Session role anchors, Ready-relative bootstrap expiry, scoped proof/provider lifetime and joined release have durable regressions alongside the circuit package.
The parent has accepted the old_reset invariant disposition. A G1 control
reader cannot run after G2 LIVE because all four G1 I/O workers must join before
G2 installation. Keep both independent mandatory assertions: hold an actual
authenticated G1 RESET reader and prove it blocks G2 installation until join;
then prove direct post-join stale-token classification cannot mutate G2. This
neither claims the impossible event ran nor changes RESET/retirement semantics.
A circuit proves Hub possession and establishes RAM-only control material. It carries opaque bytes. Only inner endpoint TLS and the endpoint ACL authorize application access. For A through B to C, A/B and B/C Peer relationships suffice. A/C need no Peer, remote-head approval, invitation, admission or ACL grant. A need not publish an endpoint. Neighboring Peer succession policies stay exact.
Each endpoint uses its own verified learned-directory selection for the other endpoint's immutable attachment stable root. No remote lineage crosses relay setup, response, a cleartext preface or bootstrap TLS. No new trust store, persistent pin, authority-decision row or approval queue exists. Missing local proof makes this attempt unavailable. It does not trigger discovery or pairing.
Production installs the endpoint application consumer; new and reattach offers without an explicit bounded consumer are denied. Route OK permits quarantined bootstrap only. Bootstrap itself creates no idle accepted circuit, fake application EOF, debug/admin interface, endpoint socket dial or remote gateway availability; those arrive only through the endpoint consumer and carrier below. Direct entry-equals-origin bypass and passive pairing recovery are unchanged. The bootstrap and fixed-session sections have no ATTACH handler, replay, route retry or 65-second timer; the recovery sections own those. Circuit framing and public EzAgent application JSONL are unchanged. The separate private configuration contract carries admission policy. SQLite schema and dependencies are unchanged.
Local proof and fresh provider contracts
The shared declarations are in directory/circuit_types.go,
records/circuit_types.go, store/circuit_types.go,
hoptls/circuit_types.go and circuit/types.go. They publish interfaces and
opaque method sets without accepting implementations. Zero handles are unusable.
The bootstrap owners implement the first four interfaces and the bootstrap handle.
LearnedDirectory.ResolveCircuitAuthority(ctx, root, reserve) implements
directory.CircuitAuthorityResolver. Its result is
*directory.CircuitAuthoritySelection. Before scanning, parsing, copying or
waiting for the directory lock, reserve directory.CircuitAuthorityBytes,
4 MiB. Reservation is bounded local work with no I/O or worker. On any error,
release and return no handle. Retained catalogs remain separately charged.
Under the context-aware directory lock:
- Check shutdown, cancellation and resource-limit/quarantine state.
- Ask
LearnedState.CircuitAuthorityProjection(root)for the one selected maximal verified authority head and generation. It implementsrecords.CircuitAuthoritySelector; false rejects absent, stale, fork-affected, ambiguous or resource-limited state. - Examine only complete verified authority bundles for that root in the retained outbound selection. Catalog construction already verified their scoped signatures and ordered genesis-to-head dependencies. Do not redo an uncharged whole-directory verification or use an endpoint binding as a proxy for authority availability. An entry with no endpoint still contributes its authority through synchronization.
- Compare ordered signed-content digests, not receipt order or ECDSA signature bytes. Identical chains collapse; proper prefixes do not compete with a longer selected chain. Return only the complete maximal chain matching the learned-state head and generation. A sole stale prefix when the learned head is longer fails. Incomparable chains, a fork, multiple stable roots using the same head, or any conflict affecting this root fail. Do not pick the first bundle or highest numeric generation across branches.
- Copy one complete lineage and head into the charged attempt owner. At most 65 records of at most 32,914 bytes retain 2,139,410 frame bytes. One-frame parsing scratch, bounded digest/container storage and head copies fit the remaining 4 MiB charge. Never expand all bundles simultaneously.
- Capture the directory instance and its current publication notification token. No token registry, durable epoch or extra per-attempt map is needed.
selection.BorrowHead(ctx) returns a *directory.CircuitAuthorityBorrow or an
error. Only one live borrow per selection is supported; a second request fails
without allocation. The bootstrap owner acquires it before constructing a
provider and holds it through every provider load, the TLS constructor's return
and credential erasure. Only then does that owner call idempotent Release().
No provider-return defer may release this handshake lifetime hold early.
borrow.Head(ctx) returns an independent public CircuitAuthorityHead or an
error. The selection's frames and head stay immutable. At most one returned
head copy is retained by the provider at a time. The provider reduces the first
copy to fixed root/head/generation and SHA-256 comparison material, clears its
SPKI, and drops that slice before loading fresh credentials or asking for the
recheck copy. After successful recheck it transfers the second SPKI allocation
into the TLS AuthorityPin without cloning it. Failure clears the recheck copy
and erases any fresh credential. Neither a nil selection nor a
nonnil zero wrapper can invoke a nil private binding: exported guards reject
nil contexts, nil/zero handles and canceled contexts. Nil/zero borrow Release
is a safe no-op; Head and Recheck reject unusable handles. The concrete
bindings additionally reject released, closing, closed and stale selections.
The wrapper's private binding is installed once and never cleared or replaced,
including at Close/Release. Mutable lifetime state stays synchronized inside it,
so a concurrent wrapper call cannot race a binding pointer reset.
selection.Recheck(ctx) takes the same context-aware lock, checks the instance
is live and the publication token is unchanged, and repeats selected-root
usability checks. It performs no callback, I/O or worker creation. This token is
conservative: any intervening publication invalidates it, even an unrelated
update or an ABA change back to the same chain. That can deny a circuit during
directory churn; it cannot accept a changed selection. A later optimization
needs its own bounded ABA-safe proof, not a looser head comparison.
Each side rechecks immediately before writing its own confirmation. That
successful check is the local selection linearization point. No directory or
store lock is held over TLS or network I/O. A change afterward is not retroactive
approval of a different head. The attempt still binds the exact verified head.
Close() atomically enters closing under the selection's bounded owner lock.
That seals new borrows, Head calls and Recheck calls. Storage is fixed: one
borrow slot, one Head-read slot, one Recheck-read slot and one close completion,
with no borrower registry or per-read allocation. Concurrent extra Head/Recheck
calls fail without starting work. Read admission uses the selection lock, then
releases it before taking directory/records locks, and checks closing again
before returning. No selection lock nests a store or network operation. Close
joins the admitted reads and the single TLS lifetime hold, then marks the handle closed,
invalidates/clears its token/head/frames and returns the proof charge. Concurrent
Close calls join the same completion without spawning a worker. A previously
issued head copy does not outlive its charged borrow. Bootstrap must abort and
join TLS before releasing the borrow and calling Close. Calling Close
synchronously while retaining one's own borrow would deadlock and is forbidden.
Closing from another owner waits for the bounded handshake to join; it does not
release storage under that handshake or introduce a cancellation worker.
Store checks borrow.Head(ctx) before credential loading and again immediately
before returning material to TLS. Failed checks erase any freshly loaded
operational signer/material. Closing wins a check-or-close race if it seals the
head before that check. A load returned just before closing remains held through
TLS credential cleanup; final invalidation cannot complete until that lifetime
hold joins. Thus no operational credential can reach TLS after final selection
invalidation. A directory publication change has the separate conservative token
semantics above, with no retroactive network-disclosure guarantee or lock held
over TLS. Frames stay RAM-only and do not install trust.
store.CircuitTLSProviderFactory changes the existing circuit-only provider
constructors to take *directory.CircuitAuthorityBorrow, not a genesis ID or a
plain copied head. Factory construction does not load credentials or acquire
another borrow:
| 1 | CircuitBootstrapClientTLSProvider(borrow, securityTime) hoptls.CircuitBootstrapClientProvider |
| 2 | CircuitBootstrapServerTLSProvider(borrow, securityTime) hoptls.CircuitBootstrapServerProvider |
Each provider invocation loads fresh local operational credentials, complete
local lineage and persisted security time. It validates local root/head/generation
consistency and uses only the charged borrow's remote head as the operational
chain check. Nil, zero, released, closing, closed, stale or canceled handles
fail before fresh material is returned for credential disclosure.
It never calls loadHubPeer. Existing peer providers still call that loader and
require active eligibility and exact accepted successor head. Other TLS roles,
certificate profiles, security-floor persistence and credential erasure do not
change. No legacy circuit constructor accepting a direct-Peer ID remains; the
store implements the factory.
The strict circuit TLS role remains ez-agent-hub-circuit/1, mutual TLS 1.3,
no resumption, exact operational chain, effective security time and proof of
private-key possession. CircuitBootstrapConn.LocalCircuitAuthority() supplies
the exact local authenticated head/generation used by that handshake, not a
second independently loaded credential. Compare it against the freshly captured
local lineage and the attachment role root. The local AuthorityLineage store
projection supplies the complete local chain; a concurrent local authority
change that makes these disagree fails rather than splicing snapshots. The TLS
peer must equal the remote selected head, generation and SPKI. Store uncertainty
and security-floor persistence failure retain their typed cause for the fatal
service owner; do not flatten them into endpoint denial or a retryable proof
miss. New/reattach denial is relay CodeDenied, malformed circuit setup/response
is CodeProtocol, resource exhaustion is CodeLimit and setup expiry is CodeTimeout.
After route OK, bootstrap failure aborts the attachment and returns a redacted
local error; no new relay response or application error frame is invented.
Relay setup and bootstrap bytes
All integers are unsigned big-endian. ASCII domains below include their explicit trailing zero byte. There is no string normalization, varint, optional field, negotiation or trailing padding. Reserved bytes must be zero. IDs, attempt and nonces must be nonzero; both nonces must differ. Local code draws each nonce from cryptographic randomness. The full attachment path has 2 through 8 unique nonzero stable roots; its first/last roots are entry/origin, and its mode is new. Reattach is denied before reservation or TLS.
Relay opaque setup is exactly 8 bytes 4148434201010000. Origin response is
exactly 8 bytes 4148434201020000. Both mean only circuit v1/new bootstrap work
with this fixed contract. They carry no proof, lineage, pin, session secret,
endpoint service outcome or authorization. Relay's existing 512-byte ceiling is
unchanged; extra bytes or nonzero unused opaque tails fail circuit validation.
The response is checked before TLS. No separate preface exists.
Bootstrap messages run inside TLS on bulk. Each starts with U32BE payload length,
then AHCB, version U8 1, kind U8, role U8 and reserved U8 0. Role is entry
1 or origin 2. No message may follow the expected one except the next
specified message or TLS close-notify. TLS does not carry authority lineages.
HELLO, kind 0x10
The payload is exactly 252 bytes; the complete frame is 256 bytes.
| Payload offset | Bytes | Meaning |
|---|---|---|
| 0 | 8 | AHCB/version/kind/role/reserved header |
| 8 | 32 | Endpoint ID |
| 40 | 16 | Fresh immutable relay attempt |
| 56 | 32 | Entry stable root |
| 88 | 32 | Entry proved authority head |
| 120 | 8 | Entry head generation |
| 128 | 32 | Origin stable root |
| 160 | 32 | Origin proved authority head |
| 192 | 8 | Origin head generation |
| 200 | 4 | Segment limit, 65,536 |
| 204 | 4 | Unsent bytes, 2,097,152 |
| 208 | 4 | Unacknowledged bytes, 8,388,608 |
| 212 | 4 | Receive bytes, 2,097,152 |
| 216 | 4 | Combined segment-slot limit, 4,096 |
| 220 | 32 | Sender nonce |
Both HELLOs have identical fields except role and nonce. All common values must match local immutable metadata, local lineage and selected remote head. Each side validates the opposite role, not just valid syntax. Generation zero is legal only for a matching genesis head. Limits are exact v1 constants, not attacker-chosen buffer sizes. Fixed arrays suffice for reading/encoding; check the length before reading a body. Fragmentation is legal. Truncation, unknown version/kind/role, wrong reserved byte, invalid limits and trailing plaintext fail.
Transcript, exporter and derivation
The canonical transcript is:
| 1 | ASCII("AgentHub-circuit-transcript-v1\0") |
| 2 | || U8(1) # relay ModeNew |
| 3 | || U8(path root count) |
| 4 | || each full path root, 32 bytes in entry-to-origin order |
| 5 | || complete entry HELLO frame, including U32BE length |
| 6 | || complete origin HELLO frame, including U32BE length |
Its maximum is 801 bytes. H = SHA256(transcript). The exporter context is
exactly H, 32 bytes. The existing role-specific API
ExportCircuitBootstrap(H) returns exactly 32 bytes E under the unchanged label
EXPORTER-AgentHub-circuit-bootstrap-v1. Hop, invitation and pairing material
are rejected, not substituted.
| 1 | session ID = HMAC-SHA256(E, ASCII("AgentHub-circuit-session-v1\0") || H) |
| 2 | control K = HMAC-SHA256(E, ASCII("AgentHub-circuit-control-v1\0") || H) |
E is cleared immediately after derivation, including errors. K is an opaque
*ControlMaterial, not copied into service or a log. It owns one session ID and
transcript hash and provides bounded MAC(input). Inputs above 1,152 bytes
fail before copying or hashing. Codec/session owners supply exact domain bytes. Clear() erases K and all owned material after borrowers
join. String/GoString must redact the object. The frame/transcript/nonce owners
clear their buffers on success and failure. Public fixture secrets are synthetic,
not operational secrets.
CONFIRM, kind 0x11
Payload length is exactly 104; frame length is 108. After the 8-byte header, append H, session ID and proof, each 32 bytes. The sender's proof is:
| 1 | HMAC-SHA256(K, |
| 2 | ASCII("AgentHub-circuit-confirm-v1\0") |
| 3 | || U8(sender role) || H || session ID) |
Use constant-time proof comparison. Role reflection, wrong session/hash, substituted endpoint/attempt/root/head/generation/path/limit/nonce or wrong exporter fails. No failed confirmation produces a successful result or clean EOF. There is no remote approval or evidence message.
Exact TLS retirement and transfer
The relay bulk adapter implements net.Conn solely for the closed TLS constructor. It forwards read/write deadlines to Bulk, reports fixed local diagnostic addresses from immutable role/attempt metadata, and never resolves/dials an address. SetDeadline sets both directional deadlines. Close invokes the one attachment Abort owner, once. TLS constructors consume this adapter on every outcome; do not also defer a raw attachment close as if ownership were retained. Relay retains revocation authority throughout.
The adapter caps each raw read at the current TLS record boundary. It stages only the five-byte TLS header, then lets TLS read at most that record's remaining payload. It never uses bufio, a speculative read or a read that crosses into the next record. TLS handles record type/version semantics; the adapter rejects record payload lengths above 16,640 before reading/allocating their body. The maximum record including header is 16,645 bytes. Input and output each have an absolute 256 KiB cumulative bootstrap wire ceiling, including headers and handshake traffic. Exceeding either ceiling aborts. This bound covers finite TLS work, not a claim about Go heap or RSS. There is one reader and one writer per phase. No raw segment reader exists during TLS.
The handshake and retirement use one absolute 10-second deadline starting at
Ready. Relay records Attachment.ReadyAt() with its monotonic component
immediately before publishing Ready. It is zero before publication and immutable
afterward, including through settlement. Bootstrap derives its deadline from
that timestamp, never from worker execution time. If execution is delayed to or
past expiry, it fails before proof reservation, phase workers or TLS work. ReadyAt
is local lifecycle evidence and adds no wire field, timer or worker.
The existing TLS constructor clears its handshake deadline on success;
the bootstrap owner immediately reapplies the original absolute deadline before
HELLO I/O. HELLO progress does not extend it. The sequence is:
- Entry writes entry HELLO. Origin reads, compares all fields, then writes origin HELLO. Entry reads and compares all fields.
- Both derive the same transcript/exporter/material. Entry rechecks its local remote selection and writes entry CONFIRM.
- Origin validates entry CONFIRM, rechecks its own remote selection and writes origin CONFIRM. Entry validates origin CONFIRM.
- Origin calls circuit-only
CloseBootstrapWrite(). This uses TLS CloseWrite to send close-notify, without closing the supplied adapter. Origin then reads one byte through TLS and requires zero bytes plus authenticated EOF. - Entry reads one byte through TLS and requires zero bytes plus authenticated
EOF from origin, then calls
CloseBootstrapWrite(). Extra application data, unexpected alerts, truncation or transport EOF fails. No relay FIN is issued by this TLS CloseWrite. - Each side joins/retires its TLS phase cancellation callback, checks the lifecycle parent again, clears both bulk deadlines, and verifies the adapter is at a record boundary. Only then disable its adapter-close capability and discard the TLS connection. Go TLS does not expose an API to erase its private cipher state; releasing those references is distinct from explicitly clearing the circuit-owned exporter, K, nonces and encoded buffers. No ordinary TLS Close is called on this success path. Close/Abort on failure still abort the attachment.
- Install the result's raw-attachment cancellation owner before returning a BootstrapResult, then transfer the original Bulk to the single segment owner through Take. The result retains no TLS-close authority. The adapter has no prefetched raw tail. TLS may have buffered plaintext from its final record; the explicit EOF read rejects any such application bytes. Record-bounded reads mean it cannot buffer any following raw DATA in its ciphertext input.
Thus an origin close-notify and following raw segment may be coalesced by relay
or the underlying socket without losing bytes. Raw bytes before the sender's
TLS close-notify fail TLS retirement. Neither side emits raw segments before
its own retirement completes. No concurrent TLS/raw readers, old TLS deadline
or obsolete TLS cancellation callback survives. Retirement failure or
cancellation at any step aborts, joins and clears. CircuitBootstrapRetirement
is an interface for these two circuit-only methods, not a generic detachable TLS
connection, and does not weaken any other role's Close/Abort behavior.
Bootstrap uses no relay control message. A peer that has completed its own retirement may enqueue authenticated session controls while the other endpoint finishes retirement. Relay's bounded lane storage owns them until the session reads them; cross-lane arrival alone is not a protocol error. There is no bootstrap control reader racing the later session reader. The session authenticates every borrowed message and releases it on every outcome.
Reservation, acquisition and cancellation
The common exported declarations in circuit/types.go bind entry, bootstrap,
result, reservation, origin acquisition, explicit consumer and session. The
bootstrap owners implement them with internal fixture composition; the
fixed-attachment reliable session is described below.
ReserveEndpoint(ctx) atomically reserves one endpoint count, 32 KiB fixed DATA
and 16 KiB CONTROL against the service budget before queue/TLS allocation,
proof work or origin TakeAttachment. Directory proof additionally reserves
4 MiB; relay retains its own 96 KiB data and 8 KiB control charge. Failed
reservation owns nothing and performs no audit I/O or detached callback work.
service/circuit_types.go declares ResourceCircuitMemory and
ResourceCircuitControl. The protected configuration supplies their count and
byte budgets independently of logical circuit admission. Scoped proof bytes use
the existing data ResourceDirectory
row, counted once per live selection. Constructors validate configuration only;
no worker, queue or TLS/provider load starts without a charged request.
A Reservation has two idempotent release gates. Close() marks circuit work,
secret clearing and borrowed-control release joined. ReleaseAfterSettlement()
marks attachment/pair settlement joined. Actual capacity is returned only after
both. Before an attachment exists, the orchestration owner marks settlement
itself. This keeps one count/byte charge through bootstrap, result and session.
Taking a payload/result transfers the pointer owner, never creates a new charge
or duplicate release defer.
Entry.Start reserves first, calls one relay.Entry.Start with the selected
candidate and setup, validates the response, then calls Bootstrapper. The caller
context remains the attachment lifecycle parent. Do not cancel a setup-only
context after Start returns. Before BootstrapRequest transfer, Entry errors
abort and synchronously join Attachment.Wait outside any callback/admission
lock, then mark settlement and release. Bootstrapper takes the same entry-only
settlement obligation on transfer and must complete it on every failed call.
No attachment-free error path may return while still owning unsettled work.
After success the obligation belongs to the RoleEntry BootstrapResult. Its terminal Wait joins its own workers, clears material and calls Reservation.Close, then synchronously calls Attachment.Wait and ReleaseAfterSettlement. Take moves that obligation together with the attachment and reservation into SessionInput. The consumed result cannot retain a settlement waiter or join/release the new owner. A terminal RoleEntry Session.Wait performs the same order. Session Start failure and bootstrap fixture consumers must also complete that order after taking an input, including aborting on failure so relay settlement can progress. Wait collects circuit and relay errors rather than hiding either. Clean success waits for the circuit close protocol and both relay lanes to settle; it does not abort or fabricate EOF to shortcut a join.
RoleOrigin BootstrapResult.Wait and Session.Wait join only circuit work, clear material and mark Reservation.Close. They never call Attachment.Wait or mark ReleaseAfterSettlement; relay owns that join and invokes OriginSettlement. This role distinction prevents relay's acquisition.Wait from waiting on itself. There is no detached goroutine waiting for entry settlement. Terminal Wait uses the caller's existing counted worker, and repeated/concurrent Wait calls join one completion without spawning waiters. The maximum remains 8 workers per endpoint, with zero additional settlement workers.
Service shutdown cancels the existing attachment lifecycle, then joins the tracked entry fixture-consumer invocation. That invocation owns the current result/input and must call its role-correct terminal Wait. Tracking the bounded invocation through Take avoids a second owner of the attachment or a stale result in a service shutdown list. Shutdown does not return the circuit charge until that invocation has joined Attachment.Wait and marked settlement. This bounded fixture path is internal; production composition uses the endpoint consumer.
Origin Admit validates mode/setup/new-admission evidence, requires the explicit fixture consumer, reserves before TakeAttachment, and returns promptly with an abortable acquisition and the fixed response. It does not wait for Ready, bootstrap, a socket or application work inside Admit. If it takes a handle then fails, it returns that acquisition with the error so relay can revoke and join it. A fully unwound error returns zero acceptance. The charged acquisition owns one worker that selects Ready, attachment Done or its Abort signal.
The Admit context is borrowed admission/setup scope only. The baseline cancels it after OK publication. Do not parent successful origin work to that context. The acquisition creates a normalized lifecycle context from its Abort signal and attachment Done, which already reflects service/link revocation. It owns and joins that bridge. Relay rollback aborts it before Ready; after Ready it runs bootstrap and the bounded Consumer. It must abort the attachment on failure so the relay supervisor wakes and can call acquisition.Wait. Wait joins only circuit/consumer work, never Attachment.Wait or the relay supervisor that is joining it.
relay.OriginSettlement is the narrowly required internal prerequisite.
Relay must invoke ReleaseAfterSettlement() on acquisitions implementing it
after acquisition.Wait, pump/user joins, borrowed-control release and incident
pair settlement, before returning the relay attempt charge. Rollback before a
binding exists also invokes it after any partial settlement. Existing acquisitions
need not implement it. No relay field or JSONL lifecycle changes. The callback
is bounded local idempotent release only, with no I/O, worker, wait or relay
reentry. Relay wires this optional callback on established FIN/abort, binding rollback,
and empty/partial rollback. Repeated binding Wait/run calls cannot repeat it.
The callback precedes returning the relay attempt charge.
BootstrapRequest transfers its attachment, reservation and role-specific
settlement obligation on every outcome. Entry.Start and originAcquisition.run
install a package-private settlementRole anchor in the request. Bootstrap rejects
an invalid anchor or a public Role mismatch before proof, phase-worker or TLS
allocation. TLS client/server selection, transcript role and cleanup use only
the anchor; a wrapper can neither substitute the TLS role nor redirect settlement
by changing public Role. An unanchored request is invalid and cannot acquire
entry settlement authority. Callers outside the circuit package must obtain
owned requests through the entry/origin constructors, not synthesize them.
An entry error aborts and is fully joined through Attachment.Wait before
Bootstrap returns, then marks settlement. An origin error requests circuit
release but leaves the settlement mark to relay, never waiting inside the
acquisition relay must itself join. A successful BootstrapResult owns the ordered
raw stream, material, lease and the same immutable role-specific terminal
obligation. Result.Role, result Wait and Take use that anchor; Take preserves it
in SessionInput.
Its single-use Take first retires the bootstrap cancellation owner, checks the
parent, and transfers a SessionInput with the unchanged attachment, original
Bulk, lifecycle Parent, material and reservation. The consumed result cannot
abort, clear or release the new owner's resources. Abort/Wait before Take must
wake/join and request release. A failed Take remains abortable/joinable.
Every phase normalizes arbitrary caller contexts before using WithCancel, WithDeadline or AfterFunc. A custom context with Done but no AfterFunc support must not create an implicit unjoined propagation worker. Use a context rooted in Background plus one explicit charged bridge selecting parent Done, attachment Done and owner-stop; join the bridge before releasing or transferring its phase. Preserve parent deadline/Err behavior. A standard parent may use the existing joined cancellation helper. TLS sees only the normalized context. Cancellation wakes blocked I/O immediately; it does not release reservations. Transfer has no uncancellable gap: join the old phase, check Parent, install the new phase before raw I/O, and abort if Parent was canceled in between. Origins may keep their acquisition lifecycle bridge through Consume, but retire the TLS abort callback before raw transfer. All waits occur outside shared locks.
Circuit state locks never nest directory/store/admission locks. The proof path uses directory then records-state locks only for local reads. Reserve callbacks run outside those locks. The existing relay admission order stays peer gate, store identity barrier, manager, directory admission, routing table. No network I/O, crypto signing, joins or consumer callback runs under those locks.
Finite resource proof
These are structural/live-owner bounds, not hard Go heap, stack or RSS limits. Class budgets default to 16 GiB DATA and 512 MiB CONTROL and can be raised. They account admitted ownership, not startup allocations or OOM safety. Counts and byte budgets intersect; a high logical count does not promise simultaneous full replay windows. There is no aggressive RSS memory-pressure monitor.
| Per endpoint owner | Bound and charge |
|---|---|
| Ciphertext protocol envelope | 2 MiB unsent + 8 MiB unacknowledged + 2 MiB receive = 12 MiB, allocated on demand |
| Queue storage | Three demand-grown FIFOs; each immutable payload and node reserve payload capacity plus 256 bytes before allocation |
| Native DATA I/O | TX emits a 24-byte header and borrowed payload without a staging copy; RX validates the header, charges the exact body, then copies into the separately charged RX queue and releases the temporary body |
| Fixed DATA reservation | 32 KiB owner/phase metadata, separate from retained allocations and TLS preparation |
| Fixed CONTROL reservation | 16 KiB for fixed controls, material and lifecycle state |
| Remote proof | Separate 4 MiB charged scoped selection until rechecks/provider join/retirement complete |
| Relay | Separate 96 KiB data and 8 KiB control per local relay owner |
| Endpoint count | limits.circuit_admission.global defaults to 524,288 process-wide logical entry/origin owners; trusted-key policies and service budgets also apply. Transit has no circuit session or replay cache |
| Workers | At most 8 per endpoint including acquisition/entry fixture-consumer supervisor, explicit custom-context bridge and all phase work; terminal entry settlement uses that existing caller, zero additional settlement waiters; no worker per frame, timer, nonce, callback, borrow or segment |
| Timers | At most 4 across bootstrap/lifecycle phases; session owns exactly one reusable ACK/liveness/close/parent-deadline scheduling timer, no per-item timer; relay timers remain separately charged |
direction.go retains no free-node cache or maximum-sized slot arrays. Empty
queues retain no payload or node allocations. The 4,096-slot total and TX
3,072/RX 1,024 subcaps remain protocol invariants. Payload capacities count
against the 2/8/2 MiB queue limits; node overhead also counts against the shared
circuit_ciphertext budget, which defaults to 256 MiB per Hub. This budget is
not the full 12 MiB replay envelope multiplied by possible sessions.
Bootstrap TLS/provider work and proof borrowers have separate charged owners
and join before transfer. Fixed control slots still coalesce bounded values;
relay-owned borrowed controls retain their separate charge until Release.
SessionConn adds 16 KiB DATA/16 KiB CONTROL fixed metadata and charges actual
buffers to circuit_ciphertext. The registry prepays metadata capacity but
allocates rows and indexes lazily. See dynamic retained-buffer ownership.
Small writes may exhaust the finite slot cap before byte caps. Backpressure, not silent eviction or unlimited metadata, is required. The session does not merge or append to accepted immutable chunks; callers may combine bytes before Write. Move one immutable payload owner from unsent to unacknowledged without copying or double charging. A receiver reserves space before accepting a frame or advancing its cursor. Never evict unacknowledged ciphertext. TX retains the borrowed queue owner through I/O; RX charges its temporary body before allocation. Fixed controls coalesce into bounded slots, not an unbounded message queue. No blocked DATA I/O holds a control/state lock.
Frozen DATA and control bytes
All integers are unsigned big-endian. Direction 1 means entry to origin;
direction 2 means origin to entry. Roles remain entry 1 and origin 2. Counters
and cursors are U64. MaxCursor = 18446744073709551614, all-ones is reserved.
Zero is an empty ACK/final cursor, never a DATA sequence or probe serial.
Sequence exhaustion seals a direction at MaxCursor, never wraps to zero.
Diagnostic cumulative byte totals and local slot generations also cap at
MaxCursor and never wrap; exhaustion is terminal resource failure. Recovery has
its separate authenticated codec below and does not change these DATA bytes.
DATA on bulk
The complete frame is the 24-byte header followed by 1 through 65,536 payload bytes. There is no extra length prefix or trailer.
| Header offset | Bytes | Value |
|---|---|---|
| 0 | 4 | ASCII AHCD, hex 41484344 |
| 4 | 1 | Version 1 |
| 5 | 1 | DATA kind 1 |
| 6 | 1 | Sender role |
| 7 | 1 | Sender DATA direction, entry 1 or origin 2 |
| 8 | 8 | Sequence 1 through MaxCursor |
| 16 | 4 | Payload length 1 through 65,536 |
| 20 | 4 | Reserved zero |
Check the fixed header before reading the body. Unknown fields, wrong remote role/direction, reserved counter, zero/oversized payload, live gap or live duplicate is terminal protocol failure. A decoder parses exactly one frame; bytes following it are the next frame, not padding. Standalone literal decoding must consume the entire supplied frame. The maximum frame is 65,560 bytes. Native Session I/O needs no full-frame workspace: TX writes the fixed header then the borrowed payload; RX validates the header before charging and allocating its exact body. The standalone workspace codec retains its 65,568-byte caller workspace contract. There is exactly one bulk reader and one bulk writer. A valid reader may return its last payload bytes with io.EOF. A complete field is retained; EOF before a complete header or body is truncation. The next lane EOF is only a bounded transport observation and cannot substitute for authenticated FIN. Interrupted or truncated transport read/write errors, including errors with a positive byte count, retire the current attachment without committing Sent. Complete malformed framing, impossible cursors and internal queue/resource violations remain terminal; see retained lifetime.
DATA is opaque inner-TLS ciphertext, not a circuit-MAC message. The unchanged fixed attachment binds its bulk direction. Inner endpoint TLS detects payload substitution and alone authorizes the application with its ACL. DATA receipt, local writes and sending controls are not authenticated circuit liveness progress. No data-hash MAC, session preface or changed exporter is introduced.
Whole-message controls
Every control is one relay message. No stream length prefix exists. The header is 48 bytes, followed by the exact body below, then a 32-byte HMAC-SHA256 tag.
| Header offset | Bytes | Value |
|---|---|---|
| 0 | 4 | ASCII AHCC, hex 41484343 |
| 4 | 1 | Version 1 |
| 5 | 1 | Kind, ACK 1, PING 2, PONG 3, FIN 4, FIN_ACK 5, RESET 6 |
| 6 | 1 | Sender role |
| 7 | 1 | Referenced DATA direction |
| 8 | 32 | Exact bootstrap session ID |
| 40 | 2 | Exact body length |
| 42 | 6 | Reserved zero |
| Kind | Body | Complete bytes | Direction rule |
|---|---|---|---|
| ACK | U64 cumulative cursor | 88 | Opposite sender's DATA direction |
| PING | U64 probe serial, 32-byte nonzero random nonce | 120 | Sender's DATA direction |
| PONG | Exact PING serial and nonce | 120 | Opposite sender's DATA direction |
| FIN | U64 final cursor | 88 | Sender's DATA direction |
| FIN_ACK | U64 final cursor | 88 | Opposite sender's DATA direction |
| RESET | U8 reason, seven zero reserved bytes | 88 | Sender's DATA direction |
RESET reasons are protocol 1, cancelled 2, timeout 3, resource 4, transport 5. There is no free-text reason. RESET terminates both directions. Unknown reasons or extra bytes are invalid, including otherwise correct tags. No control is acknowledged except FIN; ACK, PING/PONG and RESET have no acknowledgement loop.
| 1 | MAC input = ASCII("AgentHub-circuit-control-message-v1\0") |
| 2 | || complete 48-byte header || exact body |
| 3 | TAG = HMAC-SHA256(bootstrap control K, MAC input) |
The domain is 36 bytes including zero. Cursor/reset MAC inputs are 92 bytes;
probe inputs are 124 bytes. The tag is excluded from its own input. Syntax,
exact expected remote role, kind-specific direction, session and constant-time
MAC verification all precede state effects. A valid MAC with an invalid
role/direction/session is still invalid. Wrong MAC/session/role/reflection must
not release bytes, advance cursors, refresh liveness or create EOF. Invalid
controls terminate the attachment; unauthenticated input earns no response.
Maximum supported control is 120 bytes, far below relay's whole-message ceiling
of 1,024. Material.MAC's unchanged bound is 1,152, not an invitation to accept
padding or unknown kinds. Every borrowed ControlMessage is released on
success, truncation, semantic/authentication failure, cancellation and shutdown,
before another receive or worker completion. Only fixed decoded values survive.
Queue acceptance, partial writes and cursor commit
session_types.go is the shared declaration owner. Three demand-grown FIFOs
contain at most 4,096 live segment nodes across TX unsent, TX unacknowledged and
RX. TX may use at most 3,072; RX may use at most 1,024. These subcaps leave
receive admission capacity even when tiny TX writes consume the transmit slot
limit. Slot pressure can backpressure before byte pressure. Each accepted segment
reserves payload capacity plus a 256-byte node allowance before allocation.
Empty queues keep no free-node cache or full-sized slot pool.
Public Write copies and accepts a prefix in chunks of at most 64 KiB, reserving
2 MiB unsent room and one slot before each copy. Each accepted chunk receives
the next sequence and remains immutable from that acceptance, including before
transmission. Caller mutation after return cannot alter it. No append to or
merging of accepted chunks is allowed. Large calls may block and return partial
n > 0, err != nil on cancellation/terminal failure; n counts accepted bytes,
not wire delivery or downstream execution. Zero-length Write returns 0,nil on
a usable open direction. There is one admitted public writer and one reader;
extra concurrent callers fail locally without allocation or a new worker.
CloseWrite takes the queue's bounded commit lock, seals the assigned final
cursor and rejects new writes. It interrupts any remaining unaccepted chunks of
a blocked Write with a partial closed-direction result, rather than waiting on
network room while delaying the close deadline. Read may return a partial payload. A slot is freed only
when its full payload has been delivered. Zero-length Read returns 0,nil while
usable and does not consume EOF or progress.
TX Begin reserves 8 MiB unacknowledged room, moves the same slot and payload charge from unsent to unacknowledged, and pins the one in-flight segment. No second copy or slot is created. Only after the entire encoded frame has been written does Commit advance Sent. Partial bulk writes continue at the exact remaining byte offset. Invalid counts remain terminal framing failures. Zero progress or a transport error, including n > 0 with an error, fails the frame without committing Sent. These emission failures retire the attachment and pin its immutable payload for authenticated replay. No later segment can begin until the current Commit or the joined replay owner reconciles the failed borrow. The borrowed payload remains charged through old I/O worker join; retirement keeps the payload charged after that join.
Authenticated ACK classification is exact:
- Cursor <= Acked is stale/repeated, including zero. Ignore it without byte release, cursor regression, liveness progress or deadline extension.
- Acked < cursor <= Sent advances acceptance, releasing only fully emitted covered slots and their one payload charge.
- The sole in-flight Started cursor may exceed Sent by one. ACK == Started is deferred until Commit because a peer can accept a frame before the local final Write returns. It frees nothing and counts no progress until Commit succeeds. Earlier sent segments remain retained under this deferred ACK; a separate possible ACK may still release them before that Commit.
- Cursor > Started, all-ones or an ACK for never-begun queued bytes is impossible and terminal protocol failure. An ACK deferred across a failed partial frame never releases it. Commit applies deferred acceptance exactly once.
RX validates the fixed header before charging and reading its exact temporary
body. It checks the next sequence and any known FIN bound, then waits for 2 MiB
receive room and a receive slot. It charges payload plus node overhead before
copying into the RX queue and then clears and releases the temporary body. Only
a completed copy commits Accepted. Neither incomplete body nor a blocked
admission advances it. ACK covers contiguous bounded receive acceptance, not
application execution, JSONL processing or inner-TLS success. There is no live
duplicate suppression. Delivered advances only for wholly consumed segments.
A terminal failure overrides pending EOF and wakes blocked readers/writers.
No I/O, consumer callback, MAC computation, allocation wait or join occurs
under a state/pool/queue/control lock. The injected clock's Now is bounded local
work and may be sampled at queue acceptance commit; it must never call back
into queues or block on session work. Reservation and payload copies are bounded local
work; queue locks never nest service/directory/store/admission locks.
ACK scheduling, liveness and fixed controls
One scheduler uses one reusable monotonic timer for the earliest ACK, idle PING, progress failure, pending close or recovery-grace deadline. SessionClock.Now cannot move backward. Tests supply a controlled clock; no sleeps, per-item timers or timer callbacks are part of the API. The scheduler is the sole receiver of the queues' one-slot Changed notification. It always re-reads snapshots, so coalescing loses no cursor change. Queue waiters use bounded local wakeups, not this notification.
ACK becomes due at 64 KiB newly accepted bytes since the last successfully admitted ACK, or 200 ms from the first outstanding acceptance, whichever comes first. Later acceptance does not postpone that first deadline. A pending ACK keeps the largest Accepted cursor. One writer sends controls outside locks. Before sending ACK, RX BeginACK pins the latest Accepted cursor and cumulative byte total. The writer encodes this pinned cursor, not an older pending-slot snapshot. On SendControl success, CommitACK records only that actual cursor; a newer pending cursor remains due based on its first outstanding acceptance. RX records acceptance's monotonic timestamp at cursor commit, using the clock passed to newEndpointQueues(SessionClock). ACKPendingSince comes from that instant, never from a delayed scheduler observation. Keep one timestamp for the first acceptance during an in-flight ACK, not a per-segment timer list; CommitACK moves it to the next outstanding interval. A failed transport send retires the attachment under the retained-lifetime rules and retains the ACK flight for the joined replay owner; it never commits ACK state. FIN forces its final ACK immediately, including cursor zero, without waiting for threshold.
Six fixed pending slots use dispatch order RESET, ACK, FIN_ACK, PONG, FIN, PING. Dispatch is a bounded round, at most one send from each nonempty slot in that order before the next round. RESET preempts any round. A replacement ACK cannot restart the round and starve FIN/PING. There is one fixed round index and no extra queue. At most one separate in-flight control is retained. ACK replaces only with a larger cursor; FIN and FIN_ACK each hold the fixed final cursor; PONG replaces with the newest valid probe; PING has at most one outstanding nonce. RESET seals ordinary requests. Slot generations compare send completions against replacement work so an old completion cannot erase a new ACK/PONG. Fixed six-slot priority cannot starve liveness indefinitely: a blocked physical writer reaches the 30-second deadline, while bounded runnable traffic keeps controls small. Relay's existing weighted control/data arbitration and unrelated-link isolation remain unchanged. No separate goroutine may wait on a blocked SendControl.
Initialize last authenticated progress at Start. Advancing possible ACK, first valid FIN, exact first FIN_ACK after local FIN send, fresh increasing authenticated PING serial, or matching outstanding PONG counts progress. Deferred ACK counts only at successful Commit. DATA, stale ACK, repeated FIN/FIN_ACK, unmatched or repeated PONG, stale PING, local I/O and malformed/unauthenticated input do not. RESET never refreshes progress. The attachment retires on authenticated resetTransport; other authenticated RESET reasons remain terminal.
After 10 seconds since last progress, queue one PING. Each endpoint's serial starts at 1, increases monotonically through MaxCursor and never reuses or wraps. Each new serial has a fresh unpredictable nonzero 32-byte nonce. A receiver tracks the highest peer serial. A repeated serial with a different nonce is protocol failure; exact repeat or lower serial has no progress and may be ignored. A newer PING queues its PONG and refreshes progress. Keep the highest serial and nonce only. There is one outstanding local probe. Its send timestamp is taken just before SendControl outside locks; its matching PONG may arrive before SendControl returns. On send error discard the sample and fail. On success use this monotonic timestamp, including bounded enqueue delay, as the RTT start. Progress does not erase an outstanding probe. A matched PONG clears it. If unanswered, replace it with a fresh probe only when another 10-second idle interval requires one, invalidating the old match. An old PONG cannot extend a deadline.
At 30 seconds since last authenticated progress declare attachment failure,
even if a PING cannot be delivered. At every state transition, an expired
liveness/close/parent deadline wins when Now >= deadline, before applying new
progress or close success. A delayed scheduler wake cannot admit a late PONG.
The first terminal transition wins concurrent races; controls accepted into
state before expiry may extend progress, not controls merely waiting to decode. PONG or other defined progress resets both
idle/failure deadlines; control traffic alone does not. RTT latest is the
nonnegative matching duration. First sample initializes smoothed; later samples
use smoothed + (latest - smoothed)/8, integer nanoseconds rounded toward zero.
Only successfully sent matched probes update RTT. RTT() returns one fixed
RTTStats snapshot and never resizes queues or alters thresholds.
Authenticated half-close and terminal ownership
CloseWrite freezes local final Assigned and starts its absolute 30-second pending-close deadline. Bulk writer drains/commits through that cursor, queues FIN, then calls bulk CloseWrite. Control FIN can arrive before final DATA because lanes are independent. Receiving the first authenticated FIN records Final and starts a 30-second deadline while final acceptance/response is pending, bounded by any earlier retained EOF-wait deadline. Replacement installation clears the physical EOF observation, not that bound. FIN before remaining replay DATA is legal and transfers the earlier bound to FIN completion without requiring EOF on the replacement. Final below Accepted, a differing repeated FIN or any subsequent DATA beyond Final fails. A repeated identical FIN is harmless but not progress. Final may be MaxCursor and may be zero. A lane reorder is not a gap.
When Accepted == Final, force cumulative ACK Final followed by FIN_ACK Final. FIN_ACK is eligible only after the final ACK's SendControl succeeds. Acceptance permits this response even if the application has not read the buffer. Read returns io.EOF only after delivery through Final with no terminal failure. It never infers EOF from bulk/control/relay closure. Bulk EOF with a known Final greater than Accepted is transport failure. Bulk EOF before control FIN is legal cross-lane ordering: retain one EOF observation at Accepted and wait at most 30 seconds for FIN. A FIN equal to that cursor can finish the close. A greater valid final exposes missing DATA, which retires the attachment under the retained-lifetime rules without extending the earlier EOF-wait deadline. Impossible or conflicting finals remain terminal. EOF itself permits no application EOF or liveness progress. Bulk EOF after a known accepted final is expected, but still does not prove application EOF. Local ACK and FIN_ACK can arrive before FIN send returns; record bounded pending confirmation and apply it only after successful FIN send. FIN_ACK must equal the local sealed final, require that FIN has begun sending, and release no payload itself. A zero final still requires both final ACK and FIN_ACK; track final-ACK observation separately from Acked zero. Mark this observation only for an ACK equal to Final received after FIN begins sending; that ACK may otherwise be stale and still counts no liveness progress. FIN_ACK does not substitute for a missing cumulative ACK, and impossible close cursors fail.
Local pending close completes after FIN sent, ACK Final observed and FIN_ACK Final observed. Remote pending close completes after final acceptance and final ACK/FIN_ACK successfully admitted. These absolute deadlines never extend with PING, ACK or DATA. A completed half-close has no close timer on the still-open reverse direction. Simultaneous close is two independent instances. Slow application reads do not extend a pending handshake deadline, but a completed remote handshake can retain bounded unread RX while the reverse half remains open. Liveness still applies. The same scheduler timer measures the fixed 65-second recovery grace without extending pending close deadlines; authenticated replacement, replay, entry retry and real-service recovery run under those deadlines.
Only after both directional handshakes complete and RX drains through its final cursor may control CloseWrite run, after bulk CloseWrite. Clean worker shutdown then consumes expected lane EOF and retains no live borrowed controls. Control EOF is expected once all required peer FIN/ACK/FIN_ACK messages have arrived, even if local RX delivery or the final local SendControl return is still pending. Retain one bounded EOF observation across that send-completion race; validate it against successful handshake commits, never shortcut those commits. If required inbound close messages are absent at control EOF, retire the attachment under the retained-lifetime rules; they cannot arrive later on that lane. Do not start replacement work after fully completed authenticated close. Start a final absolute 30-second transport-drain deadline at local control CloseWrite; missing lane EOF/Done cannot hang close indefinitely. Clean Attachment.Done with nil Err after both handshakes and RX delivery is a completion notification, not a reason to Abort. The surrounding origin bridge may cancel Parent on that clean Done; that terminal notification must not retroactively turn completed authenticated close into cancellation failure. Other parent cancellation remains terminal. Incomplete-close transport retires on attachment errors or premature lane loss. Clean Wait returns nil only for both authenticated closes and successful settlement. Parent cancellation, absolute timeout, fatal framing/authentication and authenticated RESET other than resetTransport remain terminal. RESET is best effort in its fixed slot, not a reason to block cleanup or start a sender worker. Terminal Abort wakes attachment I/O and all queue/API waits; attachment retirement wakes only old I/O owners.
NewSessionStarter(SessionConfig{Clock: MonotonicSessionClock{}}) returns
(SessionStarter, error) and validates only. The stateless exported clock uses
Go's monotonic time and one reusable timer. Fixtures may instead supply a bounded
controlled clock. Start(*SessionInput) (Session, error) consumes SessionInput on
every outcome, zeros transferred fields, validates role/parent/attachment/bulk/
material/reservation and preserves the unchanged lease. BootstrapResult.Take carries a private immutable settlementRole anchor from
its accepted local role. Start uses that anchor on failure even if the public
Role is malformed; attachment metadata exposes no local path position and must
not be used to guess entry or self-join an origin acquisition. Internal fixtures
that construct input directly must supply a valid local role. A malformed input
without an anchor has no entry settlement authority. Abort and mark its circuit
gate, leaving relay-owned settlement to its actual owner. Nil/zero unowned
handles are invalid, not capabilities to join. It allocates session state only behind that already acquired capacity. Install one explicit bridge
rooted in Background before raw I/O, including for custom contexts; preserve
Parent deadline/Err without WithCancel(customParent) or implicit AfterFunc
workers. Parent cancellation aborts and Stops queues. Non-clean Attachment.Done
retires the attachment under the retained-lifetime rules, retaining queues and byte admission.
The completed clean-Done exception above preserves authenticated terminal
success, including a final local control-close return race. The scheduler checks a parent deadline alongside its other deadlines, using the same
timer, without a separate deadline callback. There is no transfer cancellation
gap and no reference to the retired bootstrap timer/TLS connection.
Four fixed I/O workers own bulk write/read and control write/read. Add one scheduler and one explicit context bridge, six session workers. Origin already has acquisition plus acquisition bridge, or entry has invocation plus invocation bridge, two surrounding workers. Total 6 + 2 = 8. Public Read/Write/CloseWrite and terminal Wait run on callers; they spawn no workers. One admitted Read and Write are joined on terminal cleanup before releasing queue payloads. Wait joins the same bounded completion for concurrent callers, never a settlement worker. Material is cleared only after MAC users join. RoleEntry then synchronously joins Attachment.Wait and calls ReleaseAfterSettlement; RoleOrigin never does either, because relay joins acquisition before settling it. Start failure inherits that same obligation and cannot return early with owned workers or attachment. The service invocation remains tracked through Take, Session.Start and terminal Wait.
Retained-state seam, not an API
The concrete session terminal transition owns attachment Abort, queue Stop, worker/API join, queue Release, Material.Clear and Reservation.Close. Attachment retirement is separate from terminal destruction, as described below. Retirement retains the same pool/payload owners, Assigned/Started/Sent/Acked/deferred ACK state, RX Accepted/Delivered and any partial-read offset, both final cursors, FIN/ACK/FIN_ACK send observations, control material, byte edge and endpoint lease. Any partial bulk emission must be replayed as its original immutable segment only after authenticated attach establishes peer acceptance. Pending close keeps its original absolute deadline within the frozen recovery grace. Recovery owners must acquire one live matching retained owner, exchange authenticated cursors/nonces, replay unacknowledged before unsent, and limit duplicate suppression to replay. The retained-lifetime owner itself adds no registry, replacement installer or permissive recovery handler; those belong to the replacement implementation below.
Circuit bootstrap constraints and verification requirements
These constraints were set before the bootstrap code was written. The implementation and its tests keep them:
- Baseline circuit providers still require direct Peer and baseline concrete owners do not implement the new declared interfaces. Bootstrap must replace that coupling, not add a compatibility acceptor or reuse a generic pin provider.
- Record-bounded adapter reads plus both TLS close-notify exchanges need real fragmented/coalesced TLS tests. Prove the final TLS record followed immediately by raw bytes retains every byte; unexpected final plaintext, raw pre-close, timeout and cancellation must fail. Ordinary role Close/exporter tests remain.
- The local-store selection and authenticated local head comparison must reject generation races. The remote token's conservative invalidation must include shutdown, missing proof, fork, stale prefix, incomparable branches and ABA. Bootstrap tests nil/zero selection and borrow wrappers, nil/canceled contexts, released borrows, repeated Close/Release, a denied second borrow and the close-versus-provider-load race. Pause after initial Head while loading fresh material, seal Close, then require the final Head check to erase that load and return no operational credential to TLS. Also pause after provider return; Close must remain charged and incomplete until TLS and credential erasure join and bootstrap releases its borrow. Prove no credential reaches TLS after final invalidation. Cancellation must abort/join TLS and release the borrow before Close, with no extra worker or proof charge reused early.
- Origin Admit's context expires after publication. Test failed OK publication, cancellation before Ready, custom-context cancellation and blocked I/O with independent acquisition Wait. The new settlement callback must run on all binding and no-binding rollback paths exactly once and keep charges live through settlement. Composition tests also cover terminal entry bootstrap success and failure, cancellation before/after Ready, response/Take failure, successful transfer into SessionInput, concurrent Wait and service shutdown before/after Take. A bounded fixture input consumer exercises the session ownership obligation without implementing the session. Hold relay settlement blocked after circuit workers join; require entry terminal Wait/shutdown to remain blocked and charged, then release settlement and observe one complete release. After Take, the old result's Wait must not join or release the new owner. Contrast origin Wait, which must return without joining Attachment.Wait so relay can finish its own settlement. No detached waiter is permitted. The session's actual Session.Wait and Start-error implementation inherit these tests at their owner. No accepting handler may ship before these paths exist.
- Fixed owner allowances and retained-allocation charges are not measured RSS. Provider/certificate/projection and short-segment metadata tests cover their respective charged owners, not prepaid maximum replay windows.
- Bootstrap acceptance needs real A/B/C signed/TLS fixtures with no A/C Peer, approved head or authority decision, A publishing no endpoint, and at least one nonadjacent endpoint beyond genesis. Snapshot Peer/decision/invitation/ admission/ACL state before and after. Missing endpoint/client ACL grants must not prevent bootstrap or be created by it. Preserve production denial, unavailable gateway rows, direct access and passive pairing recovery.
Entry and origin implementation evidence and prerequisite repairs
circuit/entry.go and origin.go implement the frozen constructors. Origin's
acquisition has one worker and one explicit cancellation bridge rooted in
Background. Ready and attachment Done, not Admit's canceled publication scope,
govern bootstrap. Consumers own result/input on every outcome. The internal
service entry invocation has one bridge and one demand-grown cancellation entry; its
reservation wrapper delays the circuit release gate until this bridge joins,
including after Take. It holds no stale result and creates no settlement waiter.
No network operation or consumer callback runs under a circuit/service state lock.
The real transitioned-store fixture found two circuit projection assumptions
that did not match the store contract. A retained local Trust.PinnedID can be an
older anchor in the complete verified lineage, while the active credential uses
the final head. The sequential local circuit projections now check anchor
membership and final-head/credential consistency, without constructing another
signature graph or adding persistent trust. Baseline service route startup had
the same head-versus-anchor comparison; it now compares the verified final head
to the active credential. The fixture rotates C after ordinary neighboring pairing, stages its signed
successor at B and records only B's necessary explicit approval before starting
the services. A and C have no nonadjacent authority decision. The projection
repairs do not change neighboring Peer succession policy.
Focused real service fixtures cover C at generation one after neighboring pairing with only B's successor approval, exact finite binary raw tail, unchanged Peer/authority decision, invitation, admission and endpoint ACL state, no A endpoint, and no A/C pairing. They exercise standard/custom cancellation before Ready and before/after Take, bootstrap loss during proof ownership, security-time persistence failure, shutdown, concurrent role-specific result Wait, consumed-result isolation, resource denial and entry settlement blocked by a borrowed relay control. The last case keeps the service charge live after circuit work has joined and until the borrowed message and relay settlement complete.
Signed topology negatives install bounded real signed public evidence in C's own learned directory. A stale retained prefix, two incomparable successors, a selected successor inconsistent with A's certificate, and a real wrong-Hub certificate all fail before raw transfer. The selection-race fixture changes the real directory publication token at TLS credential retirement, before CONFIRM. Injected negative evidence is kept local with the existing directory-write fixture gate so the test does not start a separate neighboring approval ceremony. The component directory tests additionally cover catalog-only incomparable state and conservative ABA invalidation; those internal corruption defenses are not claimed as separate topology scenarios. The component retirement tests supply fragmented/coalesced TLS-record and premature-raw proof; the service fixtures do not duplicate that transport.
Relay settlement tests check optional callback order and exactly-once invocation on established FIN/abort, failed OK publication, and partial/empty rollback using real mux lanes. Service refusal can arrive as Transport when RESET discards a flushed failure before a reader consumes it. Exact CodeLimit/position bytes stay covered by the retained RESET-gated relay callback tests, not inferred from the ungated topology. Bootstrap composition alone does not deliver Session.Wait or Start-error handling; the fixed session implements both with the same transferred SessionInput settlement obligation, and its evidence is recorded below.
See the circuit and service test owners. No bootstrap fixture is remote application or manual UX acceptance.
Additional ownership-review correction evidence
A later independent review identified missing test evidence, not a production
security/lifecycle defect: origin shutdown in each ownership phase, entry shutdown
before Take, the remaining custom-context failure matrix, and asserted Wait
outcomes. The authorized correction adds real-topology cases in
service/circuit_test.go and extends relay/settlement_test.go. It adds no code
or contract change to production.
Origin Close now cancels and joins before-Ready acquisition, untaken result and taken input owners without a fixture-release cancellation trigger. A real lease completion barrier observes circuit release before pre-Ready acquisition join; a borrowed real control message holds established origin relay settlement after consumer/acquisition join. Both gates retain their actual budget charge. Entry Close covers both the existing taken-input/borrowed-control barrier and untaken result with invocation/bridge completion held. Close returns only after zero circuit and relay data/control usage. Origin result/acquisition Wait returning while Attachment.Wait is still blocked detects the real self-join cycle rather than substituting a fake attachment.
The standard/custom matrix covers those shutdown phases, blocked settlement, resource denial with a healthy concurrent circuit, bootstrap loss, fatal security time, and relay's component failed-publication path. Wait tests compare all concurrent and repeated terminal results for each role under healthy bootstrap followed by intentional abortive fixture cleanup and under induced attachment failure. Entry retains both circuit cancellation and typed relay settlement failure. Origin reports circuit-owned failure only. A healthy origin Wait that initiates abort has no pre-existing circuit cause and can return nil; it never claims application EOF. The fixture retains every cleanup outcome rather than ignoring result/attachment Wait errors.
One focused run exposed a fixture preflight race: publication visibility on all Hubs did not imply completion of directory synchronization, and an intervening publication correctly invalidated a proof borrow. The fixture now waits until actual neighbor compact-summary counts/digests match each sender's outbound snapshot, with unchanged publication tokens over that observation. This is fixture setup, not route/relay/bootstrap retry or a weakened security recheck. The circuit still starts one exact attempt.
Fixed-session implementation and service evidence
codec.go validates the complete fixed DATA header before a body read and
continues partial writes at their remaining offset. control.go checks exact
length, role/direction/session, body semantics and constant-time MAC before state
application. direction.go owns three demand-grown FIFOs under one lock with
condition-variable pressure waits. Each immutable payload has exact capacity
and a charged node. Begin moves that owner from unsent to
unacknowledged; successful Commit alone advances Sent. Deferred ACKs free nothing
before Commit. RX acceptance reserves room before copying and advancing Accepted;
Delivered advances only after complete segment consumption.
session.go implements the opaque ByteStream Read/Write/CloseWrite plus Session
Abort/RTT/Wait. Four I/O workers, the scheduler and explicit Background-rooted
bridge are fixed at six. Entry invocation or origin acquisition and its bridge
supply the other two, eight total. The session owns one reusable scheduling timer.
No I/O, MAC, randomness, admission wait or join runs under state, queue, control
or service admission locks. Public API users and all six workers join before
queue Release, Material.Clear and the circuit lease mark. RX workers clear and
release temporary bodies before their own completion.
Entry then joins Attachment.Wait and marks settlement synchronously; origin does
neither, leaving relay's supervisor to settle it. Service's invocation bridge
stays counted through Take, Start and Wait. Concurrent/repeated Wait shares one
cached completion. After those joins, Wait drops input, parent, attachment,
reservation, queue-container and clock references and clears pending controls and
probe nonces. A retained terminal byte edge keeps its cached outcome and RTT,
not retired resource owners. Take fixes a private settlementRole anchor to the
accepted local role. Start rejects both malformed roles and valid-enum roles
that differ from that anchor before allocating queues, workers or a timer.
Rejection zeros every input field, clears material and uses the anchor for cleanup,
without inferring local position from attachment metadata. Entry joins
Attachment.Wait and marks settlement; origin leaves both to relay. Explicit
package fixtures with a zero anchor still require a valid public Role.
Terminal RESET correction
The authorized post-review correction fixes a dead local RESET path. Previously,
terminate canceled the ordinary send context and aborted the attachment before
the sole session writer's deferred SendControl could copy RESET. Now the winning
transition seals session API admission, latches at most one RESET for local
cancellation, deadline or resource failure, cancels ordinary SendControl and stops
the queues immediately. The existing session control writer then encodes once
outside all state/queue locks and calls
Attachment.TrySendTerminalControlAndAbort(context.Background(), payload).
This independent live context adds no bridge, timer or worker. The call never
waits for Ready, slot pressure or physical delivery. Encoding or admission failure
falls back to Attachment.Abort. Unauthenticated malformed input still receives
no circuit response. A deadline can win the terminal result but cannot make a
malformed-input cause response-eligible. Inbound authenticated RESET releases its
relay borrow before terminating byte users and produces abortive Wait, never EOF.
Relay validates the bounded opaque payload, context, published endpoint state, closing/terminal state and lane liveness. One nonwaiting permit receive under its bounded local lock either transfers the existing send slot or refuses it. The sole existing relay writer sends the opaque control followed by the unchanged ATTACHMENT_ABORT, then flushes both under the same existing one-second abort-forward deadline before ordered mux RESET. No second transport, extra payload owner, worker or timer is introduced. The six session workers plus two surrounding owners, one session scheduling timer and four-timer total endpoint ceiling remain unchanged; relay/mux workers and timers stay separately charged. Admission means copying only, not physical or remote-consumption delivery. Ordinary busy-slot and closing/dead-lane fallback do not wait. An admitted terminal control on a physically stalled lane can still use the existing relay forwarding deadline and settlement bounds; these remain separately charged and are not a new instantaneous-socket promise.
The writer publishes its transport-drain deadline before entering a control-close
wait, so the scheduler observes the new bound even when close blocks.
CloseWriteControlContext(s.ctx) also wakes the session writer when cancellation
crosses a close waiting behind the relay writer. After successful control close,
the existing session writer stays until terminal publication, so it still owns
any later terminal attempt. A closed control lane rejects the attempt and aborts.
The original context-free relay close remains a compatibility wrapper. Circuit
workers/API users join before queue release and secret clearing. Entry then waits
for relay settlement; origin returns from Session.Wait without joining the relay
supervisor that owns acquisition.Wait. Both reservation gates remain required.
Real strict-mux/relay tests consume and authenticate actual local RESET bytes and the ordered relay abort. A test-only physical RESET gate prevents the existing mux discard race during that observation; this is delivery evidence under the gate, not a remote-consumption guarantee. Busy ordinary-slot tests keep the writer blocked without opening its fixture gate and still join/clear/release. An actual signed/TLS origin-session Abort with blocked byte users checks that terminal scheduling does not create an acquisition self-join cycle. Real Take service tests reject entry-to-origin and origin-to-entry public role mutation, as well as the retained invalid-role-255 cases, with standard/custom parents and zero joined circuit/relay charges. A validation-only component clock rejects any entry into session state or scheduling on a role mismatch.
Queue storage grows with accepted segments and returns each payload/node charge on ACK, complete delivery or joined terminal release. Native DATA I/O has no persistent full-frame staging arrays. The per-endpoint payload envelope remains 2 MiB unsent + 8 MiB unacknowledged + 2 MiB RX, with 4,096 total slots and TX 3,072/RX 1,024 subcaps. Fixed metadata, temporary RX bodies, queue allocations, proof/TLS preparation and relay owners retain their separate charges. This is owned-storage accounting, not heap/RSS acceptance.
service/circuit_session_test.go consumes actual signed/TLS BootstrapResult.Take
inputs with this starter. One-relay A-B-C and two-relay A-B-C-D exchange exact
32 MiB binary scripts in each direction, beyond all retained payload budgets,
and finish through authenticated FIN/final ACK/FIN_ACK and nil terminal Wait.
A-B-C reuses the accepted successor-lineage fixture with no A endpoint or A/C
Peer/head approval. Security snapshots remain unchanged and remote gateway rows
remain unavailable. An empty half-close proves final ACK zero and FIN_ACK zero
are required while the reverse direction remains usable.
On both paths a blocked fixture reader fills RX with 32 accepted 64 KiB segments and holds the 33rd frame in a charged temporary RX body. The sender backpressures. Reverse authenticated close, signed publication changes and a second bounded real session on the same mux links progress before the blocked reader resumes. An unequal diamond changes actual route preference under pressure while the original full path and attempt remain unchanged. Fixtures that predate recovery treated removal, verified authority fork, transit transport loss and exact-link replacement as terminal. Current recovery fixtures retain sessions on path loss and explicitly end those failure fixtures after checking retirement. Actual origin process/state loss still needs a new circuit and bootstrap because no matching retained origin survives.
The separate wire probe has one entry owner before Start. It writes one DATA frame to the real origin session, borrows that session's actual cumulative ACK, checks its full header/session/cursor and tag with the bootstrap Material.MAC, then releases the borrow and injects an invalid-tag ACK. Origin fails abortively; entry Start consumes the failed owned input. This is actual session-control cryptography over service TLS, not the relay's synthetic-control proof. The normal duplex/pressure fixtures do not add a second control reader or inspect private queue state.
Shutdown tests use standard/custom parents, concurrent Wait, a completion barrier after entry worker/API join and an origin acquisition barrier after Session.Wait. They prove entry invocation Close and origin settlement retain their own charges through those local joins. They do not claim that remote acquisition settlement holds entry-local pair settlement. The borrowed-control service barrier and the real-mux settlement barrier separately prove the actual Attachment.Wait hold. Invalid Start uses a both-Take barrier and corrupts each role in turn, proving original settlement authority and secret cleanup survive malformed public fields. All joined circuit and relay data/control charges end at zero; custom parents detect hidden propagation workers.
Component tests remain the owners of malicious controls, sequence exhaustion, partial writes, deferred ACK failure/retention, full byte/slot queues, live gaps and duplicates, nonce/RTT/timeout races and cross-lane close ordering. Their controlled clocks avoid wall-clock timer assertions. Service fixtures add signed bootstrap composition rather than duplicating that matrix. See the circuit tests and service composition tests.
The fixed-attachment circuit is the foundation for recovery. Bootstrap and the fixed session alone claim no application EOF, endpoint socket dial or public or private JSONL change. The lifetime split is described below, followed by authenticated replacement, retained-origin acquisition and replay, exact replay/live sequencing, automatic entry route retry and real-service recovery composition. A bounded endpoint consumer carries endpoint TLS into the existing ACL engine before any remote gateway row is selectable. Circuit close proves byte-stream close only, never client authorization or application execution.
Recovery design
This section defines the recovery protocol. It leaves the approved bootstrap, AHCD DATA, AHCC control, relay setup/framing and JSONL bytes unchanged. The implementation sections that follow describe the owners of each part.
A route is an eligible potential path in routing's RAM projection. A CIRCUIT is
one immutable relay Attachment. A reliable circuit session is the retained
entry/origin queue, control material and byte edge across separate attachments.
Keep these existing source identifiers. Only the entry chooses replacements.
Transit relays never change a suffix, interpret recovery messages or replay DATA.
Wire encodings and authentication
All integers are unsigned big-endian. All domains are ASCII with the explicit
trailing NUL shown below. Fixed lengths are mandatory. There are no optional
fields, negotiation, padding after the tag or new transport prefixes. Identity
and session IDs, attempts and nonces are nonzero. All unused bytes are zero.
Counters use 0 through MaxCursor, fffffffffffffffe; all-ones is forbidden.
Recovery generation uses 1 through MaxCursor. Generation zero denotes the
original bootstrap attachment locally and is never sent in recovery.
Compute the replacement binding digest B as SHA-256 of:
| 1 | "AgentHub-circuit-recovery-binding-v1\x00" |
| 2 | || mode:u8=2 || path_count:u8 || endpoint[32] || origin[32] |
| 3 | || path_roots[path_count][32] |
Path_count is 2 through 8, roots are unique/nonzero, the first is the retained
entry root and the last equals the retained origin root. The endpoint, entry,
origin and session ID must equal the original retained binding. The path itself
may differ. Unused local Path roots must be zero but are not hashed. B deliberately
excludes Attempt because relay.Entry.Start generates it after receiving Setup.
Every subsequent recovery message binds that fresh Attempt explicitly.
Recovery Setup is exactly 144 bytes in relay.Opaque, only for ModeReattach:
| Offset | Bytes | Field |
|---|---|---|
| 0 | 4 | ASCII AHCR |
| 4 | 1 | version 1 |
| 5 | 1 | setup kind 0 |
| 6 | 2 | zero |
| 8 | 32 | retained session ID |
| 40 | 8 | entry recovery generation G |
| 48 | 32 | fresh entry nonce E |
| 80 | 32 | replacement binding digest B |
| 112 | 32 | setup tag |
Setup tag is HMAC-SHA256 with the original ControlMaterial key K over
"AgentHub-circuit-recovery-setup-v1\x00" || Setup[0:112].
The origin compares B to actual OriginRequest metadata, not an entry-supplied
path alone. Setup authenticates a bounded acquisition request; it does not
prove fresh peer presence, commit handoff or release quarantine. The origin
response is exactly 4148435201800000, eight bytes AHCR/version 1/kind 128/two
zero bytes. It conveys provisional acquisition only, not authenticated success.
The original ModeNew setup/response remain unchanged.
Recovery controls are whole 232-byte opaque CIRCUIT_CONTROL payloads. Their header is 48 bytes, body 152 bytes and tag 32 bytes:
| Offset | Bytes | Field |
|---|---|---|
| 0 | 4 | ASCII AHCR |
| 4 | 1 | version 1 |
| 5 | 1 | message kind below |
| 6 | 1 | sender Role, entry 1 or origin 2 |
| 7 | 1 | zero, no DATA direction field |
| 8 | 32 | retained session ID |
| 40 | 2 | body length 152, 0098 |
| 42 | 6 | zero |
| 48 | 8 | G |
| 56 | 16 | actual replacement Attempt |
| 72 | 32 | B |
| 104 | 32 | E |
| 136 | 32 | origin nonce O |
| 168 | 8 | entry RX Accepted, EA |
| 176 | 8 | entry TX Started, ES |
| 184 | 8 | origin RX Accepted, OA |
| 192 | 8 | origin TX Started, OS |
| 200 | 32 | tag |
Each tag is HMAC-SHA256 with K over its exact domain, then the complete header
and body, bytes [0:200]. No tag is included in its own input. There is no new
key derivation, exporter, circuit TLS or session ID. Constant-time comparisons
apply to tags, session and nonce bindings. ControlMaterial.MAC's existing
1,152-byte input ceiling accommodates every input here.
| Kind | Sender | Name | Exact domain before header/body |
|---|---|---|---|
| 1 | entry | ATTACH | AgentHub-circuit-attach-v1\x00 |
| 2 | origin | ATTACH_OK | AgentHub-circuit-attach-ok-v1\x00 |
| 3 | entry | ATTACH_CONFIRM | AgentHub-circuit-attach-confirm-v1\x00 |
| 4 | origin | ATTACH_READY | AgentHub-circuit-attach-ready-v1\x00 |
| 5 | either | REPLAY_DONE | AgentHub-circuit-replay-done-v1\x00 |
| 6 | entry | LIVE | AgentHub-circuit-live-v1\x00 |
| 7 | origin | LIVE_OK | AgentHub-circuit-live-ok-v1\x00 |
ATTACH repeats Setup's G/B/E, carries the frozen EA/ES and has O/OA/OS zero. ATTACH_OK echoes those fields, sets fresh random O distinct from E, and still has OA/OS zero. ATTACH_CONFIRM repeats ATTACH_OK's entire body. ATTACH_READY keeps that body except for the now-frozen OA/OS. REPLAY_DONE, LIVE and LIVE_OK repeat ATTACH_READY's complete body. No message may change a snapshot within one candidate. Empty cursors are valid; empty nonces are valid only for ATTACH's O. Kinds 2 through 7 require both nonces. Decode validates expected remote role, kind/state, reserved bytes and all bindings before mutating state. The relay's outer attempt must match the acquired Attachment and the body Attempt.
Retained-owner acquisition before route OK
The origin maintains a demand-grown retained-owner registry bounded by configured admission and prepaid service metadata. Owners register after successful bootstrap transfer at Session.Start and leave only on terminal destruction. Each keeps its existing circuit lease and actual retained-allocation charges. It stores the original endpoint, entry/origin roots, session ID, original control material, lifecycle parent, stable byte edge and an opaque local generation token. Registry selection is not endpoint publication selection. A recovery can survive publication withdrawal, but cannot survive owning authorization revocation, process/state loss, parent loss or terminal deadlines. The byte edge may still be carrying the original inner TLS handshake. Do not require completed inner TLS or an already-open application as a condition of acquisition. Never create or transplant a TLS object, invoke Consumer again, dial an endpoint or call PrepareEndpoint.
Origin Admit uses the existing synchronous, cancellable callback. In order:
- Validate ModeReattach, exact Setup syntax and actual metadata. Under the bounded registry lock, find the live matching row and acquire its single verification/candidate hold slot. A concurrent verification or candidate already using that slot returns CodeLimit without allocation. Convert this same slot to the accepted candidate; do not create a second hold registry. Recheck terminal/grace/close/parent state before returning any acceptance.
- Copy fixed comparison fields, release the registry lock, verify Setup MAC and B outside all registry/session/service/relay locks. The hold prevents key erasure. No network or callback is performed under these locks.
- Under the owner's lock, recheck the row token, deadlines and MAC result. Verification begun before expiry grants no deadline extension: a valid MAC returned at or after any absolute grace, EOF-wait or FIN deadline is denied. Failed verification/recheck releases the provisional slot and key-use hold, not the retained session's key or deadline state. Require G greater than the highest confirmed recovery generation. Claim exactly one candidate slot atomically. A competing or still-retiring candidate returns CodeLimit; it neither replaces nor terminates that owner. Missing/dead/mismatched/stale state or bad proof returns CodeDenied. Malformed Setup returns CodeProtocol. No externally detailed authentication oracle.
- Take the provisional attachment once. Install a revocable per-attempt acquisition containing the hold, candidate token and owned attachment before returning the eight-byte response and Acquisition. Never retain OriginOffer. If Take or later checks fail, unwind the hold/slot, or return the acquisition for relay Abort/Wait cleanup. Zero acceptance cannot abandon a taken handle.
The acquisition waits for Ready outside Admit. Admit's context is borrowed and relay cancels it after OK publication; it cannot become the retained consumer or candidate lifetime parent. Use the retained lifecycle bridge and the acquisition's explicit stop token, not an implicit custom-context worker. Before Ready there is no circuit I/O. After Ready it permits only the recovery exchange. It has no access path that can expose quarantined candidate bytes to the retained byte edge. Setup verification alone cannot pause or retire a still-healthy old attachment. A failed OK publication aborts this candidate and releases its hold without clearing queues, key, lease or byte edge. Acquisitions are revocable until their own settlement. A candidate slot is not reused while its workers, borrows or relay settlement remain charged. OriginSettlement marks only that attempt's settlement, never destroys the shared retained session.
Candidate confirmation, installation and lost replies
The entry first declares old attachment failure, freezes its emission high watermark after old I/O joins, and increments its local generation once per fresh route attempt, even when relay setup fails. G never wraps or reuses. Draw a fresh E for each attempt. Fresh relay admission supplies a fresh Attempt; no attempt mutation or suffix substitution is possible. Incomplete RX bodies are cleared and released, not inserted into the retained stream. Keep RX partial-read offsets.
After route OK and response validation, entry sends ATTACH. Origin verifies it against the acquired Setup and attachment, draws fresh O and sends ATTACH_OK. This step does not retire the old origin attachment. Entry verifies ATTACH_OK and sends ATTACH_CONFIRM. Only receipt of the valid confirmation proves entry received this origin challenge. Origin then atomically advances its confirmed G floor, marks this candidate authenticated, pauses/retires the old attachment, and joins its I/O before freezing OA/OS. If it had not declared failure, this transition declares it and starts its own fixed grace. Existing earlier grace wins. Outside locks, validate cursor pairs and send ATTACH_READY. Entry validates ATTACH_READY and installs the authenticated replay candidate. Origin may start replay after admitting READY; entry may start only after receiving it.
Each worker, notification, control borrow, send completion and result carries its local candidate token, G and Attempt. Check these at application time. An old candidate's abort/Done/Err/RESET or late callback can retire only its own binding and return its own charge. It cannot Stop retained queues or act on the replacement. The existing AHCC controls remain unchanged and gain no attempt field. Their physical Attachment reader supplies the attempt provenance. Pending AHCC send completions and EOF observations from retired paths do not commit on a new path. Local authenticated pending FIN/final-cursor state stays retained.
Lost ATTACH_OK means origin has only a quarantined hold and entry has no proof of origin acceptance. Lost CONFIRM likewise installs nothing at origin. Lost READY may leave origin authenticated/replaying while entry still waits. In all cases deadlines or explicit loss retire the candidate and entry retries with fresh G/E/Attempt. A confirmed G remains consumed even if the candidate fails. Old challenges never verify against a new O. Do not resend handshake messages on the same reliable control stream, or treat successful SendControl, a physical write or local Ready as proof the peer received anything. Exact repeated recovery controls are a protocol error on a current candidate; FIFO transport does not duplicate messages. Stale candidate results are ignored after releasing borrows.
Cursor validity and ciphertext replay
EA and OA are cumulative acceptance, not application delivery. ES and OS are Started, not Assigned or Sent. Started includes the one immutable segment whose old write may have failed partially; authenticated peer acceptance can prove it arrived despite that local failure. Freeze them only after old I/O joins. New application writes may continue assigning bounded unsent segments, but cannot advance Started during handoff/replay. Reads can drain existing RX without changing Accepted. Preserve all retained pool ownership and pressure bounds.
At origin, require origin.Acked <= EA <= OS and origin.Accepted=OA <= ES.
At entry, require entry.Acked <= OA <= ES and entry.Accepted=EA <= OS.
Both snapshots must equal local frozen values where applicable, lie at or below
MaxCursor and respect any known final cursor. Every sequence above local Acked
through local Started must still have its original immutable payload owner.
Acceptance regression below Acked, acceptance beyond Started, missing retained
payload, reserved counters or final-cursor disagreement is terminal retained
protocol/state failure, not a route retry. Never accept a peer's cursor merely
because it is less than Assigned. Unsent segments cannot have been accepted.
Apply the authenticated peer Accepted as cumulative ACK after those checks and
old borrow join. It can release now-proven accepted payloads, including the
interrupted Started segment. Discard old deferred ACK/send observations. Do not
roll back the historical Sent high watermark; use a separate replay traversal
cursor. Replay the exact retained immutable segments (peer Accepted, local Started] in sequence order with the unchanged AHCD header, sequence and payload.
Do not resegment, renumber or recopy into an additional payload queue. Replay
precedes all unsent and newly assigned bytes. DATA remains opaque inner-TLS
ciphertext, never an application operation or authorization proof.
Each receiver starts at its frozen Accepted and accepts only its exact next sequence through the peer's frozen Started. Authenticated replay permits dropping sequences at or below the frozen Accepted without a second RX insertion, byte count increment or consumer invocation. That allowance ends at the replay/live boundary. It does not excuse a gap, an out-of-order new sequence, duplicate above the snapshot floor, changed role/direction, oversized frame or DATA beyond Final. The honest sender starts above the cursor, so dropped replay is defensive only. Keep no unbounded duplicate history. Existing live duplicate/gap rejection remains.
ACKs during replay use unchanged AHCC bytes and can free replay payloads only through a begun replay emission, with the same in-flight deferred-release rule. The attach cursor is the only exception allowing proof of an old failed Started write. Normal PING/PONG and final-cursor controls may operate after READY with attempt provenance. A valid remote FIN before all its DATA is not a gap. Persist both final cursors, application seals and original absolute close deadlines. Reemit retained FIN and, when final acceptance permits, final ACK then FIN_ACK on the replacement. Reemit even when the previous SendControl succeeded. Those writes never proved receipt. Previously received ACK/FIN_ACK proofs remain valid; path-local send/EOF/drain observations are rebuilt, not used to shortcut cleanup.
Each side sends one REPLAY_DONE only after its complete replay writes have returned successfully AND its RX Accepted equals the peer's frozen Started. Receiving peer REPLAY_DONE proves the peer accepted this side's entire frozen emission range. It does not prove the peer received this side's REPLAY_DONE. Validate the unchanged full snapshot body, and latch at most one early DONE while the other lane catches up. Entry sends LIVE only after its own DONE was admitted, peer DONE was received and both local replay conditions hold. Origin accepts LIVE only under those same local conditions and after receiving entry DONE. Origin sends LIVE_OK, then permits live emission. Entry permits live emission only after receiving LIVE_OK. Origin receipt of LIVE proves entry got origin DONE; entry receipt of LIVE_OK proves origin got entry DONE and LIVE.
No extra final ACK is needed for byte correctness. Lost LIVE_OK can leave origin live and entry waiting. Origin must not claim that entry received it. Entry's unchanged candidate/grace deadline still retires that attempt; origin handles its attempt-scoped loss or silent liveness failure. Both owners keep the same byte edge and later recover without reopening a consumer. Across independent lanes, at most one post-replay frame can be held in its charged temporary RX body while its LIVE/LIVE_OK control is pending. Pause further bulk reads at that boundary; never classify that legitimate lane reorder as a live gap or expose it early. After local live admission, duplicate suppression stops. No fresh payload starts until replay completion. Entry receipt of LIVE_OK and origin receipt of LIVE are their respective recovery-success linearization points, before which the original grace remains in force. This asymmetry is intentional, not an atomic both-peers-know claim.
Failures, deadlines and bounded owners
Declared attachment failure and terminal retained-session failure are distinct. Explicit link/attachment failure starts recovery immediately when observed. A silent path starts it only at the existing 30-second no-authenticated-progress liveness boundary. A ten-second idle PING is not itself failure. DATA, local writes, route refresh and malformed traffic cannot postpone this declaration. Transit reports ATTACHMENT_ABORT/RESET best effort toward usable surviving sides; no circuit_closed frame or acknowledged failure barrier is added.
Each endpoint uses its monotonic SessionClock. The first declared failure in a
recovery episode fixes recoveryDeadline = failureAt + 65 seconds. Attempts,
route changes, refreshes, notices and handshake progress never extend it. A
successful local live transition ends that episode; a later independent failure
starts another. Check Now >= every active deadline before accepting a transition.
Grace expiry is terminal. A timer wake that runs late cannot accept a late reply.
Setup retains relay's ten-second admission deadline. Acquisition before Ready is capped by that existing setup deadline. After Ready, all four attach messages must finish by ReadyAt + 10 seconds and any earlier grace/close/parent deadline. After authentication, replay and LIVE exchange must finish within the remaining grace/close/parent time. Liveness continues from authenticated progress, with receipt of each first valid recovery step counting candidate progress. Before CONFIRM, candidate traffic never refreshes the old attachment's liveness. Local admission or writes do not count. A replay timeout retires only that candidate while grace remains. No per-message retransmission timer or unlimited handshake retry loop exists.
The pending absolute 30-second CloseWrite/received-FIN/EOF-wait deadline from the fixed session is NOT paused, restarted or replaced by the 65-second grace. The earlier deadline wins. Recovery can finish pending close only in its remaining time. Completed half-close has no pending deadline to recreate; unread accepted RX and reverse-direction state remain charged. FIN alone never starts recovery. Expected bulk EOF after authenticated Final is not failure. An unexpected lane loss, including truncated DATA caused by EOF, is transport failure and may recover; a complete malformed header or impossible authenticated cursor is protocol failure. Clear and release incomplete RX bodies and replay the original segment. Transport drain after completed close retains its existing absolute 30-second bound. Do not launch replacement work for a fully completed close.
| Cause | Disposition |
|---|---|
| Setup denial, missing row, competing candidate, invalid quarantine proof | Reject/retire candidate only; no circuit response to bad authentication; keep unrelated/healthy retained owners |
| Explicit transport loss, relay Transport/attempt Timeout/Cancelled due to path retirement, missing replies, silent progress timeout | Retire exact attachment, preserve state, entry retries within fixed grace |
| Stale generation/old physical reader, late old RESET/result/Done | Ignore for current owner, release old borrow and settle old attempt |
| Complete malformed protocol/auth input on authenticated current candidate, authenticated RESET other than resetTransport, impossible cursor/final, counter exhaustion | Terminal retained failure; never retry as a route problem |
| Authenticated current resetTransport | Recoverable attachment failure, not FIN/EOF |
| Parent/client-entry loss, inner TLS failure, owning authorization revocation, service stop, retained-state/process loss, store fatal cause | Terminal under existing owner contract; no recovery/bootstrap substitute |
| Grace, absolute pending close, parent or final-drain deadline expired | Terminal retained timeout |
Remote relay failure codes are not themselves circuit-authenticated terminal proofs. A relay CodeDenied/Protocol/Limit rejects that path attempt. Preserve local store-fatal and authorization causes rather than flattening them into retry. Before confirmation, invalid candidate authentication cannot terminate a healthy session by lookup alone. After confirmation, protocol/auth failures are terminal. A terminal error stops queues, wakes byte users, joins all API/MAC/I/O owners, clears material/payloads and returns both lease gates as before.
At most one candidate per retained owner and two incident attachments, old plus candidate, can be charged. No next candidate starts until the retiring candidate has joined and settled. Entry joins its own Attachment.Wait synchronously. Origin acquisition Wait joins only attempt-local work; its candidate hold remains charged until OriginSettlement invokes ReleaseAfterSettlement. Wait NEVER waits for Attachment.Wait, shared Session.Wait or its relay supervisor. Relay owns settlement and invokes the per-attempt settlement hook. A terminal registry removal prevents new holds, joins admitted MAC/byte users and waits for all attempt settlement marks before releasing the original endpoint lease. Network I/O, MAC, joins and consumer callbacks never run under owner locks.
Endpoint payload budgets, 4,096 total slots and TX 3,072/RX 1,024 subcaps remain unchanged. Recovery reuses charged queue owners without a new bootstrap proof/TLS reservation or persistent DATA workspace. Charge fixed registry/candidate metadata and at most four 232-byte pending recovery values plus one in-flight value to existing endpoint overhead/control allowances. Keep at most one LookupLease per entry and close even a CodeNoRoute result's nonnil lease. Relay attempts retain their separate 96 KiB/8 KiB charges and process-wide 4,096-owner admission ceiling.
Implementation ceiling is eight circuit/service workers per retained endpoint, as in the fixed session. Four I/O workers belong to the current attachment generation; join them before starting candidate bulk/replay I/O. Before confirmation the bounded attempt supervisor alone sends/receives recovery controls synchronously, including while the old origin's four I/O workers remain live. It creates no candidate bulk pump or second reader on the old attachment. Scheduler and lifecycle bridge persist. The two surrounding worker positions become the once-invoked consumer and bounded acquisition/entry-attempt supervisor. Replace existing nested bridges, do not add recovery workers on top. Admit runs in relay's existing supervisor. Use one reusable session scheduling timer for liveness, grace, candidate, close and local retry wakeups; no additional endpoint timers or callback workers. Blocked slot admission cannot start workers, allocate queues or extend grace. Structural allocation/worker tests must prove these ceilings before enabling.
Entry uses routing.Table.Lookup(origin)'s selected candidate then ordered
alternatives, actual CandidateView/AdmissionToken and LookupLease.Changed.
No on-wire poll, new address or route chooser in a relay is allowed. Try candidates in that order, remembering only a bounded index for the current
projection revision. After exhausting it, wait on the existing change token or
a one-second local retry wake on the session timer, then reacquire current
candidates. Across all revisions, start at most one fresh attempt per second
and at most 64 attempts in one recovery episode. A route change wakes lookup
but does not bypass that admission interval. Exhausting 64 attempts leaves the
owner paused until grace expiry, not an unlimited spin. Reuse eligible exact
peer links; new links still require ordinary fresh peer TLS/trust/mux/READY.
Selected route exports refresh at 20 seconds, expire at 60 without valid refresh,
and cannot extend circuit grace. Never keep or mutate an expired admission token.
Concrete implementation and test ownership
The recovery design publishes no Go declarations or accepting stubs. The following private APIs implement it; their implementations arrive together with tests. The existing public Session byte edge and Consumer invocation count stay stable.
| Owner | Files and concrete seam |
|---|---|
| Recovery codec/fixtures | New circuit/recovery_codec.go and focused tests. Private fixed recoveryMessage, encodeRecovery, decodeRecovery, recoveryBindingDigest, encodeRecoverySetup, decodeRecoverySetup, response validator. Use original Material.MAC. Load these literals, never derive expected tags with project code. Do not alter bootstrap_codec.go, codec.go or AHCC domains. |
| Replay queues and session | circuit/direction.go, session_types.go, session.go, new recovery.go and tests. Add private pause/join, frozen recovery snapshot, apply authenticated acceptance, borrow/commit replay and replay-only RX acceptance operations. No queue Stop/Release on path loss. Replace destructive attachment failure with failAttachment(token, cause) distinct from terminal destroy. Keep Assigned/Started/Sent/Acked, partial RX read offsets, final state, edge and lease. Scheduler owns deadlines and one timer. |
| Retained acquisition and registry | circuit/origin.go, new circuit/recovery_origin.go, circuit/types.go only for implemented constructor/config changes. A bounded retainedRegistry.acquire(ctx, metadata, setup) returns an opaque held owner; candidate claim/install/retire and token checks are owner-local. Register at Session.Start, not on mere ROUTE_OK. New origin bootstrap still invokes Consumer once. Attachment acquisition Abort/Wait become per-attempt, not a terminal consumer join. Persistent consumer and parent ownership must be separated from failed attachment Done. |
| Entry route retry and service | circuit/entry.go, new recovery_entry.go, service/circuit.go, circuit_types.go, relay.go and focused service tests. Supply current routing Table and registry through implemented configuration, share original endpoint lease, track retained owner through shutdown. Replacement calls existing relay.Entry.Start with ModeReattach and the authenticated Setup. No Bootstrapper call or second Consumer on recovery. Production nil consumer still denies both modes. |
| Relay failure isolation | relay/binding.go, existing setup/owner lifecycle and tests only as needed. Retire each immutable binding, forward existing abort best effort to surviving side, preserve attempt provenance. No wire change, route retry, replay or retained-session selection in relay. |
Before enabling any recovery handler, durable tests must cover literal positives, all truncated prefixes, wrong roles/kinds/domains/reserved fields, valid-tag wrong session/attempt/path/generation/nonces and impossible cursor bounds. Controlled clock tests own exact 65/30/10-second boundaries, explicit versus silent failure, late old notifications, competing holds, failed OK publication, every lost reply, confirmed-generation replay, partial old emission/deferred ACK, replay before unsent, byte-for-byte TLS-handshake continuity, blocked RX, half-close, EOF reorder, slot/memory/worker limits and no second consumer. Signed real service fixtures own alternate/restored routes, unchanged trust/ACL state, publication withdrawal versus revocation, unrelated-circuit isolation and joined shutdown. Independent review, the authoritative build and aggregate acceptance are separate gates. The frozen literals below are review evidence, not evidence of runtime recovery.
Retained lifetime implementation
session.go and session_attachment.go separate exact physical attachment
retirement from terminal session destruction. Each immutable private token owns
four I/O workers and their cancellation. failAttachment(token, cause) checks
current provenance, pauses only queue I/O admission, cancels/aborts the old
attachment and fixes the first recovery deadline at failure declaration plus
65 seconds. Explicit loss observed before the liveness boundary starts grace at
that observation. Silent failure starts at lastProgress + ProgressTimeout,
even when the scheduler or a byte caller observes it late. A first observation
at or after that boundary plus 65 seconds publishes terminal timeout immediately,
without admitting a fresh recovery episode. Retirement does not stop/release
queues, clear material, close the lease or replace the public byte edge. Truncated transport frames, lane EOF before all
DATA through a valid FIN, and authenticated resetTransport use this path.
A FIN that exposes missing DATA after an earlier EOF retains that earlier
absolute EOF-wait deadline rather than replacing it with a later close bound.
Complete malformed framing/authentication,
impossible authenticated cursors, other valid RESETs, parent loss, shutdown and
absolute deadline expiry remain terminal. Silent no-progress failure retires at
the existing 30-second liveness boundary; idle PING alone does not retire.
The scheduler and lifecycle bridge persist with one reusable timer and no new workers. The bridge watches parent cancellation while the old workers finish and joins their temporary RX-body cleanup. TX borrows, including partially emitted immutable payloads and deferred ACKs, remain pinned. RX partial-read offsets, ACK flights, pending controls, final cursors and close observations remain in the original queue/session owners. Read and Write retain finite-budget admission and backpressure while paused. Only authenticated delivered FIN permits EOF. Existing close, EOF-wait and drain deadlines are not extended by recovery. Terminal Wait still joins all byte/I/O/MAC users, clears payloads/material and completes the original role-specific lease obligations once.
The implemented private PauseIO, failAttachment, applyAttachmentControl
and joinAttachmentIO operations have current session lifecycle consumers.
The confirmed replay/install owner consumes the joined token and
pinned queue state. It joins before installing replacement I/O, reconciles
ACK/borrow state under authenticated acceptance, and resumes live queue I/O only
after replay completion. There is no unauthenticated install stub.
joinAttachment synchronously joins entry relay settlement without releasing
the retained endpoint lease; terminal Wait and the recovery attempt preparation
both use it before release or the next admission.
Origin skips Attachment.Wait and settlement release to avoid its relay
supervisor's self-join cycle.
Retained lifetime alone is retirement/retention without end-to-end replacement. The attempt-rooted acquisition is separate from the persistent retained owner; registry/acquisition, authenticated handoff, replay and replacement, entry retry and the real service boundaries are the following sections. Attachment Done does not cancel the retained consumer parent. Production installs the remote application consumer; admission without a consumer still denies reattach.
session_retained_test.go covers immutable partial emission/deferred ACK,
partial RX delivery, fixed grace and absolute close/EOF deadlines, delayed
silent-failure observation before and after grace expiry, stale token isolation,
transport RESET versus fatal current input, finite paused admission,
parent cancellation while old I/O holds a charged RX body, pinned ACK flight and separate
entry/origin settlement. Existing session lifecycle tests now distinguish
recoverable lane loss from terminal grace expiry while keeping their terminal
join and no-fabricated-EOF assertions.
Authenticated replacement implementation
recovery_codec.go implements the frozen AHCR Setup, response and seven control
kinds. It uses the original ControlMaterial MAC and unchanged domains, with
fixed lengths, reserved-field checks and constant-time session/nonce/tag
comparisons. Tests consume the unchanged recovery positive and negative literals.
No bootstrap, AHCD, AHCC, relay envelope or JSONL wire bytes changed.
Reattach(ctx, relay.Entry, Session, EntryRequest) performs one explicitly
selected fresh ModeReattach attempt. It checks the original endpoint and
participants, retires and synchronously settles the old entry attachment,
consumes a fresh generation/nonce, then uses relay's ordinary Start admission.
It shares the original endpoint lease and does not call Bootstrapper or Consumer.
The caller must keep ctx live after success. Routing lookup, pacing, alternate
selection and retries remain the entry-supervisor/service owners' responsibility.
NewRecoveringOriginHandler requires an explicit retained lifecycle parent.
Its demand-grown retained registry registers only at successful Session.Start,
never at ROUTE_OK or mere Take. Before taking OriginOffer it finds the matching live
session and claims one verification/candidate hold. The hold protects the
original key outside locks and remains occupied until actual origin settlement.
Bad syntax returns Protocol; missing, stale, mismatched or bad proof returns
Denied; a competing or still-settling candidate returns Limit. Publication
withdrawal is not reattach authority and does not remove this matching row.
Terminal parent/authorization/state loss still forbids recovery. The original
bootstrap-only NewOriginHandler remains available to explicit bootstrap fixtures;
it denies ModeReattach rather than installing an accepting placeholder.
The initial origin consumer runs once. At registration its pre-Start bridge joins before session workers start; Session's persistent bridge takes the retained parent. Original acquisition Wait joins only its captured initial attachment I/O once retained, so a failed old relay can settle while the consumer remains live. Replacement acquisitions join only their own users and I/O, never Session.Wait or Attachment.Wait. A terminal row removal seals admission. Session.Wait joins held MAC/candidate owners before clearing material. The lease waits for consumer completion and every incident origin settlement, not just the original attempt. Service installs this handler for its internal consumer boundary and joins retained consumers at shutdown. Production nil consumer still denies both modes.
recovery.go performs the frozen challenge, confirmation and READY exchange,
then reconciles authenticated acceptance against Started and retained immutable
payloads. Only valid CONFIRM consumes the origin generation and retires a healthy
old attachment. Lost ATTACH_OK or CONFIRM installs nothing; lost READY retains
the consumed generation and retires only that candidate. Fresh attempts never
reuse its nonces or generation. Session's single timer retains ReadyAt+10-second
attach, fixed grace, liveness and earlier absolute close/parent bounds.
Replay borrows the original immutable payloads, precedes unsent bytes, and drops duplicates only through the authenticated frozen RX floor. REPLAY_DONE and LIVE/LIVE_OK gate live emission; at most one charged post-replay RX body waits for the control-lane barrier. Four old I/O workers join before four new workers start. The persistent bridge rebinds to the new physical token. Path-local send, EOF and probe observations reset, while received close proofs, partial reads, final cursors and absolute deadlines remain retained. Old results check physical/candidate provenance atomically before terminal publication. Clean relay drain is not transport failure. Relay rejection/transport results alone never authenticate a terminal retained-session failure.
Focused codec, queue, controlled-clock, registry and real signed/TLS relay tests cover the implementation. The service probes exercise quarantined candidate competition, withheld confirmation, lost READY, consumed-generation rejection, withdrawal, old-attempt settlement before terminal lifetime, and post-replacement opaque duplex continuity with the same byte edges and one consumer each. The pressure fixture fills RX and holds a charged temporary body, then recovers an interrupted 16 MiB stream with immutable unacknowledged data, queued unsent bytes and a retained partial-read offset. A gated acceptance test cancels after Offer.Take but before OK publication and checks the held owner settles without reopening or terminating the healthy original stream. The tests explicitly distinguish entry-local Wait from remote origin settlement. A separate actual relay callback gate delays the original origin acquisition's Abort/Wait and its result until a new authenticated attachment is live. The test verifies opaque bytes before and after releasing that result, unchanged replacement metadata/lifetime, the newer candidate hold remaining occupied, and exactly one old attempt settlement with relay charges falling from two to one while the endpoint stays retained. It does not bypass a replacement candidate's hold to admit a successor: that hold must still join and settle before reuse. Existing fixed-path failure fixtures now terminate surviving retained peers explicitly rather than assuming best-effort RESET delivery or relay EOF destroys shared state. Automatic recovery orchestration and the broader alternate-path, inner endpoint TLS/application and availability gates remain downstream acceptance, not claims made by this section.
Exact replay and live resumption
The inherited authenticated replacement state machine now has focused queue and paired session fault coverage. This section completes replay and live sequencing, not automatic route lookup, retry pacing or final service orchestration.
Queue reconciliation runs only after retired I/O joins. It validates local cursor/final bounds and the complete immutable unacknowledged payload chain before applying authenticated peer acceptance. Paused attachment observations cannot commit TX or ACK flights. Reconciliation discards those old flights, retains the historical Sent watermark, and releases only payloads proved accepted by the peer. Replay uses the existing slot owners and a separate traversal cursor; ACKs cannot release a currently borrowed replay payload until its complete write returns. Unsent and newly assigned bytes remain behind the replay/live barrier.
ResumeLive checks that TX replay and RX acceptance reached their frozen Started
boundaries without an outstanding borrow before permitting live queue I/O. The
session publishes local recovery success only after that admission succeeds.
Frozen-floor duplicates insert no RX bytes; duplicates above the floor, gaps and
all live duplicates remain protocol failures. Accepted partially read payloads
keep their offsets and full accounting charge until the consumer finishes them.
No payload replay queue or application/TLS resumption mechanism is added.
An EOF before the authenticated peer Started retires that candidate immediately. It cannot claim replay completion or wait for an unrelated FIN. A completed local LIVE result remains immutable if its physical path later fails, which starts a new recovery episode. Clean authenticated FIN drain cannot abort a successful candidate merely because its attach supervisor has not returned yet. Retained FIN/final ACK/FIN_ACK proofs, zero-final closes, original absolute close deadlines, fixed recovery grace, finite queues and the separate control lane remain intact. Pre-FIN bulk EOF starts its absolute wait deadline only when none exists. A later EOF on an authenticated replacement rebuilds the path-local observation without extending that retained deadline. A controlled-clock paired replacement regression checks unchanged deadline ownership and timeout at the original instant.
replay_queue_test.go proves opaque consumer bytes, immutable frame/slot ownership,
repeated interrupted writes, cumulative/deferred ACK release, frozen duplicate
windows and byte/shared-slot accounting under pressure. replay_session_test.go
uses real paired relay attachments, fresh authenticated handoffs and the unchanged
DATA/control codecs. It injects partial header/payload reads and writes, ACK and
ATTACH_OK loss, interrupted simultaneous directional replay, LIVE_OK lane reorder
and loss, live gaps/duplicates, and lost pending FIN/final ACK/FIN_ACK with zero
final. Both stable consumer edges are checked against their original binary byte
streams. Bootstrap material is synthetic in these session tests; the inherited
service recovery tests retain real signed bootstrap/TLS and pressured-stream
composition coverage. These session tests enable no production endpoint consumer
or remote availability. The entry-supervisor/service owners still own automatic
attempts and broader topology acceptance; the endpoint carrier owns endpoint
TLS/ACL/application composition.
Entry retry and grace ownership
NewEntry still performs one exact initial setup. NewRecoveringEntry wraps
that successful bootstrap result's local transfer. When the consumer starts the
entry session, it installs one sequential retry supervisor. Construction,
untaken results and origin sessions start no route lookup or retry worker.
Recovery calls Reattach, never Bootstrapper or Consumer again.
The supervisor holds at most one atomic routing.Table.Lookup(origin) lease,
including a nonnil NoRoute lease. It uses the selected candidate first, then the
bounded ordered alternatives. CandidateView and AdmissionToken pass unchanged
to relay Start, which allocates a fresh AttemptID and performs exact physical-link
admission. There is no suffix substitution or ban on a restored original route.
After exhaustion, the supervisor waits for projection change or a one-second
local wake, then reacquires. A change token wakes lookup promptly but cannot
bypass pacing. The minimum interval between starts is one second with bounded
random jitter of zero through 255 milliseconds. At most 64 attempts start per
recovery episode; exhaustion leaves the session paused until its original grace
expires. Only authenticated local LIVE resets episode accounting.
The existing session scheduler owns retry wakeups on its one reusable monotonic timer. The retry supervisor has one coalesced notification slot and no timer, callback worker or second coordinator. It runs each Reattach synchronously, so old I/O and entry settlement, and every failed candidate's settlement, join before the next attempt. A successful attempt's parent remains live through its path lifetime. Terminal session publication cancels the active parent even if relay Start is still blocked before READY and no recovery candidate exists yet. Session.Wait joins the retry supervisor before clearing retained state or releasing reservations and lookup capacity.
The session remains the sole grace and close-deadline owner. Explicit attachment failure starts recovery immediately; silent failure uses the existing absolute no-progress declaration boundary. Candidate admission, failed/lost replies, route publication, refresh and backoff do not change the fixed 65-second grace. The earlier absolute parent, pending FIN, EOF-wait or drain deadline still wins, including equality. Expiry cancels blocked attempt work and stops queues, waking both blocked readers and full-queue writers without fabricated application EOF. Origin retains and responds to authenticated replacements, but never selects a route or starts this supervisor.
For service entry invocation, EntryRecoveryConfig carries an optional local
caller/bridge transfer. Take installs the additional terminal caller, closes the
transfer notification and joins the previous bridge before returning SessionInput.
The persistent session bridge then watches caller cancellation; service stop
still cancels the tracked invocation parent. This replaces the surrounding
bootstrap bridge's worker position with retry, retaining the eight-worker
circuit/service ceiling and unchanged endpoint and relay reservation gates.
These channels are local ownership plumbing, not wire fields.
The behavior exists in entry.go, entry_retry.go, session.go, recovery.go
and the internal service entry constructor. Controlled-clock regressions cover
route ordering, failed and repeated candidates, exact-link token replacement,
restoration, lost ATTACH_OK retirement, pacing across publication, 64-attempt
exhaustion, grace/close equality, route changes adjacent to grace, silent loss,
shutdown, blocked byte APIs, and reusable timer/lookup/lease capacity after join.
Real-service recovery topology composition is covered under service recovery
below.
Service recovery and terminal settlement
Real service composition now exercises NewRecoveringEntry and
NewRecoveringOriginHandler together through signed directory/normal-peer TLS
line and diamond topologies. These internal consumers retain one Session byte
edge across fresh attempts. Line restoration preserves partial reads and exact
16 MiB streams each direction beyond the retained queue windows. Diamond loss
selects an alternate, restores the original path on fresh peer links, then uses
that original path after alternate loss. An independent circuit keeps its fixed
healthy attempt and byte progress. Peer removal and a verified transit-root fork
also retire the active diamond path and require automatic alternate installation,
exact bytes and the same fixed consumer count. Neither recovery creates another
consumer. The service contract
owns the concrete composition and the endpoint consumer handoff.
The retry supervisor's successful attempt context is also the relay lifecycle parent. Terminal publication cancels blocked/failed attempt work immediately, but an authenticated clean close of an installed LIVE replacement leaves its parent live through Attachment.Wait. Supervisor exit closes routing lookup leases without cancelling that successful path. Session.Wait joins candidate users, retry and I/O/API workers, settles the entry attachment, cancels the remaining attempt context, and marks final settlement exactly once. Abnormal termination retains immediate cancellation and queue wakeup. Origin still never joins Attachment.Wait from its acquisition or session worker.
A candidate Done notification can be selected after the candidate reaches LIVE. Its pending-only failure claim and the LIVE transition share the Session lock. If LIVE wins, the ordinary attachment observer classifies settlement using the authenticated-close and lane-EOF requirements. If failure wins, the candidate cannot subsequently enter LIVE. Other recovery abort paths can still retire an already-live physical attachment.
This ordering is implemented in entry_retry.go and session.go, not merely a
design requirement. Real-service clean recovered Wait regressions detected the
previous premature parent cancellation, which returned CodeCancelled after
successful bytes and authenticated EOF. The corrected service tests also retain
endpoint charges while delayed original relay retirement remains gated, and
prove late old acquisition results cannot release or destroy a replacement.
Automatic acquisition/installation cancellation evidence uses a nil-by-default
SessionConfig.BeforeRecoveryInstall internal fixture barrier. On origin it runs
after authenticated ATTACH_CONFIRM and READY emission, before installation; on
entry it runs after authenticated READY. It receives only the existing local
context and immutable attachment metadata, runs outside locks in the existing
attempt owner, and must honor cancellation without spawning work. No production
consumer installs it. The install owner still performs all cursor/provenance/
terminal checks after the barrier. Session.Wait joins candidate users before
clearing the callback, and the fixed metadata allowance includes its one function
reference. It is not an application, route-selection or wire-policy hook.
Real service tests fail the original attachment, then let NewRecoveringEntry create the one gated attempt. Caller cancellation and entry/origin shutdown join that attempt at acquisition before READY and at the origin install boundary. The install barrier returns nil on cancellation so the real owner's recheck, not an injected protocol failure, rejects installation. Joined endpoint/relay charges, acquisition settlement counts and reuse of every global routing lookup slot prove that retry, retained holds and invocation owners have completed.
See the service recovery tests. Silent loss and precise grace/close equality remain controlled-clock component evidence; the real-service tests do not claim real inner endpoint TLS/application recovery. Production installs the joined carrier and real endpoint TLS/ACL/application consumer, with no rebootstrap or direct-local fallback.
Endpoint carrier contract
This section defines the production composition, implemented by the production
carrier below. The
existing bootstrap, response, transcript, exporters, HELLO/CONFIRM, AHCC, DATA
and 144/232-byte recovery encodings remain byte-for-byte unchanged. The new
endpoint descriptor is outside those encodings, in relay's existing bounded
opaque setup. Its first production authentication is the separate AHEC control
exchange below. Bare recovery setup remains valid only for internal fixtures;
production requires the envelope. Pairing never uses this envelope or Session.
Literal positives, negatives and transition cases live in
internal/agenthub/testdata/carrier.
Endpoint setup in the existing opaque slot
AHES is exactly 16 + q bytes. Integers are unsigned big-endian.
| Offset | Bytes | Value |
|---|---|---|
| 0 | 5 | 41 48 45 53 01, AHES version 1 |
| 5 | 1 | Purpose: 1 application, 2 endpoint_access |
| 6 | 8 | Positive binding generation captured from verified endpoint binding |
| 14 | 2 | Inner length q, exactly 8 for new or 144 for reattach |
| 16 | q | Unchanged circuit SetupOpaque or authenticated recovery setup |
New is 24 bytes; reattach is 160. Both fit relay.MaxOpaqueBytes = 512 without
changing AHRA. AHES has no addresses, client identity, ACL, socket, timestamp,
new role selector or negotiation. Endpoint and full path are already in AHRA;
OriginRoot must equal its last root. Entry and origin resolve canonical SPKI
whose identity hash equals that endpoint ID. Unused opaque tails remain zero.
An unknown purpose/version, zero generation, wrong mode/length, truncation,
extra byte, nested envelope or substituted inner header fails before bootstrap
allocation. Relays forward it without interpretation.
The circuit entry/result/retained owner carries a local descriptor by value. It cannot be recovered from untrusted context values. Origin's service wrapper unwraps only the inner circuit setup before calling the existing handler, and retains the envelope descriptor with the acquired owner. For reattach, require exact equality with that retained descriptor before candidate acquisition; then run the unchanged recovery MAC/binding/confirmation. Do not authenticate an AHES change merely because the inner recovery MAC passed. Current publication is not reattach authority and withdrawal does not replace the original binding generation. No second AHEC exchange or endpoint preparation occurs on recovery.
Authenticated production readiness before session workers
Opaque setup is not authenticated by the frozen bootstrap transcript. A transit could change purpose or generation while preserving endpoint/path. AHEC closes that gap. It is a whole-message opaque relay control, NOT AHCC, bootstrap TLS, DATA, gateway JSON or pairingwire. It runs once after bootstrap TLS retirement, under the established circuit ControlMaterial, before ordinary session workers or endpoint bytes are admitted. It never changes the bootstrap response.
Each AHEC payload is exactly 191 bytes, with no length prefix of its own. Relay supplies the existing control wrapper.
| Offset | Bytes | Value |
|---|---|---|
| 0 | 5 | 41 48 45 43 01, AHEC version 1 |
| 5 | 1 | 1 PREPARED from origin, 2 ACCEPT from entry, 3 START from origin |
| 6 | 32 | Exact ControlMaterial.SessionID |
| 38 | 16 | Initial attachment Attempt |
| 54 | 32 | Exact endpoint ID |
| 86 | 32 | Entry stable root, first root in attachment path |
| 118 | 32 | OriginRoot, last root in attachment path |
| 150 | 8 | Positive binding generation from AHES |
| 158 | 1 | Purpose from AHES |
| 159 | 32 | HMAC-SHA256 tag using circuit control key |
MAC input is ASCII AgentHub-endpoint-carrier-v1 followed by one NUL octet,
then the entire 159-byte unsigned payload. Use ControlMaterial.MAC; service
never obtains its secret. Every receiver constant-time compares the tag and
compares every field with its own immutable descriptor and authenticated
attachment/material. Kind implies sender role, not a peer-provided role field.
No unknown kind, reflection, out-of-order control, retry, duplicate, bad tag,
wrong attempt, trailing byte or fallback is legal. Release each borrowed
ControlMessage before receiving again. Total AHEC application control is exactly
573 bytes on success, at most three messages. No endpoint/application byte may
precede completion. A failure aborts the initial Session and follows existing
role-specific cleanup; it does not start a 65-second recovery episode.
Circuit owns the complete AHEC role state machine, encoding/verification, MAC, attachment SendControl/ReceiveControl and borrowed-message release. Service receives only a closed recheck phase and immutable public metadata. There is no BeforeWorkers callback taking Session, no service raw-control API, and no concrete-session type assertion to obtain an attachment or ControlMaterial.
The following Go shapes are the internal implementation contract in circuit.
They are declarations to implement later, not source added at this gate:
| 1 | type EndpointPurpose uint8 |
| 2 | const ( |
| 3 | EndpointApplication EndpointPurpose = 1 |
| 4 | EndpointAccess EndpointPurpose = 2 |
| 5 | ) |
| 6 | type EndpointDescriptor struct { |
| 7 | Purpose EndpointPurpose |
| 8 | BindingGeneration uint64 |
| 9 | } |
| 10 | type EndpointPhase uint8 |
| 11 | const ( |
| 12 | OriginPrepared EndpointPhase = 1 // Before sending PREPARED. |
| 13 | EntryAccept EndpointPhase = 2 // Verified PREPARED, before ACCEPT. |
| 14 | OriginStart EndpointPhase = 3 // Verified ACCEPT, before START. |
| 15 | EntryReady EndpointPhase = 4 // Verified START, before worker launch. |
| 16 | ) |
| 17 | type EndpointPhaseView struct { |
| 18 | Phase EndpointPhase |
| 19 | Role Role |
| 20 | Descriptor EndpointDescriptor |
| 21 | Metadata relay.AttachmentMetadata |
| 22 | } |
| 23 | type EndpointRecheck func(context.Context, EndpointPhaseView) error |
| 24 | type EndpointPhaseConfig struct { |
| 25 | Descriptor EndpointDescriptor |
| 26 | Recheck EndpointRecheck |
| 27 | } |
| 28 | // New field on SessionConfig. Nil is internal-fixture mode only. |
| 29 | // Endpoint *EndpointPhaseConfig |
Descriptor is comparable and closed: purpose 1 or 2 and positive generation. Metadata is an independently owned value copied from the initial attachment, not service input. Service verifies Phase/Role and every captured selection field and returns a bounded typed local error or nil. Recheck runs synchronously, outside circuit/peer/directory locks, and must honor its phase context. It may perform bounded local publication/route/reservation checks, but no control I/O, endpoint TLS, socket dial, worker creation, Session operation or relay join. Circuit validates the nonnil callback and descriptor against the private production descriptor transferred in SessionInput before allocation. Missing or mismatched config fails closed; a nil config cannot admit a production result. Bare recovery fixture inputs retain nil config and their unchanged Start behavior.
For production, Start consumes input on every outcome, validates ownership, reserves its fixed worker positions, initializes queues and registers retained origin state, then joins the pre-Start bridge. The row is pinned but non-acquirable until the AHEC state machine succeeds. Start launches only the persistent lifecycle bridge before AHEC, watching Parent AND TerminalParent. The bridge cancels the circuit-owned phase context and aborts phase I/O, not an unstarted scheduler. The state machine has sole attachment control ownership until it returns. Every borrowed message is verified and released within the current receive step, including malformed input and cancellation. No borrow or queued AHEC payload reaches session control workers.
Origin calls Recheck with OriginPrepared, then sends PREPARED. Entry receives and verifies it, calls EntryAccept, then sends ACCEPT. Origin receives and verifies ACCEPT, calls OriginStart, then sends START. Entry receives and verifies START, then calls EntryReady. Each recheck/send/receive completion checks cancellation and the absolute phase deadline before transition. Circuit uses its privately retained Material/Attachment; service never obtains either. START follows origin retained registration and the reserved engine handler. Only after its role sequence succeeds does Start launch ordinary workers and return a usable Session. Origin's once-run Consumer then starts endpoint TLS. Gateway still rechecks the live prepared owner before ready and tunnel_ok.
On any AHEC or Recheck error, Start unregisters retained state, joins the phase bridge, accounts for worker positions never launched and performs its existing role-specific rejection cleanup. Entry joins attachment settlement; origin leaves that join to relay. On success it marks the origin row acquirable and transfers the same bridge to normal terminal ownership before launching the remaining workers. There is no cancellation gap after Take and no phase worker added to the fixed circuit worker allowance. Recovery invokes neither AHEC nor Recheck; it validates the retained descriptor before ordinary candidate work.
One clock for retirement and the production phase
Add Clock SessionClock to BootstrapConfig. Existing internal callers may
leave it nil, selecting MonotonicSessionClock for the new retirement timestamp
only. Production requires one service-constructed SessionClock supplied to
BootstrapConfig.Clock, SessionConfig.Clock and the carrier adapter. Tests pass
the SAME controlled clock instance to all three; unrelated clock epochs are
invalid composition. This does not change approved bootstrap TLS/setup deadline
calculation or bytes. Wall/security time and certificate-generation clocks
remain separate.
At adapter.retire() success in bootstrap.go, immediately sample Clock.Now
and capture it before proof/provider release or any delayed result handoff.
The raw result stores that timestamp and transfers it through Take to a private
SessionInput field. Retained/entry wrappers preserve it unchanged. It is not
reset at Take, Start, recheck, registration or worker launch, and service needs
no RetiredAt accessor. A zero timestamp fails production before AHEC.
Circuit computes the single absolute AHEC deadline as captured retirement time plus ten seconds, using SessionConfig.Clock for comparisons and its reusable phase timer. An earlier still-active caller deadline wins. Equality expires before send/admission/transition. Controlled timers and comparisons use that same clock; production MonotonicSessionClock shares time.Now's monotonic domain with transport deadlines. Completed bootstrap phase deadlines are not kept as terminal Session parents. AHEC does not extend the separate ten-second bootstrap phase, reset a recovery timer or allow late AHEC after control ownership transfer.
Reserved stable net.Conn adapter
Add circuit.NewSessionConn with an internal config containing a live Session,
local and remote role/root/endpoint address values, a required already-reserved
carrier lease, terminal caller context and monotonic clock. It owns the Session
on every outcome and returns one net.Conn with CloseWrite, Abort and joined
Wait. The adapter lives in circuit, imports neither endpoint nor service, and
never exposes attachments, TLS objects, secret material or a dial address.
Its synthetic address Network is agenthub-circuit; String contains only role
and public root/endpoint IDs. Local/RemoteAddr are stable over replacement and
must never become a dial target or invitation address.
A wrapper that starts an unjoined goroutine for each blocked Session operation
is forbidden. Reserve 16 KiB fixed DATA and 16 KiB CONTROL per adapter in addition
to the circuit lease. The process AdmissionPool has an independent adapter
counter using the configured global limit, default 524,288. Actual storage also
intersects the endpoint-carrier byte budgets. At most four demand-allocated
32 KiB buffers cover one pump buffer and one queued buffer in each direction.
Native Session readiness lets the receive pump wait without allocating a buffer
while idle. Two joined pumps are the sole Session.Read and Session.Write callers.
The adapter queue owner uses a mutex,
fixed wait notifications and at most two reusable deadline timers, one per
API direction. There is no per-call worker/timer, unbounded waiter list or
buffer proportional to caller write size. Buffers reserve actual capacity from
circuit_ciphertext before allocation. Pump and timer counts grow with admitted
adapters, not the configured maximum. They are additional composition counts,
not a reinterpretation of circuit.MaxWorkersPerEndpoint or proof of total Go
heap usage. Existing serving workers and gateway pumps remain separately counted.
API Read drains only received queued bytes, releasing space for the receive
pump. API Write repeatedly copies available bounded prefixes into owned queue storage
until it has accepted the whole input or encounters a nonnil deadline/terminal
error. It never returns (n < len(p), nil). A write larger than queue capacity
waits for bounded queue space instead of allocating caller-sized storage. The
send pump drains accepted bytes through Session.Write with partial-write offsets
before reusing storage. Once Write reports bytes accepted they remain
transport-owned, even if a later API call times out. A timed-out unaccepted
suffix is never secretly queued later.
Receive staging can block during recovery without exposing EOF. Bytes cannot
be discarded or copied twice when deadline/cancellation and queue progress race.
Deadlines follow net.Conn semantics, not relay bulk deadlines:
- SetReadDeadline/SetWriteDeadline set absolute bounds on pending and future calls in that direction. Zero clears the bound. SetDeadline sets both in one local critical section. Earlier caller terminal deadlines still win.
- At or after a nonzero deadline, a blocked operation wakes and returns a
timeout wrapping
os.ErrDeadlineExceeded, withnet.Error.Timeout() == true. A write may return its already-copied prefix and that error. Do not abort the Session merely for an API deadline. Extending or clearing the deadline lets later operations proceed; existing accepted bytes continue to drain. - Update deadlines by generation; a stale timer tick cannot expire a newer setting. Every wake checks the current clock before admitting bytes. Equality loses to expiry, even if queue progress is also ready. Setters never touch a peer socket, attachment deadline, recovery grace or FIN deadline.
- Support concurrent net.Conn calls by serializing each direction with bounded admission bookkeeping. Waiting for the direction gate also observes its current deadline and Close. It cannot allocate a request-sized queue. One read and one write may progress independently.
- CloseWrite seals new API writes after any currently copied prefix, wakes writers with their accepted prefix and a nonnil closed-direction error, drains accepted bytes, then invokes Session.CloseWrite exactly once. Read stays live. It is idempotent and returns promptly after sealing. The adapter has an absolute drain/close bound of thirty seconds from the FIRST seal, including time spent draining to Session. An earlier Session FIN/EOF close deadline, caller deadline or in-progress recovery grace wins. It uses the existing timer allowance, never starts another thirty seconds on Close or later Session.CloseWrite, and does not extend authenticated close deadlines. The paused recovery scheduler includes this carrier deadline even when a full TX path blocks the send pump before native FIN timing starts. Equality expires the carrier; recovery grace cannot postpone that close bound. Wait joins the eventual drain/FIN outcome.
- Session's authenticated FIN becomes io.EOF only after all received staging and queued bytes are delivered. Physical EOF, RESET or path loss cannot become adapter EOF. Terminal error wakes both directions, allowing a received prefix to be returned with that error but never a success-only fabricated FIN.
- Close is the idempotent, joined GRACEFUL full-close path. Seal API admission, drain all accepted writes, then Session.CloseWrite; do not abort just because tls.Conn.Close called raw Close after enqueueing close_notify. Close also wakes pending API reads and lets the receive pump drain queued/remaining reverse bytes into fixed discard storage until authenticated EOF. Discarding unread inbound bytes after full Close is legal; losing admitted output on a successful Close is not. Read/Write/setters thereafter return net.ErrClosed. A preexisting read/write API deadline does not discard accepted output or become a shutdown timeout. Full Close uses the first-seal bound above and current caller/session bounds, without extension. During orderly drain the owner keeps its terminal context live; normal engine return alone cannot cancel that context underneath close_notify/FIN.
- If graceful drain/FIN cannot finish within its fixed bound, classify close
timeout as failure, Abort immediately, then join. Caller cancellation,
revocation and other terminal failure take Abort, not the graceful path.
Abort has exact shape
Abort() error, is idempotent and nonwaiting, aborts Session and wakes both pumps/API directions; it releases nothing. Wait or Close after Abort joins the same terminal completion. Close may then return a nonnil cause; it cannot claim successful delivery of discarded output. - Both Close and Wait join pumps, admitted API calls and Session.Wait before closing the carrier lease. Origin Session.Wait never joins its relay supervisor; origin settlement still belongs to relay. Entry joins its attachment settlement through Session.Wait. Expiry declares failure at the fixed close bound; native settlement joins retain their existing finite deadlines and charges. Neither a timer nor Abort releases capacity.
The endpoint engine receives this raw carrier and performs ordinary fresh inner TLS once. After authentication, its existing lifecycle transfers the TLS budget and calls RunApplication or ServeEndpoint. The adapter and those TLS/session objects stay unchanged over circuit replacement. Do not transplant TLS onto replacement bulk or drain the inner stream to inspect application operations.
Bounded local lifecycle observation
Circuit supplies these closed local types and documented interface. Start's existing Session result also implements EndpointSession for production; this named interface needs no assertion to an undocumented concrete owner. The carrier config requires EndpointSession, not a raw-control-capable Session.
| 1 | type SessionPhase uint8 |
| 2 | const ( |
| 3 | SessionLive SessionPhase = 1 |
| 4 | SessionRecovering SessionPhase = 2 |
| 5 | SessionTerminal SessionPhase = 3 |
| 6 | ) |
| 7 | type TerminalClass uint8 |
| 8 | const ( |
| 9 | TerminalNone TerminalClass = 0 // Live/recovering only. |
| 10 | TerminalJoining TerminalClass = 1 // Authenticated close, join pending. |
| 11 | TerminalClean TerminalClass = 2 // Authenticated close AND nil joined result. |
| 12 | TerminalFailed TerminalClass = 3 // Terminal circuit/carrier failure. |
| 13 | TerminalCallerLost TerminalClass = 4 // This local caller transport already lost. |
| 14 | ) |
| 15 | type EndpointStopReason uint8 |
| 16 | const ( |
| 17 | StopCarrierFailure EndpointStopReason = 1 |
| 18 | StopCallerLost EndpointStopReason = 2 |
| 19 | StopRevoked EndpointStopReason = 3 |
| 20 | StopInnerTLS EndpointStopReason = 4 |
| 21 | StopService EndpointStopReason = 5 |
| 22 | StopApplication EndpointStopReason = 6 // Abnormal proxy/application failure. |
| 23 | StopCloseTimeout EndpointStopReason = 7 |
| 24 | ) |
| 25 | type SessionObservation struct { |
| 26 | Phase SessionPhase |
| 27 | Terminal TerminalClass |
| 28 | Joined bool |
| 29 | Episode uint64 |
| 30 | Attempt relay.AttemptID |
| 31 | GraceDeadline time.Time |
| 32 | Changed <-chan struct{} |
| 33 | } |
| 34 | type EndpointSession interface { |
| 35 | Session |
| 36 | Observe() SessionObservation |
| 37 | AbortEndpoint(EndpointStopReason) error // Nonwaiting, no resource release. |
| 38 | } |
Observe takes one value snapshot and its closed-pulse Changed channel under the
Session mutex; it does no I/O, wait or worker creation. Publish phase/class/pulse
together on declared recoverable loss, authenticated replacement installation,
authenticated live resumption and terminal outcome. Installation changes the
observed attempt and pulses Changed under the same lock even while replay is
still recovering, before LIVE. Episode never wraps; exhaustion is terminal failure. This snapshot has
no arbitrary error text, TLS material, cursors, payloads or route paths. It is
not gateway/EzHub JSON or durable state. A missed pulse cannot hide the current
terminal class.
A nil runtime terminal cause from authenticated bilateral FIN first publishes SessionTerminal/TerminalJoining with Joined=false. The existing owning Consumer calls Wait; Wait's final role-specific cleanup/settlement result publishes Joined=true and TerminalClean only if that complete result is nil. A join error publishes TerminalFailed. Wait publishes the final joined snapshot and pulse under the same mutex before its join-completion channel opens, preserving the classification after cleared SessionInput. The writer never blocks on Wait or infers failure from SessionTerminal alone. It ignores TerminalJoining for failure status and waits for a class pulse or its own caller/output failure. A nonnil winning terminal cause publishes TerminalFailed immediately; joined cleanup later sets Joined without erasing failure. Clean classification cannot be requested by service.
AbortEndpoint accepts only the listed reasons and translates them to terminal
failure in the same once-owned terminal transition as Abort. StopCallerLost
publishes TerminalCallerLost only when cancellation remains the winning cause
after absolute-deadline arbitration. At recovery-grace or carrier-close deadline
equality, expiry wins and remains TerminalFailed; a caller-loss callback cannot
rewrite that timeout classification. Other reasons publish TerminalFailed. Zero/unknown reason returns a local invalid-call
error without changing terminal state, never clean close. SessionConn adds the internal method
AbortWithReason(EndpointStopReason) error, forwarding to this transition;
its ordinary narrow Abort() error uses StopCarrierFailure. Phase/caller bridges
and gateway/engine cancellation owners use the known reason, not error strings.
TerminalParent loss after entry transfer supplies StopCallerLost; service-parent
stop supplies StopService. Ordinary Session.Abort remains generic terminal
failure. A late Abort/caller-loss callback cannot overwrite an already winning
close/failure or the classification of a replacement attempt.
Revocation, inner TLS failure, service stop, grace/close expiry, authenticated RESET, malformed/forged control and abnormal proxy failure are TerminalFailed. Recoverable attachment loss stays SessionRecovering/TerminalNone during fixed grace. Normal application completion requests bounded TLS/adapter Close and is TerminalClean only after authenticated close and nil join, not merely because the application function returned nil. A closed client-entry socket is locally TerminalCallerLost; the opposite origin sees the resulting authenticated reset or transport failure as TerminalFailed, not proof that its own caller vanished.
Gateway's exact retained preparation owner uses this class plus its existing ready/tunnel phase for delivery. Before ready, keep unavailable/resource/protocol errors; after ready before tunnel_ok, a failure uses existing error circuit_failed; after tunnel_ok it uses existing terminal status circuit_failed. TerminalClean closes normally with NO failure status. TerminalCallerLost performs joined cleanup and only best-effort delivery on any surviving outer transport. Neither class bypasses reservation release/join. Old-attempt completions cannot report recovered or close a replacement. Circuit never writes gateway frames.
Production carrier implementation
The AHES/AHEC contracts are implemented in endpoint.go, with
literal codec, authentication, phase-order and deadline regressions. Entry and
retained origin carry an immutable EndpointDescriptor through bootstrap Take
and authenticated replacement. Production SessionConfig requires the matching
EndpointPhaseConfig and the same retirement/Session clock. Origin registration
is pinned but non-acquirable until the once-run phase succeeds. Bare fixture
bootstrap and recovery bytes remain unchanged.
NewEndpointOriginHandler exposes the typed per-offer EndpointConsumer owner on
the same retained registry as internal recovery. It denies bare Admit. Invalid
calls consume and join a supplied owner; unused pre-worker owners are aborted
and closed; successful replacement uses the original descriptor and consumer.
Registered production Session teardown, rather than a second acquisition abort,
owns its terminal control attempt. Tests prove queued RESET survives consumer
return, scoped Close joins before capacity release, and incident settlement is
still relay-owned. A countercheck also delivered RESET with the prior tail, so
that factoring alone is not evidence of an end-to-end revocation repair.
ReserveSessionConnLease consumes a pre-reserved carrier RAM lease and claims
one process-wide adapter token before production readiness. An unused
lease Close releases it. NewSessionConn adopts that slot without charging a
second one; fixture callers may let the constructor reserve its slot. The
adapter uses at most four demand-allocated, charged 32 KiB buffers, two joined
pumps and two reusable local deadline timers. It exposes stable public-only synthetic addresses, independent
Read/Write deadlines, CloseWrite, nonwaiting Abort and joined Wait. Ordinary
Close seals admission, drains accepted output and joins Session FIN/settlement
under the first close bound. Capacity and storage are released only after pumps
and API calls join. Deadline changes wake pending operations without changing
accepted-byte ownership or aborting the retained Session.
EndpointSession adds a private value observation with live/recovering/terminal, attempt/episode, grace deadline, Changed, and joining/clean/failed/caller-lost classification. The last episode's fixed grace deadline remains observable after authenticated resumption, allowing the gateway to report the causal status pair even if one physical frame write spans the whole episode. Clean is published only after authenticated close and nil joined result. This adds no gateway, relay, bootstrap, DATA or recovery field. See the service implementation and service carrier tests.
Pressured carrier terminal wakeup
An idle SessionConn send pump observes both the retained Session Changed pulse and its caller's cancellation, in addition to adapter queue activity. This matters when the receive queue and staging buffer are both full: the receive pump cannot fetch another native error, and terminal failure must still abort both application directions without a rescuing read or Wait. The send pump uses the existing Abort/join path. Recovering, TerminalJoining and TerminalClean do not become failure merely because they wake it. Native terminal classification survives adapter cleanup; capacity still releases only after pumps, APIs and Session join. No additional worker, timer, buffer or wire field was introduced.
Adapter regressions cover the full terminal-reason matrix, pending Read and pressured Write, caller cancellation, and unchanged once-only charge release. A real pinned endpoint/device TLS and application-codec test fills both unsent windows during recovery, authenticates replacement before reads resume, and continues exact duplex payloads and close_notify on the original TLS owners. That component test uses synthetic initial circuit material. The production service checkpoint separately covers real bootstrap, ACL, application socket and gateway status.
Local inventory callbacks
SessionConfig.Projection publishes fixed owner observations and the current
public attachment path at handoff, recovery transitions, terminal and Joined.
The callback does bounded local work under circuit-to-projection lock order. It
must not perform I/O, wait, acquire admission or call back into the circuit.
Service uses it for retained display identity, not diagnostic replay.
BootstrapRequest.PreparationFailed, EntryRecoveryConfig.PreparationFailed
and SessionConfig.PreparationFailed notify the bounded service registry before
failed preparation cleanup/settlement, including the last raw-result cut and
rejection after Take but before observer handoff. They carry no error or secret.
Raw bootstrap results clear the callback before retaining the request. A failed
preparation remains terminal with Joined false until its owner joins; it never
fabricates a live phase or exposes control material. See the
service domain readers
and service preparation regressions.
Resource-pressure terminal cause
The internal AbortResourcePressure hook publishes the locally detected
ErrResourcePressure and TerminalResourcePressure before interrupting the
carrier. It uses the existing authenticated resetResource reason without
changing encoding or adding a reason, frame, ACK, retry or timer.
A received circuit resetResource remains a generic terminal session failure.
It is not echoed and must not start attachment recovery. A received mux
ResetResourceLimit instead follows normal attachment-failure recovery with the
fixed 65-second grace and existing earlier absolute deadlines. Relay classifies
that hop failure as CodeTransport, without retaining a typed resource cause as
endpoint pressure evidence. Provenance checks still prevent stale attempts from
changing a replacement.
First cause wins. A busy terminal slot or failed best-effort delivery still joins
and releases its owners; attachment loss may end in generic failure after the
existing recovery grace. The approved client-entry gateway feedback is
best-effort terminal/resource_limit for entry-Hub locally detected pressure.
Remote resource reasons do not establish that local cause. This is a
Hub-to-client contract
only. No application payload or EzAgent status is synthesized, and no new
inter-Hub lifecycle semantics, wire, RESET code or guaranteed delivery is
authorized.
Dynamic retained-buffer ownership
limits.circuit_admission supplies positive int64 global, per_client and
per_endpoint policies, each defaulting to 524,288. circuit.AdmissionPool
keeps separate process-wide logical circuit and adapter counters with the global
limit, without proportional storage. Services sharing a live process pool must
use the same global limit. Client and endpoint counters are Service-local and
keyed by authenticated stable client identity and locally authorized endpoint.
Origin never derives a client key from relay metadata. Entry and origin each
count once; transit forwarding has no session or replay cache. Entry invocation,
retained origin and replacement attachments keep the original reservation through
circuit join and all relay settlements. Queue sizes, 4,096 segment slots,
64-KiB segments, ACK ordering and the 65-second recovery grace remain unchanged.
Fixed circuit DATA/CONTROL metadata is 32 KiB/16 KiB, separate from retained
ciphertext and prepaid service metadata. A local Hub's circuit_ciphertext
ledger defaults to 256 MiB shared across actual queue payload capacities,
256-byte node allowances, temporary RX bodies and SessionConn buffers. Reserve
succeeds before allocation or copy. TX emits its 24-byte header then the borrowed
immutable payload without a DATA staging allocation. RX validates the header,
charges its exact body, copies into a separately charged queue node and releases
the temporary body. There are no two persistent Session DATA staging buffers.
ACK, complete delivery and joined terminal release return retained charges;
partial delivery keeps the full allocation charged. Standalone fixtures may omit
CiphertextBudget; both production carrier ends install it. This is actual
retained ownership, not a full 12 MiB window prepaid for every possible session.
SessionConn uses the independent adapter counter and a fixed 16-KiB
DATA/16-KiB CONTROL metadata reservation. Its two pumps own at most four dynamic
32-KiB allocations. RX moves a charged read buffer to the application queue;
TX moves a charged queue buffer to the Session writer. Neither transfer copies
or changes the charge. Partial application reads retain full allocation capacity;
partial/pending Session writes retain the pump's allocation until I/O returns.
For a native Session, the receive pump waits for readiness before allocating its
32-KiB buffer. Adapter storage is otherwise demand-driven and charged, not prepaid arrays.
Budget callbacks run outside the adapter lock. Joined Wait releases remaining
queues only after pumps and API users join. Every receive-pump exit publishes
its RX terminal result and wakes application readers. If authenticated
TerminalJoining or TerminalClean already won, later allocation denial preserves
that outcome and queued final bytes, then exposes EOF rather than leaving the
reader waiting for an exited pump. Otherwise allocation denial retains the
resource-pressure cause. Known staging admission pressure is preserved as
resource exhaustion at the gateway preparation boundary.
The service registry reserves the configured session_registry metadata
allowance for its lifetime, default 64 MiB and minimum 4 MiB. A 64-KiB fixed
allowance plus 4 KiB per row capacity covers public rows, AVL ordered nodes,
runtime/cancellation and retained-origin indexes, and map growth overlap. Rows
and maps allocate lazily; pagination and shutdown need no maximum-sized scratch
arrays. Metadata capacity intersects circuit admission and resource counts.
Endpoint observations describe already admitted circuits and take no second
global token. Restricted-pairing registrations retain a separate 16-owner
process allowance. Joined release removes rows exactly once with handle identity
protecting against stale removal. Session totals use int, not uint16 or a fixed
2,064-row ceiling; pages remain 16 rows and attachment paths eight roots.
The circuit tests own allocation and ciphertext-retirement regressions. These component checks do not establish simultaneous live Hub maxima. The separate 2,048-owner and 1-GiB stress profiles are not shipped defaults or fixed product maxima.
Origin pre-reserved lease transfer
EndpointOrigin.AdmitReservedEndpoint is an internal new-endpoint admission
path, not a wire operation. Production service calls it with the endpoint lease
reserved immediately after local endpoint/descriptor verification, before
carrier, registry or TLS preparation. The method consumes that lease and the
scoped consumer on every outcome. Invalid calls release both gates; retained
admission adopts the existing lease without invoking ReserveEndpoint again.
An accepted acquisition keeps the established retained-origin circuit,
consumer and all-attempt-settlement joins. Replacement continues to use
AdmitEndpoint and the original retained lease, without fresh preparation or
client-key inference. Focused configured-policy tests reject excess endpoint
leases before preparation. Separate transfer tests carry real application bytes
with an origin circuit budget allowing exactly one reservation.