@optimystic/db-core 1.20.1 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/src/btree/btree.d.ts +36 -4
  2. package/dist/src/btree/btree.d.ts.map +1 -1
  3. package/dist/src/btree/btree.js +86 -18
  4. package/dist/src/btree/btree.js.map +1 -1
  5. package/dist/src/cohort-topic/gossip/bus.d.ts +15 -14
  6. package/dist/src/cohort-topic/gossip/bus.d.ts.map +1 -1
  7. package/dist/src/cohort-topic/gossip/bus.js +15 -16
  8. package/dist/src/cohort-topic/gossip/bus.js.map +1 -1
  9. package/dist/src/cohort-topic/ports.d.ts +30 -4
  10. package/dist/src/cohort-topic/ports.d.ts.map +1 -1
  11. package/dist/src/cohort-topic/ports.js +14 -0
  12. package/dist/src/cohort-topic/ports.js.map +1 -1
  13. package/dist/src/cohort-topic/registration/renewal.d.ts +27 -1
  14. package/dist/src/cohort-topic/registration/renewal.d.ts.map +1 -1
  15. package/dist/src/cohort-topic/registration/renewal.js +15 -4
  16. package/dist/src/cohort-topic/registration/renewal.js.map +1 -1
  17. package/dist/src/cohort-topic/service.d.ts +21 -4
  18. package/dist/src/cohort-topic/service.d.ts.map +1 -1
  19. package/dist/src/cohort-topic/service.js +208 -18
  20. package/dist/src/cohort-topic/service.js.map +1 -1
  21. package/dist/src/cohort-topic/willingness.d.ts +1 -1
  22. package/dist/src/cohort-topic/willingness.js +1 -1
  23. package/dist/src/cohort-topic/wire/codec.d.ts +3 -1
  24. package/dist/src/cohort-topic/wire/codec.d.ts.map +1 -1
  25. package/dist/src/cohort-topic/wire/codec.js +7 -1
  26. package/dist/src/cohort-topic/wire/codec.js.map +1 -1
  27. package/dist/src/cohort-topic/wire/index.d.ts +1 -1
  28. package/dist/src/cohort-topic/wire/index.d.ts.map +1 -1
  29. package/dist/src/cohort-topic/wire/index.js +1 -1
  30. package/dist/src/cohort-topic/wire/index.js.map +1 -1
  31. package/dist/src/cohort-topic/wire/types.d.ts +17 -1
  32. package/dist/src/cohort-topic/wire/types.d.ts.map +1 -1
  33. package/dist/src/cohort-topic/wire/validate.d.ts +15 -1
  34. package/dist/src/cohort-topic/wire/validate.d.ts.map +1 -1
  35. package/dist/src/cohort-topic/wire/validate.js +39 -0
  36. package/dist/src/cohort-topic/wire/validate.js.map +1 -1
  37. package/dist/src/collection/collection.d.ts +43 -5
  38. package/dist/src/collection/collection.d.ts.map +1 -1
  39. package/dist/src/collection/collection.js +60 -13
  40. package/dist/src/collection/collection.js.map +1 -1
  41. package/dist/src/collection/struct.d.ts +6 -0
  42. package/dist/src/collection/struct.d.ts.map +1 -1
  43. package/dist/src/collection/struct.js.map +1 -1
  44. package/dist/src/collections/tree/tree.d.ts +3 -1
  45. package/dist/src/collections/tree/tree.d.ts.map +1 -1
  46. package/dist/src/collections/tree/tree.js +11 -5
  47. package/dist/src/collections/tree/tree.js.map +1 -1
  48. package/dist/src/network/struct.d.ts +15 -0
  49. package/dist/src/network/struct.d.ts.map +1 -1
  50. package/dist/src/network/struct.js.map +1 -1
  51. package/dist/src/testing/test-transactor.js +6 -2
  52. package/dist/src/testing/test-transactor.js.map +1 -1
  53. package/dist/src/transaction/coordinator.d.ts +6 -0
  54. package/dist/src/transaction/coordinator.d.ts.map +1 -1
  55. package/dist/src/transaction/coordinator.js +6 -0
  56. package/dist/src/transaction/coordinator.js.map +1 -1
  57. package/dist/src/transactor/network-transactor.d.ts.map +1 -1
  58. package/dist/src/transactor/network-transactor.js +1 -0
  59. package/dist/src/transactor/network-transactor.js.map +1 -1
  60. package/package.json +1 -1
  61. package/src/btree/btree.ts +92 -18
  62. package/src/cohort-topic/gossip/bus.ts +25 -26
  63. package/src/cohort-topic/ports.ts +31 -4
  64. package/src/cohort-topic/registration/renewal.ts +40 -5
  65. package/src/cohort-topic/service.ts +251 -21
  66. package/src/cohort-topic/willingness.ts +1 -1
  67. package/src/cohort-topic/wire/codec.ts +12 -0
  68. package/src/cohort-topic/wire/index.ts +3 -0
  69. package/src/cohort-topic/wire/types.ts +20 -0
  70. package/src/cohort-topic/wire/validate.ts +45 -0
  71. package/src/collection/collection.ts +3098 -3039
  72. package/src/collection/struct.ts +463 -456
  73. package/src/collections/tree/tree.ts +15 -7
  74. package/src/network/struct.ts +770 -755
  75. package/src/testing/test-transactor.ts +5 -2
  76. package/src/transaction/coordinator.ts +6 -0
  77. package/src/transactor/network-transactor.ts +1897 -1896
