docs/internal/agenthub-directory.md
AgentHub local directory catalog
internal/agenthub/directory builds an in-memory, network-independent public catalog. Build accepts a typed Source containing only complete signed current authority lineages, endpoint identity/binding/publication/revocation frames, and active relationship ceremony/approval frames. Callers must select committed state before calling it. Every catalog-changing authoritative transaction must verify its candidate before persistence, using Build or the narrow endpoint revocation replacement below. The caller publishes the result only after a durable commit. An uncertain write publishes no catalog success. The package does not read the store, sign records, authorize peers, or transport catalogs.
Build verifies a selection, not its provenance or freshness against a previous catalog. A valid older publication or revocation list supplied alone cannot be distinguished from the caller's current selection. The store must compare signed revisions and contents with its authoritative endpoint state on load and enforce monotonic replacements in transactions. Supplying both old and new selections for one endpoint is a conflict, not an instruction to pick the newer record. Likewise, the typed public-only source cannot prove that a relationship is locally active; that selection belongs to the store.
Each endpoint carries the exact current origin authority bundle. Each relationship carries both complete authority bundles ending at its ceremony signing generations. Prefix and equality checks use typed canonical signed-content digests, so valid signature variants of the same records are one lineage while different transition content remains a fork. Verification uses independent records.MemoryStore dependency scopes per endpoint or relationship, records.VerifyAuthorityLineage, records.Verifier, and records.ValidateAuthoritative. In particular, a historical key shared by different relationships cannot become an unrelated authority-head candidate. Distinct current roots cannot own the same current head. A catalog contains only one current endpoint selection per endpoint ID and one active relationship per unordered pair of roots. A relationship has exactly one verified approval per signer slot and one matching canonical ceremony. The approval deadline is not rechecked for already active historical evidence.
The catalog has no private fields by construction. Its input is signed v1 frames and canonical public ceremony bytes, not Hub snapshot or Pairing rows. It rejects malformed frames, extra bytes, absent dependencies, wrong families, mismatched current hosting generations, incomplete approvals, nonretained signing generations, and conflicting selections. Source and output bytes are copied; Catalog.Source returns fresh copies. Identical entries collapse; authorities sort by genesis frame, endpoints by endpoint ID, relationships by ceremony bytes, and approvals by signer slot. No read signs or repairs state. Private endpoint observation reads borrow each
endpoint's contiguous range by binary search in these verified, immutable,
ID-sorted catalogs, including the local conflict comparison. They still compute
the complete census and project every visible row under the current directory
lock. They do not rescan a whole catalog for each endpoint, retain a metadata
cache, or weaken generation, sequence, exact continuation or stale-sample checks.
Catalog limits cover the strict store's collection maxima, including withdrawn and retired endpoints:
- 257 authority bundles: one local authority plus
store.MaxPeers, currently 256. - 1,024 endpoint entries, matching
store.MaxEndpoints. - 256 relationship entries and distinct ceremonies, one per active peer. The store also caps retained Pairing rows at 256.
- 21,313 distinct signed-content records:
257 * 65 + 1024 * 4 + 256 * 2. Each authority has one genesis and at most 64 transitions; each endpoint has identity, binding, publication, and revocation-list frames; each relationship has two approvals. Origin bundles and historical signing prefixes repeat frames already counted in the current authority bundles. - 16 MiB of distinct signed frames, independently of the private store's 64 MiB document ceiling. Private ACLs and invitations consume document bytes but add no selected public frames. Persistence requires both envelopes; collection maxima do not promise every combination of maximum-sized records.
- 315,648 ceremony bytes:
256 * records.MaxCeremonyBytes, currently 1,233 bytes per ceremony.
A separate 21,313-row input bound limits parsing and verification before semantic deduplication. Valid exact-frame variants with the same typed signed-content digest consume one authority, endpoint, relationship, record-count, and retained-byte slot. Each variant that survives input admission still undergoes full signature and dependency verification. Different signed content remains a conflict or authority fork. Ceremonies use exact canonical bytes. Admission checks use remaining-byte subtraction.
BuildContext observes cancellation between bounded record operations and
shares a batch-local budget of 42,626 cryptographic signature checks. Exact verified authority bundles are reused. A bounded
signature cache shares only successful cryptographic checks, keyed by exact
SPKI, domain-separated input, and signature; it never shares dependency or
trust decisions between scopes. Per-verification dependency, signature, and
byte limits in records remain unchanged, including cache hits, as do
independent endpoint and relationship dependency scopes.
The immutable catalog retains one exact frame for each verified signed-content digest, plus bounded slice and entry metadata. Build chooses the byte-lexicographically least variant in its input. Outbound aggregation does the same across current contributions; retained repair evidence supplies a representative only when current contributions do not contain that signed content. The choice spans authority, endpoint, and pairing-approval uses and is independent of arrival order. Catalog.Source still makes independently mutable copies,
including repeated authority dependencies. The 16 MiB distinct-frame limit is
not a bound on that expanded export, transient parsing allocations, or total
verification cost. Entry counts, lineage lengths, frame limits, and the
signature-work budget bound those operations separately.
TestHubCatalogCapacityCoversStore guards the cross-package capacity invariant;
regressions also build all 256 relationships plus the local authority and
validate all 1,024 endpoints with seeded in-memory P-384 credentials, checking
catalog completeness and a strict snapshot encode/parse round trip. Small
catalog regressions cover bootstrap, restart, and uncertain persistence without
repeating credential-file durability work for every endpoint.
The caller must provide the current signed publication and revocation-list replacements. An authority activation must atomically rebind and advance the signed publication of every retained endpoint, including withdrawn and retired endpoints. The store owns the private notification window. Re-grant removes the old tag and replaces the signed revocation-list state. At 1,024 public tags, store.RevokeEndpointAuthorization drops the oldest private notice without restoring ACL access; the transaction's signRevocations sorts the remaining tags lexically and signs the complete replacement before persistence. Invitation rows, claimant locks, client identities, ACLs, revocation secrets, pairing recovery state, names, aliases, profiles, paths, sockets, dial addresses, pending or denied successors, collision witnesses, terminal forks, transition bookkeeping, and removed relationships never enter Source. Source contains no runtime framing. Normal-peer transport and learned-directory behavior are specified below.
Narrow immutable endpoint revocation replacement
The exact integration API is:
| 1 | func (c *Catalog) ReplaceEndpointRevocationContext(ctx context.Context, endpoint identity.ID, priorAccessRevision, nextAccessRevision uint64, expectedTags [][32]byte, signedFrame []byte) (*Catalog, error) |
records.RevocationList.Tags uses raw [32]byte notification tags, not the
family-qualified records.Digest used for record dependencies. The caller signs
the complete replacement list and supplies its expected canonical tags. The
method does not sign, sort, evict notices or change private ACLs.
Only a strict local Build or BuildContext result, including BuildBatchContext
results and earlier narrow replacements, is a valid predecessor. Strict
construction retains an immutable endpoint-ID-to-position index with exactly one
entry per selected endpoint. Valid signature variants collapse before indexing;
distinct selections remain conflicts. Learned compact decodes and outbound
selections cannot supply an authoritative predecessor, even when a particular
endpoint looks unambiguous. There is no fallback scan or opportunistic full build.
The zero value, nil catalog, absent endpoint and nil context fail. Cancellation
returns the context error without a candidate or predecessor mutation.
The prior revision must equal the indexed endpoint's current signed access
revision. The next revision must be exactly prior + 1, with nonzero revisions
and no overflow, matching one authoritative access mutation. The supplied frame
must be a canonical v1 revocation list for that endpoint and exact next revision.
Its tags must equal expectedTags element-for-element, with at most 1,024 tags
in strictly increasing unsigned byte-lexicographic order. Duplicate, unsorted,
missing or extra tags fail; nil and empty slices both mean the empty list.
Malformed frames, trailing bytes, wrong record families, wrong IDs, stale or
skipped revisions, wrong keys, wrong signature domains and noncanonical signature
encodings fail through the existing records checks.
Verification uses a new dependency scope containing only the indexed endpoint's existing identity frame. The records verifier checks that identity's self-signature and the replacement's endpoint signature with an operation-local budget of exactly two cryptographic checks. It preserves the existing Ed25519 and fixed-width low-S P-384 rules and per-scope limits. It validates only that narrow verified graph, not any authority, binding, publication, relationship or unrelated endpoint. A strict catalog's retained distinct-frame byte total is adjusted by subtracting the old revocation frame length and adding the new length. The 16 MiB limit still applies. The ID and fresh revision make the replacement digest distinct from every other entry's revocation digest, so no table count or other frame charge changes.
The result owns a new endpoint descriptor slice of at most 1,024 entries and the
new exact signed frame. It shares the immutable endpoint index, authority and
relationship containers, endpoint identity/binding/publication bytes, all origin
containers and bytes, and every unrelated revocation frame with its predecessor.
Endpoint order is unchanged. It retains no predecessor catalog or verification
graph. Public evidence uses ordinary Go lifetime ownership and is never erased
through a shared catalog. Retention accounting includes the bounded endpoint
index and conservatively charges shared storage in each retained catalog.
Caller inputs must remain unchanged during the call; neither input frame nor tag
storage is retained afterward. Source() continues to return independently
mutable deep copies, including repeated dependencies.
The store's typed endpoint mutation owner can prepare this candidate outside its
request-facing locks, then publish it only after definite WAL durability.
Admission revocation has no public selection change and reuses the exact existing
catalog pointer. Broader changes still require full BuildContext; bootstrap,
strict recovery and checkpoint healing must not substitute this narrow check for
complete catalog verification.
TestReplaceEndpointRevocationDifferential compares exact source and compact
bytes/count/digest with fresh builds for Ed25519 and P-384, empty and full 1,024-tag
windows, eviction and re-grant. Signature-variant tests retain the supplied exact
replacement while preserving unrelated canonical representatives.
TestReplaceEndpointRevocationMaximum1024Endpoints fills the existing distinct
byte envelope with 1,024 endpoints, compares a legal full-window replacement with
a fresh build and proves that one extra tag beyond the envelope is refused by
both paths. Structural tests inspect the actual complete index and backing-slice
sharing, enforce the two-signature budget, count operation boundaries independent
of endpoint population, and check cancellation, malformed inputs, immutable
exports and concurrent reads without latency thresholds.
For a replacement change, select TestReplaceEndpointRevocation through
just test-go-package ./internal/agenthub/directory -run '^TestReplaceEndpointRevocation'.
Use focused race coverage when concurrent ownership changes. The integration
owner selects broader coverage under the test policy;
these are not additional per-feature completion gates.
Store integration
Signed mechanics stay in records. Catalog admission and representative gathering
use the operation-local records.SignedFrameSelection; directory code owns traversal, reservation,
table counts, byte charges and the preference for current contributions over
retained repair evidence. Revision extraction uses records.SelectionPolicy,
the same typed key/revision policy as learned selection. Policy errors cannot
silently supply a zero revision; this lookup requires verified ordinary catalog
records. Canonical frame equality
and least-frame projections use the records comparison owner. Build and outbound
operations reuse its bounded, operation-local SignedFrameSelection metadata
memo for repeated exact dependency frames. Bundle comparisons, canonicalization
passes and compact authority-scope lookup therefore do not repeatedly validate
the same hot P-384 lineage. The memo retains at most 256 entries and one MiB of
frame/core bytes per instance; eviction never changes admission. This scratch
fits within the existing compact working allowance. None of these metadata
operations replaces independent signature and dependency verification. Compact
ordering, bytes, count, digest and all admission/retention bounds are unchanged.
Outbound representative collection indexes only the selected output's typed
digests, with at most MaxRecords entries checked before growth. It then scans
the already verified current contributions and considers only those digests.
The first current witness replaces stale repair evidence even when its exact
bytes sort later; subsequent current witnesses select the least exact frame.
Every match still compares exact canonical cores, so digest equality cannot hide
a content collision. A second bounded map records which selected digests have
current support. There is no retained-contribution union map, copied preferred
map, or independent selection owner. The selected byte total is checked before
cloning the output. Both scans and the rewrite pass check cancellation.
The directory keeps distinct selection policies for endpoint dependency tuples, endpoint-wide publication high water, complete revocation replacements, authority fork branches and supported historical relationship epochs. They share typed content identity but not freshness or trust meaning. Their existing witness, working-space and retained-ownership bounds remain separate.
store.Endpoint retains signed current publication and revocation-list frames and validates them against the counters, ACL notices, state, and current hosting binding on load. Authority activation rebinds every retained endpoint and advances its signed publication in one transaction.
store.DirectoryCatalog returns the immutable catalog and the revision of one locked Hub snapshot; DirectoryCatalogAtRevision rejects a stale expected revision without returning bytes. The store projects only committed local lineage, endpoint frames, and a nonremoved active Peer with matching active Pairing.RemoteTrust, completion, request ID, and ceremony digest. It reuses the exact pairing ceremony and both signed approvals, never re-signs them, and selects signing-generation prefixes separately from each relationship's retained accepted lineages. The verifier checks both exact historical signer keys and generations in those prefixes, then proves the prefixes remain in the current authority bundles. It does not reapply approval deadlines or current-generation activation eligibility to historical active relationships. A terminal normal-peer fork or local removal withdraws its relationship in the same committed revision; after bilateral removal, a fresh pairing publishes only its new epoch. It does not use administrative, address, or endpoint listing views as source material. The store compares the candidate's explicit public projection with the committed selection. An identical selection reuses the immutable catalog; a changed selection runs BuildContext before persistence and installs the result only after definite durability. Catalog reads reuse that committed object without verification or copying. The returned whole-Hub revision remains a private local stale-read token, not a public synchronization revision. Floor-only security-time reservations cannot change the public selection and do no catalog construction or unchanged credential validation. Restart and recovery build once after strict store validation; no read signs or repairs records. Precommit failures keep the old snapshot and catalog, and an uncertain write poisons the handle so neither old nor candidate catalog is returned until a complete selected snapshot passes recovery or restart. The cache is memory-only; no catalog file is stored.
Compact catalog transfer value (codec)
Catalog.CompactSnapshot(ctx) serializes the immutable interned selection directly; it never calls Source(). DecodeCompactSnapshot(ctx, bytes, count, digest) verifies the value and returns a newly owned immutable catalog. Source() continues to return independent, mutable copies on every call. This codec is network-independent: it neither creates a Peer nor stages or installs learned state. In particular, the revision returned by store.DirectoryCatalog is a private whole-Hub stale-read token and has no field in this format. A snapshot count and digest are not an origin revision or a connection update sequence.
Compact v1 uses exact signed record frames and exact public ceremony bytes. All integers are unsigned big-endian with fixed widths; indexes are zero-based u16. The single value is:
| 1 | ASCII "AHCC" | u8 version=1 |
| 2 | u16 frame_count | u16 ceremony_count | u16 authority_count | |
| 3 | u16 endpoint_count | u16 relationship_count |
| 4 | frame_count * (u32 frame_length | exact signed frame) |
| 5 | ceremony_count * (u16 ceremony_length | exact ceremony) |
| 6 | authority_count * (u8 lineage_length | lineage_length * u16 frame_index) |
| 7 | endpoint_count * (u16 identity | u16 binding | u16 publication | |
| 8 | u16 revocation | u16 current_origin_authority_index) |
| 9 | relationship_count * (u16 ceremony_index | u16 initiator_approval_frame_index | |
| 10 | u16 target_approval_frame_index | |
| 11 | u16 initiator_authority_index | u8 initiator_prefix_length | |
| 12 | u16 target_authority_index | u8 target_prefix_length) |
Frames and ceremonies each appear once, in strictly increasing unsigned byte-lexicographic order. Authority rows compare their complete ordered frame lists lexicographically, with a prefix before its extension. Endpoints follow endpoint ID order, breaking ties by identity, binding, publication and revocation frame bytes, then origin lineage. Relationships compare ceremony bytes, then initiator and target approval frames, then their signing lineages. Rows with equal signed content are deduplicated after full verification; randomized signature variants select one byte-lexicographically least exact frame. Learned transfers may retain independently valid competing rows for one identity or relationship; the strict local Build path still rejects conflicts. Endpoint indexes select the matching origin bundle, including a fork branch. Approval indexes select the first canonical lineage containing the signed-content-equal signing prefix. An authority's lineage indexes are in genesis-to-head order, length 1 through 65. A relationship's prefix length is 1 through the referenced current lineage length and selects the exact historical signing prefix. Its two approvals remain in initiator, target slot order. An endpoint refers to the complete current origin lineage. Cross-family substitutions and dependencies are checked by the existing scoped catalog verifier, not inferred from indexes. There are no recursive references or extension fields. Empty tables are valid; unused, repeated, missing, cyclic or out-of-range references, alternate ordering, malformed frames, invalid signatures, mismatched prefixes, trailing bytes, and noncanonical representations fail closed.
The snapshot count is exactly the sum of the five header table counts, including each distinct frame and ceremony once. It is zero for the empty value. The snapshot digest is SHA-256(ASCII("AgentHub/directory/compact/v1") || 00 || complete_compact_bytes), raw 32 bytes. Both are external arguments/results, not extra bytes in the value. Digest and count must match before verification; re-encoding the verified catalog must reproduce all input bytes. Caller-provided transfer bytes must remain unchanged during decode; the resulting catalog aliases none of them. The encoded result is independently owned by its caller and may be retained across chunks and retries without rebuilding from Source().
Five row counts fit u16 but have the narrower local-catalog bounds: at most 21,313 distinct frames, 256 ceremonies, 257 authorities, 1,024 endpoints and 256 relationships. Every frame is 1 through records.MaxFrameBytes (32,914) bytes and their sum is at most 16 MiB. Every ceremony is 1 through records.MaxCeremonyBytes (1,233) bytes and their sum is at most 315,648 bytes. MaxCompactBytes is the sum of the header, maximum table payloads, length fields and reference widths (currently 17,225,622 bytes); both encoder and decoder enforce it. The decoder checks the minimum possible row footprint against received length before allocating count-sized tables, and checks individual and cumulative lengths before slicing. It never accepts parser staging beyond the limit, including maximum-payload length-prefix headroom. Structural invalidity or signature failure cannot install a partial catalog. Cancellation between bounded operations returns the context error; cryptographic verification shares the local catalog's limit of 42,626 signature checks while preserving per-scope dependency limits.
MaxCompactWorkingBytes is a conservative aggregate charge for a simultaneous compact value, indexes, decoding and verification scratch and retained catalog. A transfer owner that has not already reserved that charge uses CompactSnapshotReserved or DecodeCompactSnapshotReserved; these reserve before construction, return a release function with successful owned output, and release on failure. The decoder's input staging is independently caller-owned and independently charged. Aggregate reservation failure and byte/count bounds return records.CodeResourceLimit, not CodeInvalidSignature; reservation cancellation returns the context error. The plain methods are for owners that already hold the working reservation. The peersync owner charges its chunk buffers, staging, encoded writes, and queued updates separately. Outbound encoding belongs to the shared directory owner; its reservation survives until the last engine releases that generation. No network synchronization or peer lifecycle changes are included in this codec.
RAM learned-directory owner (package boundary)
NewLearnedDirectory creates a daemon-lifetime owner with no store or transport
connection. Stage accepts a complete compact value, count and digest for an
authenticated peer ID supplied by the eventual sync owner. It reserves the input
copy plus stage metadata before allocation, permits one stage per peer and
sixteen owner-wide by default, and returns a single-use SnapshotStage.
NewLearnedDirectoryForPeers accepts a finite staging population through 256.
Production derives it from protected peer_connection.count, as it does for
peersync.NewSlotsForPeers. The default service therefore admits 256 transport
and directory staging owners without borrowing public TLS pending slots.
Actual input, metadata, scratch and graph allocations still require DATA
reservations; this is not prepayment of 256 maximum snapshots. Verification
remains serialized and cancellation-aware. No snapshot encoding, frame,
repair deadline or per-peer duplicate rule changes. StageOwned instead
consumes an already reserved immutable transport buffer and its release callback
on every return path. Bulk peersync transfers that ownership rather than copying
the complete value again. Ordinary Stage retains its independent-copy contract.
Install
decodes and verifies the complete compact selection, independently re-verifies
its signed records in scoped dependency stores, then applies it to a private
copy of records.LearnedState under the owner lock. Only a successful complete
installation changes the peer contribution, public projection and receiver
high-water marks together. Abort, error paths and Close release reservations;
a concurrent abort or close during verification defers release until verification
finishes. A reservation returning after abort or close never attaches bytes or
ownership to the dead stage. Identical installed count/digest values are
idempotent replacements and retain no extra charge. Reverification reserves the
maximum single-scope scratch requirement, not the sum of every scope's expanded
graph. After independent verification, VerifiedPool interns exact verified
graphs, lineage prefixes, keys and evidence bytes. A candidate acquires references
to matching immutable predecessor allocations only after verifying its own
scopes. Its key includes the exact signed frame, dependency graph and lineage
context. A shared historical key cannot merge different authority roots.
VerifyAuthorityRecordsWithWork verifies every record of one ordered bundle in
one dependency context; it does not reuse predecessor verification results.
Each pool owns its indexes and reference-counted allocation handles. The parent
lookup pin lasts through construction; Rehome imports selected high-water and
fork evidence absent from the input before detaching that pin. No parent-pool
chain survives publication. Immutable frame storage also backs the parsed core,
signature bytes and evidence references. Lineage key and identity prefixes share
bounded slabs with capacity-limited views. A successor never extends a published
predecessor slab or rewrites its metadata. Catalog.Source() still returns fully
independent mutable copies.
Graph leases suballocate chunks from 16 KiB up to one MiB. The last object in any
generation releases its chunk, so tail waste and overlapping readers stay
charged. Object charges include struct sizes, slice capacities, allocation
rounding and ownership metadata; pool indexes have a separate allowance backed
by a maximum-index allocation test. CloneBytes includes selection-map slot
capacity, growth allowance and bounded conflict evidence. A bounded acceptance
scratch phase covers each batch's metadata growth. Its high-water reservation
transfers into the installed state rather than being charged a second time.
LearnedState.RetainedBytes remains a conservative graph diagnostic; directory
ownership uses the pool's shared allocation leases and separate metadata owner. Catalog retention measures actual owned frame
capacities and dependency-reference arrays, with allocation overhead. Parser,
verification and encoding scratch are not falsely retained with each catalog.
Exhaustion at any reservation boundary
rejects the candidate without altering installed state. peersync charges its own chunk buffers, update queue, encoded frames and
in-flight writes. It does not treat this complete-value staging API as a
framing or sequencing codec.
SetLocal(ctx, catalog, reserve) takes a committed local catalog and an aggregate
reservation callback, never a peer trust row. The directory reserves its retained
catalog reference as well as reverification and retained learned records.
Neither this
owner nor a signed pairing approval creates a Peer, pins a successor, learns an
address or changes an endpoint ACL. Local and peer catalogs remain distinct; a higher peer record that disagrees
with the committed local catalog makes that endpoint non-connectable rather
than replacing its locally authored state. Endpoints returns independently owned, sorted opaque rows for at most 1,024
endpoint IDs, and RelationshipEvidence returns bounded historical bilateral
ceremonies with their immediate contributor IDs and a local-source flag. Neither
the evidence nor those contributors asserts a live link, origin reachability,
an authenticated path, or local relationship eligibility. Summaries reports the last verified
compact count and digest per peer. All three are RAM-only projections, not a
client gateway message or a route. A publication is discoverable only when its
current selected binding, endpoint identity and complete replacement revocation
list agree. Publication high-water revisions are keyed by endpoint across binding
changes; the selected publication must still name the selected binding. Lower
publication revisions remain stale, including across peers and after rebinding;
equal revisions with different canonical content quarantine the endpoint.
Hosting and publication usability require the retained current origin head and
generation. The selected endpoint projection carries that exact verified
binding lineage's stable origin root, current authority head and current
authority generation; it is non-connectable if any field is absent or disagrees
with the binding. A retired origin cannot regain hosting selection by signing higher
endpoint revisions. Historical publication signatures still constrain the
endpoint-wide high-water mark, but cannot make a retired tuple usable. Thus an
old signer can affect availability, not restore its hosting eligibility. Historical
pairing approval generations remain valid evidence.
A stale signed peer replacement cannot roll back a newer publication,
binding or access revision. After complete count, digest, canonical-byte and
signature verification, freshness applies to each signed object. Stale forwarded
echoes do not reject unrelated newer records in the same transfer. This lets two
Hubs converge after concurrent independent updates. A newer binding with a stale
publication is not published unless the selected publication names that binding.
Snapshot absence removes that peer's exact
contribution, but does not erase retained signed endpoint state or conflict
evidence. Withdrawal and retirement require signed publication states and remain
separate from route reachability.
Only a committed local relationship replacement or an authenticated participant's
replacement can retire an epoch, keyed by the unordered authority-root pair and
ceremony digest. A direct participant must first have supplied that pair; its
later omission can retire retained epochs for that pair. An unrelated forwarder's
omission removes only its exact contribution and grants no retirement authority.
Retirement survives reconnect and prevents replay from that peer or resurrection
through another peer's stale copy. The retirement set is bounded at 4,096 epochs;
the records owner's smaller signed-request cap also applies. An epoch already
retired is ignored without rejecting unrelated updates, and exhaustion is
CodeResourceLimit. A stale epoch echo cannot retire that peer's newer epoch.
Each peer contribution remains the exact decoded catalog covered by its count
and digest. Receiver-owned retained epochs live in the separately charged
canonical outbound selection, whose own count and digest cover the combined
result. No rows are substituted into a received contribution. Different
ceremonies from different peers have no signed total order. RelationshipEvidence
returns distinct supported ceremonies without allowing an old epoch to suppress
a fresh one. Only conflicts within the signed approval/request semantics exclude
evidence. The previous outbound selection is never a relationship contributor:
a relay replacing E1 with empty state or E2 removes its E1 support. Other
contributors may still supply E1, including stale echoes around a cycle. Those
rows remain explicitly historical evidence, not current topology. Reconnect
retains exact peer contributions; restart clears them. Peer removal is local,
not distributed revocation. Authenticated immediate normal-peer links and
route advertisements, withdrawal and expiry alone establish current usability.
These rules never change local Peer trust or eligibility.
Route identity is the stable authority root. For an endpoint origin it
uses EndpointView.OriginRoot; Origin and OriginGeneration are the exact
current-head verification projection, not a second topology ID. For an immediate
neighbor it uses the authenticated normal-peer link's genesis ID, the same key used
by peer.Manager channel and hold operations. RelationshipEvidence, its
historical participant heads, and contributor IDs are not routing topology and
must not be joined to links. The local store authority view supplies the local
stable root. Thus an operational renewal or approved authority successor does
not rename a route, while an unapproved head cannot become a next hop. Routing
may add its own atomic route projection, but it does not need a wire or directory
record change to identify origins and direct neighbors.
Distinct stable authority roots that share one current head quarantine both roots in learned state. Identical endpoint content verified through those roots does not collapse their lineage scopes or choose an arrival-order winner. The binding remains an authority ambiguity after either root advances to a distinct head; only a strictly higher internally consistent hosting binding selects one root and repairs it. This does not reject the accepted case where roots share only a historical key and have distinct current heads. Outbound compaction keeps separate lineage scopes for identical binding content while one scope remains current, including when the other scope arrived after its root advanced. A fresh receiver therefore reconstructs the same quarantine. Compaction still drops an unmatched retired binding scope, so a stale record with a larger binding revision cannot displace current hosting state.
Equal-revision canonical disagreement and cloned endpoint bindings use bounded
records.LearnedState evidence, not a first-writer winner. A conflict row is
non-connectable and includes endpoint ID, selected or conflicting binding generation,
origin IDs (full fingerprints) and role-correct KEY CHECKs. Ordinary record
conflicts also carry independently owned signed evidence. Current-head and
identical-binding authority ambiguity uses the already retained bounded lineage
state and does not synthesize uncharged frame copies. Displayed origins come from the actual conflict witnesses,
selected binding or explicit local-authoritative disagreement, never unrelated
historical candidates. An internally consistent higher binding/revision repairs
an ordinary conflict, including a cloned-origin conflict. Compaction retains
bounded signed competing bindings that prove an unrelated-origin clone repair
to receivers that missed the conflict. Unsupported unrelated-origin migration
without such proof still fails closed. Evidence exhaustion is a resource
limit, not a bad signature. Cancellation is a context error and signature errors
retain their record code. ErrStaleSnapshot means obsolete staging ownership,
not merely a stale signed object within a fully verified aggregate.
Per-daemon learned authority, pairing-request and comparison-key caps prevent
unbounded accumulation across peer reconnects. Close discards all learned
revisions and contributions; a new owner can temporarily accept an older valid
snapshot after a full restart. No learned data is persisted.
Reachability is not endpoint availability
The routing owner keeps RAM candidates keyed by stable
root. It does not write directory rows, approve a Peer, learn a dial address,
or publish an endpoint. An advertised otherwise unknown root consumes bounded
route capacity only. Endpoint lookup uses verified OriginRoot, never current
head, contributor or historical pairing evidence.
Route presence is not endpoint authorization or a selectable remote carrier.
A remote gateway row becomes available only through the production endpoint
carrier composition, even when the origin is reachable. Production has a route
owner. Real signed/TLS line tests combine a route to verified OriginRoot with
unavailable remote listing and refused direct preparation when no carrier is
selectable; an unknown-origin route DATA test checks that directory identities,
endpoints, Peer trust and dial addresses are unchanged. Structural/live-owner
accounting and the circuit handoff are recorded in the relay
implementation status.
See service integration tests
and the service boundary.
Canonical outbound selection
Outbound(ctx, reserve) returns an immutable {Catalog, Data, Count, Digest}
generation, a change channel and a caller-owned reference release. It combines committed local records with verified
learned records, including retained in-process forwarding evidence. It never
expands Catalog.Source(). The selection keeps the highest signed binding and
access revisions, the endpoint-wide publication high-water dependency tuples,
the highest publications for each retained binding, and up to
two distinct canonical-content witnesses per conflict family. Multiple valid
P-384 signatures for the same record digest consume one witness slot. The
lexicographically smallest exact signed frame represents that digest; compact
exact-frame interning remains separate. Revocation lists replace complete lists,
so removed tags stay removed. Historical competing binding generations remain
repair proofs, with at most two binding contents and two publication contents
per binding. They consume the existing compact endpoint-row and byte limits.
Exhaustion rejects the candidate rather than dropping required repair proof.
Verified binding proofs are applied in increasing generation order before their
higher repair, independently of canonical byte ordering on the wire. A repeated
single branch cannot erase a conflict.
Complete authority lineages travel with their dependency scopes. Linear
successors supersede prefixes. Obsolete origin tuples cannot compete for current
hosting, but their exact publication dependency scopes remain when needed to
carry endpoint-wide high-water evidence. Authority
fork branches remain verifiable evidence rather than trust decisions. Relationship
forwarding uses only current input contributions, excluding locally superseded
epochs. Retained endpoint and authority proofs cannot resurrect an unsupported
ceremony. Distinct supported historical epochs share the same bounded row budget.
The aggregate uses the same byte, frame and table-row limits as a compact local catalog; conflict witnesses consume rows within those limits, not extra capacity. Candidate construction uses a cancellable, shutdown-aware transaction gate. Only one candidate graph per directory is built at a time; readers and bounded transport staging remain independent. A local feed cannot race an echoed peer snapshot into two full speculative graphs before either can publish.
Decode and outbound construction each reserve the unchanged
MaxCompactWorkingBytes allowance before allocation. Exact retained catalog or
encoded-generation ownership is acquired while construction remains charged;
unused working parts are then released. Small catalogs do not retain one-MiB
scratch tails. After decoding, the independently owned catalog no longer needs
the encoded staging buffer, so its input reservation is released before graph
construction.
Peers with the same count and compact digest share one immutable catalog and
one exact retained reservation. Every incoming snapshot first passes full decode,
canonical re-encoding, scoped dependency checks and signature verification.
A claimed digest is never enough to borrow storage. Different valid signature
representations have different compact digests and keep separate catalog owners.
Each contribution and in-flight candidate holds a reference. Replacement or
omission drops only that contribution's reference; abort and close cannot release
storage still held by a candidate. The final reference releases its reservation
once. Peer summaries and relationship contributor provenance remain independent.
Atomic publication swaps the peer/local selection, learned state and outgoing
generation before dropping predecessor ownership. Outstanding output references
retain their old catalog, bytes and reservation until their final release.
TestLearnedSharedCatalogReplacementOwnership and
TestLearnedSharedCatalogCancellationOwnership check exact intermediate charges,
candidate/contribution references, retained old readers and first-versus-last
release through replacement, cancellation and Close. Verification-before-sharing
and distinct P-384 signature representations have separate negative controls.
Exhaustion leaves the previous
selection installed. Closing and replacing one shared notification channel wakes
all engines without a subscriber registry, queue or goroutine per subscriber.
Outbound working-memory proof
The allowance is 77,291,096 bytes. Retained local/peer catalogs and predecessor
output are independently charged RAM, not temporary payload copies. Selection
borrows their frames. Only dependency-reference containers, indexes and bounded
parse caches belong to its working reservation. The exact-frame ID cache holds
at most MaxEndpoints entries; after that, misses parse normally without changing
admission. Intermediate endpoint witnesses retain their existing
2*MaxEndpoints row limit. Publication and revocation families each keep at
most two current contents per ID, and final rows retain MaxEndpoints.
The conservative phase bounds use 512 bytes per indexed entry plus minimum-table allowance. This covers bucket or group slots and controls, overflow, count/header/directory metadata and old/new tables concurrently live during growth on the supported Go runtime. Reference allowances include backing-array capacity, temporary sort/selection arrays, authority and endpoint dependency scopes, and the cloned output's containers. Each semantic-cache owner gets four MiB for its one-MiB frame/core payload, 256-entry map/list metadata, and a complete strict parse miss before eviction, including core, key and tag scratch. No retained verification graph is copied or recharged here.
| Phase | Payload-copy ownership | Conservative live peak |
|---|---|---|
| Selection | No retained payload copies; two semantic owners and bounded selected indexes | 51,716,096 bytes |
| Catalog cloning | At most two compact payloads for owned frames and exact interning keys, all still-live selection indexes, selected container/reference storage and one semantic owner | 71,190,828 bytes |
| Compact encoding | At most three compact payloads for the owned catalog, exact keys and output bytes, table/sort/reference metadata and one semantic owner | 71,109,826 bytes |
Canonicalization's maps/cache are unreachable before cloning. Selection's
identity, endpoint, publication, revocation and nested generation indexes are
conservatively counted as live through cloning in selectOutbound. Their
additional allowance is 4,723,712 bytes. Selection's temporary containers/indexes
are unreachable only after that helper returns, before encoding. The compact
encoder uses one exact-string index per table, with sorted keys borrowing those
strings and installing numeric indexes in place. It has no second copying
frame or ceremony index. Count and byte checks precede new key insertion.
Retained-size measurement after encoding uses a bounded pointer index under
the same reservation; its catalog/output payload and metadata fit below the
encoding bound. Splittable ownership transfers only after these scratch owners
return. Allocator rounding, index growth and old/new output reservations remain
charged; unreachable garbage is not a second live owner.
The directory owner encodes, counts and hashes once per generation under its working reservation, then retains the encoded bytes with the selected catalog. All peer engines and retries share that value through reference-counted handles. Replacing a generation or closing the owner releases its reservation only after the last borrowing engine or in-flight write finishes. Engines assign only their connection-local IDs and send changed count/digest values. Thus a line topology propagates non-neighbor records and signed withdrawals without repeated echo transfers. Learned forwarding state is RAM-only and uses no private store revision as a wire sequence.
Peer sync v1 (service-composed)
internal/agenthub/peersync owns the strict v1 messages and one-connection
engine. The service composes this engine over authenticated normal-peer links; gateway
learned listing now consumes the verified RAM owner; routing remains separate.
The READY hook hands the service an opaque peer.ReadyLink. The service
calls ready.ClaimDirectory(ctx) synchronously before scheduling setup. This
claims only the emitting physical link, never a replacement selected by the
relationship. EstablishPair(ctx, lease) consumes the resulting exact-link
DirectoryLease and uses its authenticated local and remote heads to select
the opener or accepter. Its cancellation and scoped channel operations also
come from that lease, never a raw mux session or captured relationship IDs.
Exactly one designated side opens control (01) then bulk (02),
both with setup ASCII "AHDS" | 01. The manager permanently claims one pair per
physical connection, binds both channels to that exact link, and rejects extra,
wrong-order or wrong-setup directory operations. Generic channel operations cannot
open or accept the reserved directory setup. A failed pair consumes the claim;
retry needs a fresh authenticated normal-peer connection, never pairing TLS.
The returned Pair transfers to Engine.Pair. The engine retains both channel
leases and a managed worker lease until its streams close and its workers join.
Draining signals it to stop; removal, fork, failure and shutdown close transport
and join the worker lease under the normal-peer link's existing barriers. One shared daemon
Slots owner and aggregate Reserve callback must be supplied to each engine.
The engine joins four workers: two readers, one coalesced snapshot writer and
one change-driven aggregate publisher. Managed links also have a joined removal
watcher that cancels verification or a queued construction transaction when the
manager stops that link. Unrelated directory construction cannot strand its
channel-owner removal barrier. The shipped service starts one engine per
selected active link, supplies committed local catalogs and binds successor
staging to current active relationships. The mux itself has
one bounded physical writer and weighted control/bulk scheduling. Later
circuit-control priority and relay bindings are not part of this contract.
Every message is u32be body_length | u8 version=01 | u8 kind | u64be sync_id=1 | kind-specific body. Integers are unsigned big-endian; digest values are raw
32-byte SHA-256 values. No trailing bytes, extensions, zero/alternate IDs,
unknown versions or kinds are accepted. The frame is carried as exact bytes on
its designated mux channel; no framing read-ahead or signed store revision is
involved. Kinds and complete bodies after the common ten bytes:
| Kind | Channel | Body after sync ID |
|---|---|---|
01 SUMMARY | control | `u32 count |
02 SNAPSHOT_BEGIN | bulk | `u64 snapshot_id |
03 SNAPSHOT_CHUNK | bulk | `u64 snapshot_id |
04 SNAPSHOT_END | bulk | `u64 snapshot_id |
05 DELTA | control | `u64 update_id |
06 REPAIR | control | u64 next_expected_update_id |
07 TERMINAL | control | u8 code (01 protocol, 02 resource, 03 invalid signature) |
All unused Message fields must be zero on encode. SUMMARY is exchanged
once in each direction. Its count/digest describe the sender's current compact
aggregate catalog; known_count/digest describe the receiver's contribution as last
installed at the sender. A matching receiver count/digest needs no snapshot;
when the remote known pair differs from the local compact value, send one
snapshot. An inconsistent remote claim of knowledge while our contribution
still differs requests repair. Summary, digest and IDs are not origin revisions;
store.DirectoryCatalog's private whole-Hub revision never enters these bytes.
Sync ID is 1 in each direction on each fresh connection, snapshot IDs and
update IDs start at 1 and increase without wrap on that connection only.
Signed publication/access revisions belong to the exact record frames and do
not reset. SNAPSHOT_BEGIN commits to the number of compact bytes and chunks,
and to the last update sent before that snapshot was selected. A snapshot
contains consecutive 32 KiB chunks (last may be shorter), with one ID, exact
index and count, followed by END. END count and digest are checked against the
complete assembled compact representation. Stage/Install checks canonical
count, digest and signatures before atomically replacing this peer's selection. An update is a complete replacement compact
value, not an append-only record: it preserves withdrawal, retirement,
revocation-list replacement, rebinding and replacement of the sender's historical
relationship contributions. It does not distribute Peer removal or promise
globally current relationship topology. Values
small enough for control (body at most 65536 bytes) go as priority DELTA;
otherwise the owner sends a bulk snapshot. Encoding is retained once directly
from the interned local-plus-learned selection across chunks and retries, never from a
per-peer expanded Catalog.Source().
Outbound construction reserves MaxCompactWorkingBytes before allocation.
Once selection, encoding and measurement scratch are unreachable, outputs of
at least one MiB transfer the existing working leases to catalog and encoded
buffer retention. The retained charge rounds up to MiB parts, including tail
capacity; it does not acquire a second charge for buffers already covered by
work. Smaller outputs acquire exact retention while work remains charged, so
many held tiny generations do not each pin a MiB. Readers keep their original
leases through replacement and directory close. Configured pressure must refuse
a candidate without evicting current output; refill permits retry with those
readers still held. Default maximum-budget viability is a separate opt-in gate.
While a snapshot is being staged, later ordered control updates are held in a
four-entry, charged queue; IDs at or below through_update_id are dropped,
and later ones replay in ID order after verified installation. Outside staging,
only the next update ID installs. A gap, inconsistent summary, chunk/digest
failure, stale replacement or discarded queue requests REPAIR; transfer
staging and queued updates are discarded. The receiver retains the abandoned
snapshot ID and drains its queued CHUNK/END tail without another retry or a
deadline extension. Repair requires a strictly newer BEGIN. At most three repair requests are
sent in either direction on one connection. A summary must arrive within 30
seconds; an open snapshot or pending repair has a two-minute deadline measured
from its begin/repair, not reset by each chunk or mux keepalive. Each control or
bulk frame also has an absolute ten-second completion deadline starting at its
first byte, covering the remaining length prefix and body. Progress never slides
that deadline. An idle channel has no read deadline. Failure releases parser
reservations, closes both channels and joins readers; the service drains the
failed link so the manager can reconnect. Context cancellation remains a context
error rather than poisoned data. A truncated
connection closes without installing a partial snapshot; a subsequent authenticated link repeats summary exchange
against retained RAM learned revisions. Equal verified count/digest on
reconnect transmits no snapshot. A new LearnedDirectory after daemon restart
has no peer contributions or high-water marks, so the next normal link repairs
from an empty learned state. Only locally authored signed origin revisions
persist. A bad signature is terminal rather than a local resource error.
Message body cap is 64 KiB, chunk payload cap 32 KiB, compact length cap is
directory.MaxCompactBytes, and chunk count is exactly the ceiling of length
/ 32768. Parser staging is reserved before allocation and charged until
processing/replay; the full inbound compact buffer is separately reserved
before SNAPSHOT_BEGIN allocates it. At END, StageOwned consumes that buffer's
reservation; decode and verification acquire their own bounded working phases.
Small priority deltas retain the copying Stage path. One stage per authenticated
peer is enforced from BEGIN through install/abort using Slots, in addition to
learned-directory's own install-time stage cap. Both production populations
follow protected peer_connection.count, through 256; only the standalone
zero-argument component constructors default to sixteen. Two
bounded message queues, one queued snapshot request, a single coalesced bulk
writer, and at most one encoded write per channel avoid an unbounded producer
queue. The mux has one physical writer. Channel-write admission has a five-second
deadline; mux queue/credit saturation backpressures senders without using a raw
link stream. Aggregate exhaustion
retains CodeResourceLimit; cancellation retains the context error; neither
is classified as poisoned input. Mux stream errors end the connection and
preserve the last verified learned contribution for reconnect.
LearnedDirectory.VerifiedLineages(ctx, reserve) reserves before returning
independently owned complete signed authority lineages from the retained outbound
selection, including transitive branches; its caller releases the returned charge.
The shipped service compares each to the exact active Peer relationship,
accepted head and request and invokes the normal-peer link's revision-bound staging path. Transport/verification never approves a successor, changes a pin,
creates a Peer, revives removed trust, or learns a dial address. Endpoint TLS,
endpoint ACLs and client admission remain independent mandatory checks.
Daemon composition
The shipped service creates one LearnedDirectory and shared peersync.Slots
per process, preloads the committed local store.DirectoryChanges selection
before binding listeners, and consumes its coalesced close-and-replace signal.
The signal closes only after a definitely durable different public catalog
is selected; private floor, alias, invitation, and revision changes do not
rebuild or transmit a catalog. No per-peer Catalog.Source() expansion or
store revision appears on the wire. The service passes the shared directory
to each manager-leased sync engine, preserving learned contributions on link
loss and discarding them on full service restart.
Following a verified complete peer install or committed local peer-transition decision, a single worker reconciles retained verified authority bundles against all current PeerTargets, including address-free relationships. A coalesced local decision signal carries neither a private revision nor public catalog bytes. Approval of the first successor in a longer lineage wakes reconciliation for the next immediate successor without needing another transfer or reconnect. The worker binds each matching genesis to the current active relationship and request, compares the full accepted prefix, and passes one exact immediate successor to the existing normal-peer revision-bound staging path. It runs separately from the installing engine because a terminal fork revocation joins that engine. Invalid, nonmatching, stale, and address-free relationships gain no consent or address.
Runtime conflict observations
Runtime endpoint, conflict, origin and evidence readers project the same verified local and learned selections. Two independently signed hosting bindings at the same endpoint binding generation remain a hosting conflict even when both origins publish the endpoint. Different publication revisions do not settle that conflict. The endpoint stays non-connectable, while its exact binding conflict, both origins, signed dependency digests and maximum binding generation remain readable for an online repair reference.
records.LearnedState.Selection can propagate a hosting conflict through a
publication whose binding dependency is conflicted. The observation owner
projects that evidence once as a hosting-binding conflict, not as publication
equivocation: its competing digests name bindings, not publications. A genuine
equal-revision publication conflict still has its own publication row and exact
signed publication/dependency evidence. Local disagreement with a higher peer
value compares only a currently selected value; a retained digest with stale,
conflicted or forked status is not a winner. Neither path changes signature
verification, freshness, admission or the authoritative local records.
Conflict digests bind the sorted origin and evidence sets. Repair references remain exact to the runtime generation, sample sequence, endpoint and conflict digest. A signed higher binding with a newer publication can resolve the clone conflict; publication changes alone cannot. A changed observation sample expires the prior reference rather than silently retargeting it.
TestDirectoryObservationPublishedCloneConflict covers published and withdrawn
local selections, lower/equal/higher clone publication revisions, both install
orders, exact evidence sets and signed higher-binding repair. The online command
journey now starts with both origins published; the minimum-directory service
regression retains the withdrawn-local repair case. These are controlled
integration fixtures, not terminal-screen or peer-sync acceptance.
Gateway projection
gateway.ProjectEndpoints combines current local published identities from the
store with LearnedDirectory.GatewayEndpoints() under a bounded list reservation. The
RAM owner has already checked signatures, freshness, replacement and conflicts;
the gateway copies only selected ID/SPKI, publication and availability facts,
access revision, the current tag set, or bounded conflict presentation. It does
not serialize Source(), evidence frames, pairing data, local sockets or addresses.
A local published row uses current store facts even if the asynchronous learned
feed has not caught up. Conflict takes precedence over both local and learned
nonconflicted rows. Route reachability alone cannot make a remote row available;
remote availability requires the selectable production carrier composition. A missing
socket does not change local publication. After
restart, the first list lacks remote rows until authenticated synchronization
rebuilds RAM state; reconnect without restart retains them. Neither a signed
identity nor list presence changes local Peer eligibility or endpoint ACLs.
The gateway contract freezes the exact list bytes.
Runtime cost and timing
Endpoints and GatewayEndpoints visit each shared immutable endpoint catalog
once, with local input first and the canonical outbound selection last. Gateway
capacity counting uses the same traversal before reserving candidate containers.
The traversal compares at most 256² peer metadata pairs and allocates no scratch;
relationship provenance still visits every contributor. Endpoints indexes local
endpoint IDs once per projection. Catalog and outbound sorting reuse IDs already
obtained from verified entries rather than parsing
SPKI during every comparison when present in their bounded advisory caches.
Learned-state authority registration journals only
entries touched by the incoming dependency scope; it does not copy every
retained authority/record map for each accepted record. Rollback, bounded fork
evidence, and independently mutable selection metadata retain their existing
semantics. Outbound and lineage readers honor cancellation while waiting for the
publication mutex.
BuildBatchContext can prepare related local selections with one bounded
cryptographic work batch. Every selection has independent dependency scopes and
catalog limits; only exact signature successes are reused. Its total signature
work remains bounded by MaxSignatureChecks. Runtime candidate verification does
not use this fixture-preparation batch or a predecessor's verified graph as a
verification cache.
WithPhaseObserver enables local, context-scoped timing of encoding,
decode/verification, candidate verification, state acceptance, ownership transfer
and outbound construction. Durations are inclusive; observers must be thread-safe,
return promptly and never re-enter the directory. It has no wire representation
and changes no verification, resource or deadline policy.
Directory and
service fixtures own phase and physical-transfer
timing checks. Broader capacity selection follows the
test ownership policy.
Relay admission and composed pressure
Relay uses EndpointAdmission and WithEndpointAdmission rather than copying
the complete public endpoint projection for each setup. New attempts require
current verified publication, a conflict-free selected binding and the final
stable origin. The directory guard rechecks the captured selection under the
paired admission lock order and again before origin publication. Reattach
fabricates no publication evidence and grants no authorization.
Admission capture and recheck read a precomputed sorted array keyed by endpoint
ID. They allocate nothing, parse no records and require at most eleven search
comparisons. Misses do not grow storage. SetLocal and snapshot Install build
the candidate array before publishing state, catalogs and Changed under the same
directory mutex. Replay, failed reservation and cancellation retain the previous
array; Close clears it and releases ownership. The index preserves selected
tuple completeness, local publication pinning, conflict quarantine and projected
hosting lineage. It has exactly the existing 1,024-endpoint ceiling and rejects
overflow rather than expanding capacity. Its actual directory reservation is
4,096 plus MaxEndpoints * sizeof(EndpointAdmissionView) bytes, 217,088 on amd64.
Construction reserves 1 MiB bounded parsing/selection scratch. Old/new overlap
is charged in full within the unchanged default directory and aggregate budgets.
Production origin preparation uses EndpointSPKI after endpoint quota admission.
It rechecks the exact captured admission under the directory mutex, reserves
4,096 plus records.MaxSPKIBytes DATA bytes for selection scratch and returned
storage, then copies only the selected endpoint key. It visits no catalogs and
projects no unrelated rows, tags, origins or conflict evidence. Reservation
errors retain their cause; cancellation after reservation releases it before
returning. The caller holds the returned release through every retained key
reference, independently of directory replacement or shutdown. Publication,
conflict, local pinning and current-binding checks remain admission requirements.
Index reservation failure rolls back the whole candidate, not only the index.
TestEndpointSPKIReservationAndOwnership,
TestEndpointSPKIUnrelatedConflictsDoNotProject and
TestEndpointSPKIRefusesUnusableAdmissions own allocation refusal, key lifetime
and independence from unrelated conflict evidence. Production quota-before-key,
single lease transfer and failure cleanup belong to the origin tests in
service.
Both capture and commit lock waits honor cancellation. The relay's charged watcher remains active through peer-manager guarded commit, so custom caller contexts do not need an unjoined context propagation worker.
The relay integration tests withdraw and republish signed endpoint state over the required directory channels while eight relay pairs per exact link carry unrelated controls and blocked bulk. Already admitted attachments remain on their fixed links during withdrawal. This proves coexistence, not circuit authentication or permission to resume endpoint bytes. Remote gateway availability belongs to the production endpoint carrier composition.
Circuit authority proof and recheck
Circuit authority selection belongs to circuit bootstrap. The
circuit contract describes the current
bootstrap and recovery boundary.
LearnedDirectory.ResolveCircuitAuthority(ctx, root, reserve) takes the remote
stable root only from immutable attachment metadata. It selects one complete
maximal nonconflicted authority lineage from the endpoint's own verified local
directory. It does not query a nonadjacent Peer, approve a remote head, or create
persistent trust. A-B-C needs only A/B and B/C Peer relationships. Neighboring
Peer successor policy is unchanged.
The resolver reserves 4 MiB before waiting for the directory publication lock or
parsing frames. It compares bounded signed-content digest prefixes in already
verified catalog bundles and requires the selected head and generation to match
records.LearnedState.CircuitAuthorityProjection. Missing evidence, stale
prefixes, forks, incomparable lineages and a conflicted projection deny selection.
The attempt retains at most one complete 65-frame lineage and a RAM-only head.
No lineage is transferred in relay setup, a preface or bootstrap TLS.
A selection owns one lifetime BorrowHead(ctx) slot. The resulting borrow's
Head(ctx) supplies the checked public authority projection to circuit-only TLS
providers. Providers retain that borrow through credential loading and TLS
construction, check it before and after loading, and erase rejected credentials.
Bootstrap calls selection Recheck(ctx) before confirmation. Every directory
publication change, including change-and-restore, and directory shutdown
invalidate the captured publication token. Neither directory nor store locks
span network I/O.
Selection storage has one Head-read slot, one Recheck-read slot and one close
completion. Close() seals new access, joins admitted reads and the lifetime
borrow, clears retained frames and SPKI, then releases the proof charge. It uses
no helper worker. The borrower must Release() before selection Close can
finish. Nil, canceled, zero, released and closing handles reject access.
The circuit contract owns bootstrap binding, local authority projection, TLS retirement and endpoint reservations. The link guide owns circuit provider policy and exact TLS/raw-byte handoff. Circuit TLS proves Hub possession and establishes controls; endpoint TLS and ACL checks alone authorize application access. The service circuit tests cover proof/provider lifetime and real signed TCP/TLS A-B-C composition without nonadjacent approval or access-state mutation. Production installs the endpoint consumers; missing consumers still deny new and reattach attempts.