@@ -8,6 +8,9 @@ import type { TreeBlock } from "./tree-block.js";
8
8
  import { AtomicProxy, type AtomicScope } from "../transform/atomic-proxy.js";
9
9
  import { jsonEncodedBytes } from "../network/transaction-size.js";
10
10
  import { branchItemBytes, divideItems, emptyBranchBytes, emptyLeafBytes, leafItemBytes, runOf } from "./node-division.js";
11
+ import { createLogger } from "../logger.js";
12
+
13
+ const log = createLogger('btree');
11
14
 
12
15
  export const NodeCapacity = 64;
13
16
 
@@ -98,15 +101,23 @@ export class BTree<TKey, TEntry> {
98
101
  return await this.getPath(await this.trunk.get(), key, navigate);
99
102
  }
100
103
 
101
- /** Retrieves the entry for the given key.
102
- * Use find instead for a path to the key, the nearest match, or as a basis for navigation.
104
+ /** Retrieves the entry for the given key, as the tree stood at some moment during the call.
105
+ * Never throws for a change that lands while it reads: a descent that a change tore is read
106
+ * again ({@link readUnchanged}). Use find instead for a path to the key, the nearest match, or as
107
+ * a basis for navigation.
108
+ *
109
+ * NOTE: "some moment" holds only for changes that move {@link _version}: this tree's own writes
110
+ * and {@link invalidatePaths}, which `Tree` calls for every change its collection reports. A
111
+ * BTree used on its own over a store that something else mutates gets only the first.
103
112
  * @returns the entry for the given key if found; undefined otherwise. */
104
113
  async get(key: TKey): Promise<TEntry | undefined> {
105
114
  // Value-of-key point lookup: the result depends ONLY on the terminal leaf's content, so the
106
115
  // interior descent nodes are pure navigation and are dropped from the OCC conflict set. The
107
- // returned Path is consumed by `at` and discarded — it never seeds a scan — so navigate=true
108
- // is safe here (unlike the public `find`).
109
- return this.at(await this.find(key, /* navigate */ true));
116
+ // returned Path is read here and discarded — it never seeds a scan — so navigate=true is safe
117
+ // here (unlike the public `find`). Not validated: the leaf it holds was read with nothing
118
+ // changing, and is that moment's entry however many hops ago the descent finished.
119
+ const path = await this.readUnchanged('get', () => this.find(key, /* navigate */ true));
120
+ return path.on ? this.getEntry(path) : undefined;
110
121
  }
111
122
 
112
123
  /** @returns the entry for the given path if on an entry; undefined otherwise. */
@@ -115,24 +126,25 @@ export class BTree<TKey, TEntry> {
115
126
  return path.on ? this.getEntry(path) : undefined;
116
127
  }
117
128
 
118
- /** Iterates based on the given range
119
- * WARNING: mutation during iteration will result in an exception
129
+ /** Iterates based on the given range.
130
+ * Finding where the scan starts and ends never throws for a change that lands meanwhile: it is
131
+ * read again ({@link readUnchanged}), so a scan that has yielded nothing has not failed.
132
+ * WARNING: mutation during iteration — once a path has been yielded — will result in an exception
120
133
  */
121
134
  async *range(range: KeyRange<TKey>): AsyncIterableIterator<Path<TKey, TEntry>> {
122
- const startPath = range.first
123
- ? await this.findFirst(range)
124
- : (range.isAscending ? await this.first() : await this.last());
125
- const endPath = range.last
126
- ? await this.findLast(range)
127
- : (range.isAscending ? await this.last() : await this.first());
128
- // If the tree is empty or endPath is not on an entry, return early
129
- if (!endPath.on) {
135
+ let bounds: RangeBounds<TKey, TEntry> | undefined;
136
+ do {
137
+ bounds = await this.readUnchanged('range', () => this.rangeBounds(range));
138
+ // Read with nothing changing, but handed back a few microtask hops ago: checked again here,
139
+ // in the same synchronous step as the iteration's first validation of the start path below.
140
+ } while (bounds !== undefined && !this.isValid(bounds.start));
141
+ if (bounds === undefined) {
130
142
  return;
131
143
  }
132
- const endKey = this.keyFromPath(endPath);
144
+ const { start, endKey } = bounds;
133
145
  const iterable = range.isAscending
134
- ? this.internalAscending(startPath)
135
- : this.internalDescending(startPath);
146
+ ? this.internalAscending(start)
147
+ : this.internalDescending(start);
136
148
  const iter = iterable[Symbol.asyncIterator]();
137
149
  const ascendingFactor = range.isAscending ? 1 : -1;
138
150
  for await (let path of iter) {
@@ -146,6 +158,65 @@ export class BTree<TKey, TEntry> {
146
158
  }
147
159
  }
148
160
 
161
+ /** Every entry in `range`, in the range's order, as the tree stood at some moment during the call.
162
+ * A range read that hands back one value: like {@link get}, it never throws for a concurrent
163
+ * change, but reads the whole range again ({@link readUnchanged}). For a range small enough to
164
+ * hold in memory and to read again; a scan that must stream, or may be long, uses {@link range}. */
165
+ async entriesIn(range: KeyRange<TKey>): Promise<TEntry[]> {
166
+ return await this.readUnchanged('entriesIn', async () => {
167
+ const entries: TEntry[] = [];
168
+ for await (const path of this.range(range)) {
169
+ entries.push(this.getEntry(path));
170
+ }
171
+ return entries;
172
+ });
173
+ }
174
+
175
+ /** Where a scan of `range` starts and the key it ends at, or `undefined` when the tree is empty or
176
+ * the range's end is not on an entry, so there is nothing to scan. */
177
+ private async rangeBounds(range: KeyRange<TKey>): Promise<RangeBounds<TKey, TEntry> | undefined> {
178
+ const start = range.first
179
+ ? await this.findFirst(range)
180
+ : (range.isAscending ? await this.first() : await this.last());
181
+ const end = range.last
182
+ ? await this.findLast(range)
183
+ : (range.isAscending ? await this.last() : await this.first());
184
+ return end.on ? { start, endKey: this.keyFromPath(end) } : undefined;
185
+ }
186
+
187
+ /** Run `read` — one descent or several — until it finishes with no change to the tree landing
188
+ * while it ran ({@link _version} unmoved), and return what it read: every block it read is then
189
+ * of one moment. Reads are not latched, so a change can land between any two of them — a replay
190
+ * that rebuilds staged nodes under fresh ids, a refresh that adopts newer blocks — and a descent
191
+ * across one can follow an id that no longer exists, or an old branch to a new leaf that no
192
+ * longer holds the key.
193
+ *
194
+ * A throw while the version moved is retried too: it is that change's symptom (`Missing block`
195
+ * for a removed id, an invalid path from a step that validates one), not a fault. With the
196
+ * version unmoved it propagates unchanged. That is an exception used as control flow, on purpose,
197
+ * and only behind a concurrent change detected independently of it.
198
+ *
199
+ * NOTE: unbounded. Each retry needs another change to land inside a descent of a few block reads,
200
+ * and every source of change (a drain step, a refresh) is finite work. If a storm of
201
+ * `btree:read-retried` lines is ever seen, bound the loop and report the contention instead. */
202
+ private async readUnchanged<T>(what: string, read: () => Promise<T>): Promise<T> {
203
+ for (;;) {
204
+ const version = this._version;
205
+ try {
206
+ const result = await read();
207
+ if (this._version === version) {
208
+ return result;
209
+ }
210
+ log('btree:read-retried what=%s reason=changed', what);
211
+ } catch (err) {
212
+ if (this._version === version) {
213
+ throw err;
214
+ }
215
+ log('btree:read-retried what=%s reason=%s', what, err instanceof Error ? err.message : String(err));
216
+ }
217
+ }
218
+ }
219
+
149
220
  /** @returns true if the given path remains valid; false if the tree has been mutated, invalidating the path. */
150
221
  isValid(path: Path<TKey, TEntry>) {
151
222
  return path.version === this._version;
@@ -1033,6 +1104,9 @@ export class BTree<TKey, TEntry> {
1033
1104
  /** A node's bytes weighed against the tree's byte target, measured once per rebalance. */
1034
1105
  type NodeFill = { bytes: number; target: number };
1035
1106
 
1107
+ /** Where a range scan starts, and the key past which it stops. */
1108
+ type RangeBounds<TKey, TEntry> = { start: Path<TKey, TEntry>; endKey: TKey };
1109
+
1036
1110
  /** What a node that divided hands its parent: the nodes now to its right, each under the lowest key
1037
1111
  * beneath it, and which of the resulting nodes the path's entry is in — 0 for the node that divided,
1038
1112
  * 1 for the first to its right, and so on. */
@@ -7,17 +7,18 @@
7
7
  *
8
8
  * - **broadcasts** outbound gossip over the injected {@link ICohortGossipTransport} (FRET cohort
9
9
  * gossip underneath — db-core never imports FRET);
10
- * - **routes by coord**: a delivered frame is fanned to every coord engine's bus on a node, so each
11
- * bus merges only the gossip whose `coord` names its own cohort (epoch alone never isolates two
12
- * coords — they can share a member set, hence an epoch);
10
+ * - **subscribes by coord**: the transport decodes each inbound frame once and hands it only to the
11
+ * buses subscribed under the `coord` it names; the bus still checks the coord itself before any merge
12
+ * (epoch alone never isolates two coords — they can share a member set, hence an epoch);
13
13
  * - **merges inbound** gossip — record deltas into the {@link RegistrationStore} (last-writer-wins
14
14
  * by `lastPing`; evictions remove), and willingness/load/summaries into the per-member
15
15
  * {@link CohortView};
16
16
  * - **detects epoch drift**: an inbound `cohortEpoch` that differs from the local epoch fires the
17
17
  * drift handlers, and record deltas under a foreign epoch are *not* merged (their slot
18
18
  * assignments belong to a different membership snapshot);
19
- * - **optionally authenticates** inbound transport frames via an injected {@link GossipInboundVerifier}
20
- * (db-p2p binds peer-sig + cohort membership), dropping forged or non-member gossip before any merge.
19
+ * - **optionally gates** inbound transport frames via an injected {@link GossipInboundVerifier} (db-p2p
20
+ * binds cohort membership), dropping non-member gossip before any merge. The frame's signature is the
21
+ * transport's job: an authenticating transport verifies it once, before any bus sees the frame.
21
22
  *
22
23
  * Convergence target (doc): a single gossip round spreads a touched record / willingness flip to all
23
24
  * members — one {@link CohortGossipBus.applyInbound} of that gossip makes it visible locally.
@@ -26,8 +27,8 @@
26
27
  import { bytesEqual, bytesKey } from "../registration/bytes.js";
27
28
  import type { RegistrationStore } from "../registration/types.js";
28
29
  import { clampTtl } from "../registration/types.js";
29
- import type { ICohortGossipTransport, PeerRef, RingCoord } from "../ports.js";
30
- import { b64urlToBytes, decodeCohortGossipV1, encodeCohortMessage } from "../wire/codec.js";
30
+ import type { ICohortGossipTransport, RingCoord } from "../ports.js";
31
+ import { b64urlToBytes, encodeCohortMessage } from "../wire/codec.js";
31
32
  import type { ChildLinkRefV1, CohortGossipV1 } from "../wire/types.js";
32
33
  import { fromGossipRecord } from "./records.js";
33
34
  import { createCohortView, type CohortView, type MutableCohortView } from "./view.js";
@@ -36,7 +37,7 @@ import { createCohortView, type CohortView, type MutableCohortView } from "./vie
36
37
  export type GossipHandler = (g: CohortGossipV1) => void;
37
38
  /** Handler for a detected cohort-epoch drift on an inbound gossip. */
38
39
  export type DriftHandler = (inboundEpoch: Uint8Array, localEpoch: Uint8Array, from: string) => void;
39
- /** Authenticity gate for an inbound gossip arriving over the transport — `false` drops the frame. */
40
+ /** The bus's own gate for an inbound gossip arriving over the transport — `false` drops the frame. */
40
41
  export type GossipInboundVerifier = (g: CohortGossipV1) => boolean;
41
42
 
42
43
  export interface CohortGossipBusDeps {
@@ -50,16 +51,16 @@ export interface CohortGossipBusDeps {
50
51
  localEpoch: () => Uint8Array;
51
52
  /** Wall clock for inbound merges via the transport path; injectable for tests. */
52
53
  now?: () => number;
53
- /** Frame ceiling for encode/decode (defaults to the codec default). */
54
+ /** Frame ceiling for outbound encode (defaults to the codec default); inbound frames arrive decoded. */
54
55
  maxMessageBytes?: number;
55
56
  /**
56
- * Optional authenticity gate run on every gossip arriving over the transport (db-p2p binds it to the
57
- * peer-sig primitive: verify `fromMember`'s signature over the gossip image **and** that `fromMember`
58
- * is a member of this coord's cohort). A `false` verdict drops the frame — no merge, no handler fire —
59
- * so a forged or non-member gossip can neither spoof willingness/load nor replicate fake records.
60
- * Absent → the gate is skipped (unit tests / key-less interim mode); the `coord` routing check below
61
- * still runs regardless. Not applied to direct {@link CohortGossipBus.applyInbound} calls (the trusted
62
- * test/internal merge entry point).
57
+ * Optional gate run on every gossip arriving over the transport — the bus's own check, after the transport
58
+ * has authenticated the frame. db-p2p binds it to cohort membership: `fromMember` must be a member of this
59
+ * coord's cohort, so a frame signed by a peer outside the cohort can neither spoof willingness/load nor
60
+ * replicate fake records. A `false` verdict drops the frame — no merge, no handler fire. Absent → the gate
61
+ * is skipped (unit tests / key-less interim mode); the `coord` routing check below still runs regardless.
62
+ * Not applied to direct {@link CohortGossipBus.applyInbound} calls (the trusted test/internal merge entry
63
+ * point).
63
64
  */
64
65
  verifyInbound?: GossipInboundVerifier;
65
66
  /**
@@ -109,7 +110,7 @@ class TransportCohortGossipBus implements CohortGossipBus {
109
110
 
110
111
  constructor(private readonly deps: CohortGossipBusDeps) {
111
112
  this.now = deps.now ?? ((): number => Date.now());
112
- this.detach = deps.transport.onMessage((_from: PeerRef, msg: Uint8Array) => this.onInbound(msg));
113
+ this.detach = deps.transport.onGossip(deps.coord, (g: CohortGossipV1) => this.onInbound(g));
113
114
  }
114
115
 
115
116
  broadcast(g: CohortGossipV1): void {
@@ -127,10 +128,9 @@ class TransportCohortGossipBus implements CohortGossipBus {
127
128
  }
128
129
 
129
130
  applyInbound(g: CohortGossipV1, now: number): void {
130
- // Coord routing: a frame is fanned to every coord engine's bus, but it belongs only to the bus
131
- // whose coord it names. Drop any gossip for another cohort so it cannot merge into this store/view
132
- // (two coords on one node can even share a member set — and thus an epoch — so epoch alone never
133
- // isolates them).
131
+ // Coord routing: a frame belongs only to the bus whose coord it names. Drop any gossip for another
132
+ // cohort so it cannot merge into this store/view (two coords on one node can even share a member set —
133
+ // and thus an epoch — so epoch alone never isolates them).
134
134
  if (!this.isOurCoord(g)) {
135
135
  return;
136
136
  }
@@ -164,14 +164,13 @@ class TransportCohortGossipBus implements CohortGossipBus {
164
164
  this.detach();
165
165
  }
166
166
 
167
- private onInbound(msg: Uint8Array): void {
168
- const g = decodeCohortGossipV1(msg, this.deps.maxMessageBytes);
169
- // Cheap routing check first so a non-matching coord skips the (expensive) signature verify.
167
+ private onInbound(g: CohortGossipV1): void {
168
+ // The transport routes by coord already; this guard keeps a misrouted frame out of the gate and merge.
170
169
  if (!this.isOurCoord(g)) {
171
170
  return;
172
171
  }
173
- // Authenticity gate (db-p2p binds peer-sig + cohort membership); a forged/non-member gossip is
174
- // dropped before any merge or handler fire. Absent in key-less/unit composition.
172
+ // The bus's own gate (db-p2p binds cohort membership); a non-member gossip is dropped before any merge
173
+ // or handler fire. Absent in key-less/unit composition.
175
174
  if (this.deps.verifyInbound !== undefined && !this.deps.verifyInbound(g)) {
176
175
  return;
177
176
  }
@@ -13,7 +13,7 @@
13
13
  * `cohort-topic-package-layering` for the authoritative layering rule.
14
14
  */
15
15
 
16
- import type { MembershipCertV1 } from "./wire/types.js";
16
+ import type { CohortGossipV1, MembershipCertV1 } from "./wire/types.js";
17
17
 
18
18
  /**
19
19
  * Ring coordinate — SHA-256 truncated to the ring width `B` (see {@link IRingHash}). db-core
@@ -56,6 +56,14 @@ export interface ITopicRouter {
56
56
  routeAndAct(key: TopicRouteKey, activity: Uint8Array, opts: { wantK: number; minSigs: number }): Promise<Uint8Array>;
57
57
  /** Direct dial to a cached primary; falls back to {@link routeAndAct} on failure (caller decides). */
58
58
  dialMember(member: PeerRef, activity: Uint8Array): Promise<Uint8Array>;
59
+ /**
60
+ * Send an encoded `RenewBatchV1` — several plain renewal pings — to `member` and resolve its encoded
61
+ * `RenewBatchReplyV1`. Rejects with {@link RenewBatchUnsupportedError} when the member does not speak the
62
+ * batch protocol, so the caller can send the same pings singly through {@link dialMember}; any other failure
63
+ * rejects as {@link dialMember}'s does. Optional: a router without it gets no batching, and every ping goes
64
+ * through {@link dialMember}.
65
+ */
66
+ dialMemberRenewBatch?(member: PeerRef, frame: Uint8Array): Promise<Uint8Array>;
59
67
  /**
60
68
  * Deliver `activity` to the **root group** of a root-placed topic — the peers responsible for
61
69
  * `rootKey` — and return the encoded reply. Optional: the walk uses it for the tier-0 step of a
@@ -69,6 +77,19 @@ export interface ITopicRouter {
69
77
  routeToRoot?(rootKey: Uint8Array, activity: Uint8Array): Promise<Uint8Array>;
70
78
  }
71
79
 
80
+ /**
81
+ * What {@link ITopicRouter.dialMemberRenewBatch} rejects with when the member does not speak the batch protocol
82
+ * (a build that predates it). That is a definite answer about the member, unlike a link failure, so the pings
83
+ * are re-sent singly rather than counted as failed. A db-core class because db-core cannot see libp2p's errors;
84
+ * the router maps the transport's own refusal onto it.
85
+ */
86
+ export class RenewBatchUnsupportedError extends Error {
87
+ constructor(readonly member: Uint8Array, options?: { cause?: unknown }) {
88
+ super("cohort-topic: the member does not speak the renew-batch protocol", options);
89
+ this.name = "RenewBatchUnsupportedError";
90
+ }
91
+ }
92
+
72
93
  /**
73
94
  * The per-coord rule for a **root-placed** cohort — the root of a topic whose tier-0 coordinate is
74
95
  * `H(rootKey)` (see `addressing.ts`). Such a cohort is the group of peers responsible for the root key
@@ -101,12 +122,18 @@ export interface MembershipLookupOptions {
101
122
  readonly rootPlaced?: true;
102
123
  }
103
124
 
104
- /** Intra-cohort gossip transport (FRET cohort gossip underneath). */
125
+ /**
126
+ * Intra-cohort gossip transport (FRET cohort gossip underneath). Outbound frames are encoded by the caller;
127
+ * inbound frames are decoded once by the transport and handed only to the subscribers of the coord they name.
128
+ */
105
129
  export interface ICohortGossipTransport {
106
130
  /** Fire-and-forget broadcast of `msg` to the cohort at `coord`. */
107
131
  broadcast(coord: RingCoord, msg: Uint8Array): void;
108
- /** Subscribe to inbound cohort gossip; returns an unsubscribe handle. */
109
- onMessage(handler: (from: PeerRef, msg: Uint8Array) => void): () => void;
132
+ /**
133
+ * Subscribe to inbound cohort gossip naming `coord`; returns an unsubscribe handle. A frame reaches a handler
134
+ * decoded, and, when the transport authenticates frames, only after its signature verified.
135
+ */
136
+ onGossip(coord: RingCoord, handler: (g: CohortGossipV1) => void): () => void;
110
137
  }
111
138
 
112
139
  /** Authoritative cohort membership snapshots (FRET `MembershipCertV1` / stabilization underneath). */
@@ -26,6 +26,11 @@
26
26
  * rate limit, and a one-off `unknown_registration` from replication lag clears on the next ping.
27
27
  * - Cohort-side: evict where `now − lastPing > ttl`; eviction is gossiped so members converge.
28
28
  *
29
+ * A participant's cycle has two halves — `preparePing` (sign this cycle's ping and name its primary) and
30
+ * `settlePing` (act on the answer) — so a caller renewing many registrations can send the pings that share a
31
+ * primary in one request (`CohortTopicService.renewMany`) and settle each with its own answer. `pingLoop` is the
32
+ * two halves around one transport send. Re-attaches and withdraws are never split this way: they go singly.
33
+ *
29
34
  * Both sides take their transport/gossip by injection so storage + sharding + TTL stay unit-testable
30
35
  * in isolation; db-core never imports FRET or libp2p here.
31
36
  */
@@ -40,10 +45,32 @@ import type { RegistrationRecord, RegistrationStore } from "./types.js";
40
45
 
41
46
  // --- participant side ---
42
47
 
48
+ /** One cycle's plain ping, signed and addressed; {@link RenewalParticipant.settlePing} acts on its answer. */
49
+ export interface PreparedPing {
50
+ /** The member the ping goes to: the participant's current primary. */
51
+ readonly target: Uint8Array;
52
+ readonly msg: RenewV1;
53
+ }
54
+
43
55
  /** Participant-side TTL renewal: periodic ping with 3-fail backup promotion. */
44
56
  export interface RenewalParticipant {
45
- /** Run one ping cycle: ping the current primary, count failures, promote/relookup as needed. */
57
+ /**
58
+ * Run one ping cycle: ping the current primary, count failures, promote/relookup as needed. The same as
59
+ * {@link preparePing}, sending the ping through the transport (a rejection is no answer), then {@link settlePing}.
60
+ */
46
61
  pingLoop(): Promise<void>;
62
+ /**
63
+ * The first half of a cycle, for a caller that sends several participants' pings together: this cycle's
64
+ * signed plain ping and the member it goes to. Rejects when the signer does; that is a failed ping, to be
65
+ * settled with no answer.
66
+ */
67
+ preparePing(): Promise<PreparedPing>;
68
+ /**
69
+ * The second half: act on the prepared ping's answer — `undefined` for none — as {@link pingLoop} does. `ok`
70
+ * resets the failure count, `primary_moved` adopts the named primary, backups and epoch, and anything else
71
+ * is a strike; the third strike in a row fails over, re-attaching to the backups singly and then re-walking.
72
+ */
73
+ settlePing(reply: RenewReplyV1 | undefined): Promise<void>;
47
74
  /** Re-attach to `target` (a backup), carrying the existing record; resolves with the reply. */
48
75
  reattach(target: Uint8Array): Promise<RenewReplyV1>;
49
76
  /**
@@ -124,7 +151,14 @@ class TtlRenewalParticipant implements RenewalParticipant {
124
151
  }
125
152
 
126
153
  async pingLoop(): Promise<void> {
127
- const reply = await this.trySend(this.current.primary);
154
+ await this.settlePing(await this.tryPing());
155
+ }
156
+
157
+ async preparePing(): Promise<PreparedPing> {
158
+ return { target: this.current.primary, msg: await this.buildRenew({}) };
159
+ }
160
+
161
+ async settlePing(reply: RenewReplyV1 | undefined): Promise<void> {
128
162
  if (reply !== undefined && this.acceptPingReply(reply)) {
129
163
  return;
130
164
  }
@@ -146,10 +180,11 @@ class TtlRenewalParticipant implements RenewalParticipant {
146
180
  }
147
181
  }
148
182
 
149
- /** Send a renew, mapping an RPC rejection to `undefined` (a counted failure). */
150
- private async trySend(target: Uint8Array): Promise<RenewReplyV1 | undefined> {
183
+ /** Prepare and send this cycle's ping, mapping a signer or RPC rejection to `undefined` (a counted failure). */
184
+ private async tryPing(): Promise<RenewReplyV1 | undefined> {
151
185
  try {
152
- return await this.deps.transport.send(target, await this.buildRenew({}));
186
+ const { target, msg } = await this.preparePing();
187
+ return await this.deps.transport.send(target, msg);
153
188
  } catch {
154
189
  return undefined;
155
190
  }