@kumiai/rpc 0.1.0 → 0.3.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.
package/lib/peer.js CHANGED
@@ -1,31 +1,84 @@
1
1
  import { BroadcastClient, createBroadcastTransport, defaultJitter, defaultRandomID } from '@kumiai/broadcast';
2
2
  import { createGroupBusServer } from './bus-server.js';
3
+ import { classifyCommit } from './classify.js';
4
+ import { CommitDeadlineError, isHeadMismatch, JournalEpochError, RecoveryRequiredError } from './commit.js';
5
+ import { decodeCommitFrame, encodeCommitFrame } from './commit-frame.js';
6
+ import { isMissingLedgerEntries } from './crypto.js';
7
+ import { asLogPosition } from './cursor.js';
3
8
  import { createDirectedClient, createInboxAcceptor } from './directed.js';
4
9
  import { adaptBusHandlers } from './handlers.js';
5
10
  import { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND } from './handshake.js';
6
11
  import { createHubMux } from './hub-mux.js';
7
- import { decodeRecoveryReply, decodeRecoveryRequest, encodeRecoveryReply, encodeRecoveryRequest } from './recovery.js';
8
- import { handshakeTopic, inboxTopic, protocolTopic } from './topic.js';
12
+ import { createLedgerEntryResolver, encodeLedgerEntries } from './ledger-entries.js';
13
+ import { decodeLedgerReply, decodeLedgerRequest, decodeRecoveryReply, decodeRecoveryRequest, encodeLedgerReply, encodeLedgerRequest, encodeRecoveryReply, encodeRecoveryRequest } from './recovery.js';
14
+ import { commitTopic, inboxTopic, protocolTopic, rendezvousTopic } from './topic.js';
9
15
  const DEFAULT_RECOVERY_TIMEOUT_MS = 5000;
10
16
  const DEFAULT_RECOVERY_JITTER_MS = 250;
17
+ /**
18
+ * How long `recover()` keeps rejoining before giving up and leaving the peer degraded. A
19
+ * deadline, like `commit()`'s, not an attempt count: losing the compare-and-set is the LIKELY
20
+ * case, since a heal runs under commit pressure and two peers healing at once race each other.
21
+ */ const DEFAULT_RECOVERY_DEADLINE_MS = 30_000;
22
+ /**
23
+ * How long the hub is asked to keep the commit log. Bounds how long a member may be offline and
24
+ * still converge by pulling alone, without another member awake to heal it.
25
+ */ const DEFAULT_COMMIT_LOG_RETENTION_SECONDS = 30 * 24 * 60 * 60;
26
+ /** How many commit frames a single pull asks for. Pull loops until the log is drained. */ const COMMIT_FETCH_LIMIT = 100;
27
+ /**
28
+ * How long `commit` keeps rebasing before giving up. A deadline, not an attempt count: several
29
+ * consecutive lost compare-and-sets on a busy group is ordinary contention.
30
+ */ const DEFAULT_COMMIT_DEADLINE_MS = 30_000;
31
+ /**
32
+ * Runaway guard only. The deadline is the real bound; this stops a hub that accepts nothing and
33
+ * never advances its head from spinning the loop forever inside a clock tick.
34
+ */ const COMMIT_ATTEMPT_CEILING = 1000;
35
+ /**
36
+ * Cap on the storm-collapse suppression set. The requestID comes off the wire, so without a bound
37
+ * a hostile relay could replay replies under endless distinct ids and grow the set forever.
38
+ *
39
+ * Eviction is safe at any size: a dropped entry only COSTS a redundant reply, never leaks. A
40
+ * suppression only stops THIS peer scheduling its own reply to a re-delivered request; a reply
41
+ * scheduled after eviction just re-seals current GroupInfo to a requester the port still
42
+ * authorizes against the live roster — a wasted publish a removed requester gets nothing from.
43
+ * The cap sits well above the in-flight request count, so eviction only reaches ids whose
44
+ * requester deadline long passed and which no honest peer asks about again (every attempt mints a
45
+ * fresh id).
46
+ */ const SUPPRESSED_REQUESTS_MAX = 1024;
11
47
  export function createGroupPeer(params) {
12
- const { hub, crypto, mls, localDID, protocols, handlers, suppress } = params;
48
+ const { hub, crypto, mls, journal, adoptJournalled, localDID, protocols, handlers, suppress } = params;
13
49
  const getRandomID = params.getRandomID;
50
+ const newPublishID = getRandomID ?? defaultRandomID;
14
51
  const recoveryTimeoutMs = params.recovery?.timeoutMs ?? DEFAULT_RECOVERY_TIMEOUT_MS;
52
+ const recoveryDeadlineMs = params.recovery?.deadlineMs ?? DEFAULT_RECOVERY_DEADLINE_MS;
15
53
  const getReplyDelayMs = params.recovery?.getDelayMs ?? (()=>defaultJitter(DEFAULT_RECOVERY_JITTER_MS));
54
+ const commitLogRetentionSeconds = params.commitLogRetentionSeconds ?? DEFAULT_COMMIT_LOG_RETENTION_SECONDS;
55
+ const commitDeadlineMs = params.commitDeadlineMs ?? DEFAULT_COMMIT_DEADLINE_MS;
16
56
  const mux = createHubMux({
17
57
  hub,
18
58
  localDID
19
59
  });
20
60
  let runtimes = new Map();
21
61
  let secret = new Uint8Array();
22
- let epoch = 0;
62
+ /**
63
+ * The epoch the app lane is built at, seeded from the handle, not zero. Zero is not neutral:
64
+ * `frameCommit` refuses to seal bodies when the live handle has moved past this, and the first
65
+ * lane operation (the seed: replay then pull) runs BEFORE the app lane is built — so a peer that
66
+ * restarted holding a journalled commit would have its own replay refused at startup by a guard
67
+ * about a host adopting early, and recover only if the host called a lane operation later.
68
+ */ let epoch = crypto.epoch();
23
69
  const buildEpoch = async ()=>{
24
70
  secret = await crypto.exportSecret();
25
71
  epoch = crypto.epoch();
26
72
  const next = new Map();
27
73
  for (const [name, protocol] of Object.entries(protocols)){
28
74
  const topicID = protocolTopic(secret, epoch, name);
75
+ // Subscribed for the member's whole life, like the commit and rendezvous topics: a
76
+ // rotation tears down the LISTENERS on an epoch it left, never the subscriptions (the mux
77
+ // guarantees it — nothing there unsubscribes). Unsubscribing tells the hub to drop this
78
+ // member's pending deliveries and free any frame it was the last reader of, so a peer that
79
+ // gave up the subscription as it rotated would delete its own unread messages, and
80
+ // everyone else's copy of them.
81
+ const selfInbox = inboxTopic(secret, epoch, localDID);
29
82
  const client = new BroadcastClient({
30
83
  transport: createBroadcastTransport({
31
84
  topicID,
@@ -52,10 +105,12 @@ export function createGroupPeer(params) {
52
105
  const acceptor = createInboxAcceptor({
53
106
  mux,
54
107
  localDID,
55
- selfInboxTopic: inboxTopic(secret, epoch, localDID),
108
+ selfInboxTopic: selfInbox,
56
109
  resolveSendTopic: (senderDID)=>inboxTopic(secret, epoch, senderDID),
57
110
  protocol: protocol,
58
- handlers: handlers[name]
111
+ handlers: handlers[name],
112
+ wrap: crypto.wrap,
113
+ unwrap: crypto.unwrap
59
114
  });
60
115
  next.set(name, {
61
116
  client,
@@ -67,9 +122,8 @@ export function createGroupPeer(params) {
67
122
  runtimes = next;
68
123
  };
69
124
  const teardownEpoch = async ()=>{
70
- // Disposal order is independent across runtimes and within a runtime, so tear
71
- // everything down concurrently and surface every failure rather than dying
72
- // on the first.
125
+ // Disposal order is independent, so tear everything down concurrently and surface every
126
+ // failure rather than dying on the first.
73
127
  const disposals = [];
74
128
  for (const runtime of runtimes.values()){
75
129
  for (const directed of runtime.directed.values())disposals.push(directed.dispose());
@@ -103,6 +157,8 @@ export function createGroupPeer(params) {
103
157
  memberDID,
104
158
  secret,
105
159
  epoch,
160
+ wrap: crypto.wrap,
161
+ unwrap: crypto.unwrap,
106
162
  ...getRandomID != null ? {
107
163
  getRandomID
108
164
  } : {}
@@ -116,30 +172,156 @@ export function createGroupPeer(params) {
116
172
  await teardownEpoch();
117
173
  await buildEpoch();
118
174
  };
119
- let handshakeUnsubscribe;
120
- let handshakeTopicID;
121
- let handshakeTail = Promise.resolve();
175
+ let commitUnsubscribe;
176
+ let rendezvousUnsubscribe;
177
+ let commitTopicID;
178
+ let rendezvousTopicID;
179
+ /**
180
+ * The last commit-log position this peer PROCESSED — applied, or dropped as stale, foreign or
181
+ * malformed. Not a delivery position: read only out of a `fetchTopic` result or a log publish
182
+ * (see `cursor.ts`). `null` means nothing processed — read the log from its oldest retained frame.
183
+ */ let reconciledHead = null;
184
+ /**
185
+ * The commit log's TIP as the last complete drain reported it — the anchor every commit
186
+ * compare-and-sets against.
187
+ *
188
+ * NOT the cursor; conflating them is a defect. The cursor is what this peer PROCESSED; the head
189
+ * is what the log's last accepted frame IS. They coincide only while every frame is log-class, a
190
+ * property of the store not this peer — so read the head from the store's own reply, never infer
191
+ * it from a cursor that happens to agree. `null` means the topic never had an accepted log
192
+ * publish, which is what the first commit of a group's life compares against.
193
+ */ let commitLogHead = null;
194
+ /**
195
+ * The sequenceID this peer ENACTED at each epoch it passed — applied from the log, or committed
196
+ * and adopted. The whole of the fork check: a second, different commit at an epoch this peer
197
+ * holds a record for is two commits at one epoch, which the hub can only produce by showing
198
+ * different logs to different members.
199
+ *
200
+ * An epoch with NO record is history, not a fork — a late joiner, rejoiner and re-seeded peer
201
+ * all walk commits from epochs they never held, and a trigger on "an epoch I passed" would send
202
+ * every one into recovery on its first pull.
203
+ *
204
+ * In memory, deliberately: a restart drops the record, and a peer with no record reads history
205
+ * as history. It can MISS a fork, never invent one, and a miss costs nothing the trim and heal
206
+ * triggers do not already cover.
207
+ */ const appliedByEpoch = new Map();
208
+ /**
209
+ * The heal trigger, RECORDED and never awaited where found. `recover()` is a lane operation and
210
+ * takes the commit mutex, so a pull that awaited it would wait on a tail including the pull. The
211
+ * trigger only writes this flag; the pull unwinds, releases the lane, and the heal runs
212
+ * afterward as its own operation. `healing` stops a second wakeup starting a concurrent one.
213
+ */ let healRequested = false;
214
+ let healing = false;
215
+ /**
216
+ * Positive evidence this peer is off the group's line, and the sole guard on `commit()`. Set
217
+ * when a pull sees proof the peer cannot reconcile: a frame framed AHEAD of its epoch, its OWN
218
+ * un-merged commit at its current epoch, or the LOSING side of a fork.
219
+ *
220
+ * Deliberately NOT `healRequested`: that flag only SCHEDULES the next heal and clears as
221
+ * ordinary control flow (`recover()` clears it at the top of every attempt), so a heal that
222
+ * finds no responder or spends its deadline leaves it false. Gating `commit()` on it would let a
223
+ * peer that just failed to heal win the compare-and-set at a stale epoch and land a commit — a
224
+ * Welcome among them — on a branch of one. This flag survives a failed heal: cleared ONLY when a
225
+ * rejoin actually lands (`recover`), the one thing that rebuilds this peer's place in the tree.
226
+ * No pull can carry a stranded peer back — the frames that would are gone, and the head sits at
227
+ * an epoch it can no longer reach by applying the log.
228
+ *
229
+ * Set on positive evidence, NEVER on poison: a frame this peer stepped over (malformed, refused
230
+ * by policy, or naming unresolvable bodies) is not evidence the group moved on, because nobody
231
+ * applied it either. Gating on poison would rebuild the group-death hazard the classifier's
232
+ * `poison` row refuses: every honest member would refuse to commit at an epoch a body-less frame
233
+ * poisoned, and no one could publish the commit that unsticks the group.
234
+ */ let stranded = false;
235
+ /**
236
+ * A commit this peer journalled, that never landed and it cannot re-issue itself: held until a
237
+ * lane operation with a return value can hand it to the host. A delivery wakeup is a lane
238
+ * operation too but has nowhere to put a loss, and dropping it is the one thing that must not
239
+ * happen — for an invite it loses an invitation, for a remove it leaves an admin believing a
240
+ * member was evicted when they were not.
241
+ */ let lostCommit;
242
+ /**
243
+ * The ledger entries this peer held when it rejoined — snapshotted BEFORE the rejoined handle
244
+ * replaces them, because a handle that rejoined by external commit holds an EMPTY ledger with
245
+ * nothing left to read.
246
+ *
247
+ * The peer's own LEDGER, deliberately not its journal. The journal is always settled by the
248
+ * time a heal runs (step 0 of every lane operation settles it before anything can trigger one),
249
+ * so filtering it would filter nothing. What a healing peer holds that the group may not is its
250
+ * ledger: entries it enacted on a branch the group discarded, or enacted and kept while the
251
+ * group moved on. Filtering THAT against the group's authenticated ledger is the membership rule
252
+ * as one set-difference: re-enact iff the group's ledger does not already contain it.
253
+ *
254
+ * `null` means no rejoin in progress. Survives a rejoin whose bootstrap failed, so the retry
255
+ * filters the same entries rather than snapshotting an empty ledger and dropping every one.
256
+ */ let inFlightEntries = null;
257
+ /**
258
+ * Entries a heal decided must be re-enacted, waiting for a lane operation with a return value —
259
+ * same problem and answer as `lostCommit`. A heal triggered by a pull is not a host call and has
260
+ * nowhere to put them; the host re-enacts with an ordinary `commit()` (a lane operation), so
261
+ * they can never be handed over from inside one.
262
+ */ let pendingReenact = [];
263
+ /**
264
+ * The group's commit mutex: every commit-lane operation serialized through one tail. The
265
+ * compare-and-set resolves races between devices, not two callers here — two `build()` calls
266
+ * against a single handle would both frame at that handle's epoch and diverge.
267
+ *
268
+ * NOT reentrant: a task that calls `runSerial` again waits on a tail including itself. That is
269
+ * why a loss is RETURNED to the host, never handed to it under the lock — the host's answer to a
270
+ * loss is to commit, and a commit takes this mutex.
271
+ */ let commitTail = Promise.resolve();
272
+ const runSerial = (fn)=>{
273
+ const op = commitTail.then(()=>{
274
+ journalReplayed = false;
275
+ return fn();
276
+ });
277
+ commitTail = op.then(()=>{}, ()=>{});
278
+ return op;
279
+ };
280
+ /**
281
+ * Whether the journal has been replayed in the lane operation now running. Cleared when an
282
+ * operation takes the mutex, set by `replayJournal`, required by `pullCommits`.
283
+ *
284
+ * The ordering it enforces saves a group of one. A peer that pulls before it replays meets its
285
+ * OWN un-merged commit in the log, whose classification is to heal — from a group that, at
286
+ * creation, has nobody to answer. Nothing else catches it: the heal resolves without advancing
287
+ * or throwing, the following replay adopts the commit anyway, and the peer converges — having
288
+ * spent a rendezvous and a recovery deadline asking the void for help, silently, every restart.
289
+ */ let journalReplayed = false;
122
290
  // Recovery rendezvous state, keyed by requestID.
123
291
  const recoveryWaiters = new Map();
124
292
  const recoveryTimers = new Map();
125
293
  const pendingReplies = new Map();
126
294
  const suppressedRequests = new Set();
127
- // Responder: after a jitter delay, answer a recovery request with current
128
- // GroupInfo — unless another responder's reply has already been observed
129
- // (storm-collapse), in which case the scheduled reply is cancelled.
130
- const handleRecoveryRequest = (requestID)=>{
131
- if (mls == null || handshakeTopicID == null) return;
295
+ /**
296
+ * Ledger-gather waiters, keyed by requestID. Called for EVERY reply, not just the first: a
297
+ * responder whose ledger fails the head check withheld an entry, so the requester falls through
298
+ * to the next reply rather than giving up.
299
+ */ const ledgerWaiters = new Map();
300
+ const pendingLedgerReplies = new Set();
301
+ // Responder: after a jitter delay, answer a recovery request with GroupInfo sealed to the
302
+ // ephemeral key inside the signed request — unless another responder's reply has already
303
+ // been observed (storm-collapse), in which case the scheduled reply is cancelled.
304
+ const handleRecoveryRequest = (request)=>{
305
+ const { requestID } = request;
306
+ if (mls == null || rendezvousTopicID == null) return;
132
307
  if (suppressedRequests.has(requestID) || pendingReplies.has(requestID)) return;
133
308
  const port = mls;
134
- const topicID = handshakeTopicID;
309
+ const topicID = rendezvousTopicID;
135
310
  const timer = setTimeout(()=>{
136
311
  pendingReplies.delete(requestID);
137
312
  void (async ()=>{
138
313
  try {
139
- const groupInfo = await port.exportGroupInfo();
140
- await mux.bus.publish(topicID, encodeHandshakeFrame(HANDSHAKE_KIND.recoveryReply, encodeRecoveryReply(requestID, groupInfo)));
314
+ // The port verifies the request and checks the requester's leaf against its own current
315
+ // tree. A refused request raises, and this peer stays silent.
316
+ const groupInfo = await port.sealGroupInfo(request.request);
317
+ // Mailbox class, deliberately: a rendezvous frame must never move the commit topic's
318
+ // head, and its reader — the requester — subscribed before it asked.
319
+ await mux.publish({
320
+ topicID,
321
+ payload: encodeHandshakeFrame(HANDSHAKE_KIND.recoveryReply, encodeRecoveryReply(requestID, groupInfo))
322
+ });
141
323
  } catch {
142
- // a failed reply just means another responder (or a retry) covers it
324
+ // a refused or failed reply just means another responder (or a retry) covers it
143
325
  }
144
326
  })();
145
327
  }, getReplyDelayMs());
@@ -149,6 +331,13 @@ export function createGroupPeer(params) {
149
331
  // suppresses this peer's own pending reply for the same request.
150
332
  const handleRecoveryReply = (reply)=>{
151
333
  suppressedRequests.add(reply.requestID);
334
+ // Bound the wire-fed set: evict oldest-first over the cap. A Set iterates in insertion order,
335
+ // so the front is the least-recently-added id — the one furthest past its deadline.
336
+ while(suppressedRequests.size > SUPPRESSED_REQUESTS_MAX){
337
+ const oldest = suppressedRequests.values().next().value;
338
+ if (oldest === undefined) break;
339
+ suppressedRequests.delete(oldest);
340
+ }
152
341
  const replyTimer = pendingReplies.get(reply.requestID);
153
342
  if (replyTimer != null) {
154
343
  clearTimeout(replyTimer);
@@ -165,107 +354,812 @@ export function createGroupPeer(params) {
165
354
  waiter(reply.groupInfo);
166
355
  }
167
356
  };
168
- // Serialize inbound handshake processing: Commits must apply in MLS order, and
169
- // both processCommit and the epoch rebuild are async. Each op waits for init to
170
- // finish, then runs to completion before the next begins.
171
- const onHandshakeMessage = (message, ack)=>{
172
- handshakeTail = handshakeTail.then(async ()=>{
173
- await ready;
174
- if (mls == null) {
175
- ack();
176
- return;
177
- }
178
- let frame;
179
- try {
180
- frame = decodeHandshakeFrame(message.payload);
181
- } catch {
182
- ack(); // drop malformed frames; acking stops poison redelivery
183
- return;
357
+ /**
358
+ * Responder: serve this member's WHOLE ordered ledger to a rejoined peer that holds none —
359
+ * SEALED to the ephemeral key inside the request's signed blob, and only to a requester the
360
+ * responder's own ratchet tree still holds a leaf for.
361
+ *
362
+ * Both halves are the port's and neither is this lane's to skip: the ledger is the group's whole
363
+ * authority state on a public secretless topic, so a plaintext reply hands every role to the
364
+ * hub and an unauthorized one hands them to any stranger who posts a request. The port refuses a
365
+ * DID with no leaf, and this peer stays silent — a refusal is not an answer.
366
+ *
367
+ * Gated on completeness: a peer that itself rejoined and has not bootstrapped holds an EMPTY
368
+ * ledger, and answering with it wastes a scarce responder (the requester's head check rejects
369
+ * it — a wasted round trip, not a soundness hole).
370
+ *
371
+ * Every responder that CAN answer does — no storm-collapse here, on purpose: a lying responder's
372
+ * answer fails the head check, and the requester needs a second answer to fall through to.
373
+ */ const handleLedgerRequest = (request)=>{
374
+ if (mls == null || rendezvousTopicID == null) return;
375
+ const port = mls;
376
+ const topicID = rendezvousTopicID;
377
+ const timer = setTimeout(()=>{
378
+ pendingLedgerReplies.delete(timer);
379
+ void (async ()=>{
380
+ try {
381
+ if (!await port.isLedgerComplete()) return;
382
+ // The port verifies the request and checks the requester's leaf against its own current
383
+ // tree. A refused request raises, and this peer stays silent.
384
+ const sealed = await port.sealLedger(request.request);
385
+ await mux.publish({
386
+ topicID,
387
+ payload: encodeHandshakeFrame(HANDSHAKE_KIND.ledgerReply, encodeLedgerReply(request.requestID, sealed))
388
+ });
389
+ } catch {
390
+ // a refused or failed reply just means another responder (or a retry) covers it
391
+ }
392
+ })();
393
+ }, getReplyDelayMs());
394
+ pendingLedgerReplies.add(timer);
395
+ };
396
+ const handleLedgerReply = (reply)=>{
397
+ ledgerWaiters.get(reply.requestID)?.(reply.sealed);
398
+ };
399
+ /**
400
+ * Read the commit log forward from the cursor, classify every frame, advance the cursor over
401
+ * each one it is done with. Returns whether any advanced the epoch.
402
+ *
403
+ * The ONLY place commit frames are read and the cursor table applied. Each frame is classified
404
+ * against this peer's state BEFORE anything is applied or decrypted (see
405
+ * {@link "classify".classifyCommit}): the classification says whether the cursor advances, the
406
+ * port is asked, and the peer must heal.
407
+ *
408
+ * The cursor advances over a frame the peer is DONE with — applied, walked as history, or
409
+ * stepped over as poison (a commit whose ledger entries will not resolve is poison: advance,
410
+ * never retry). It does NOT advance over its own un-merged commit, which stops the drain. A
411
+ * throw (port broke its contract on a frame it should have applied) leaves the cursor put and
412
+ * the next pull re-reads that frame.
413
+ *
414
+ * Also the only place the log's tip is learned, taken from the store's OWN reply, never inferred
415
+ * from the cursor. Recorded ONLY on a complete drain: a tip ahead of the frames it covers would
416
+ * name a commit this peer has not reconciled to, and the next `commit()` would win a
417
+ * compare-and-set at an epoch it had not caught up to. Only `own-unmerged` stops the pull early
418
+ * and takes no tip; the `ahead` path steps OVER its frame and drains to the end, so it DOES
419
+ * record the tip (the head is genuinely beyond this peer) — and the `stranded` flag, not a
420
+ * withheld tip, then stops the next `commit()` racing at it.
421
+ */ const pullCommits = async ()=>{
422
+ if (!journalReplayed) {
423
+ throw new Error('pullCommits: the journal must be replayed first in every lane operation, or a peer that crashed on its own commit heals from it instead of adopting it');
424
+ }
425
+ if (mls == null || commitTopicID == null) return false;
426
+ const port = mls;
427
+ const topicID = commitTopicID;
428
+ let advancedEpoch = false;
429
+ // The tip from the SAME reply whose frames were processed, so it can never run ahead of them.
430
+ const takeHead = (head)=>{
431
+ commitLogHead = head == null ? null : asLogPosition(head);
432
+ };
433
+ while(true){
434
+ const result = await mux.fetchTopic({
435
+ topicID,
436
+ // From the cursor. With no cursor (fresh member from a Welcome, trimmed backlog, just
437
+ // rejoined) read from the OLDEST retained frame. Seeding from the topic's `head` would
438
+ // be a guess: it names commits this peer never applied, wrong in exactly the case this
439
+ // lane exists for.
440
+ ...reconciledHead != null ? {
441
+ after: reconciledHead
442
+ } : {},
443
+ limit: COMMIT_FETCH_LIMIT
444
+ });
445
+ if (result.messages.length === 0) {
446
+ // Drained. The tip an EMPTY page reports is not redundant: a topic keeps its head when
447
+ // its frames age out, so a fully swept log still has a tip — and a peer that anchored on
448
+ // its own cursor here would compare-and-set against `null` on a topic whose head is a real
449
+ // sequenceID, and lose forever.
450
+ takeHead(result.head);
451
+ return advancedEpoch;
184
452
  }
185
- if (frame.kind === HANDSHAKE_KIND.commit) {
186
- const { advanced } = await mls.processCommit(frame.payload, {
187
- senderDID: message.senderDID
453
+ for (const message of result.messages){
454
+ // A commit this peer landed moved its cursor to that frame's position on acceptance, so an
455
+ // ordinary pull starts after it (the journal carries that across a restart). A peer that
456
+ // meets its own commit here is one whose journal was lost or never written.
457
+ const position = asLogPosition(message.sequenceID);
458
+ let frame;
459
+ try {
460
+ frame = decodeHandshakeFrame(message.payload);
461
+ } catch {
462
+ reconciledHead = position; // malformed: dropped, and the cursor still steps over it
463
+ continue;
464
+ }
465
+ if (frame.kind !== HANDSHAKE_KIND.commit) {
466
+ reconciledHead = position; // the commit lane carries commits, and nothing else
467
+ continue;
468
+ }
469
+ // Split the frame into the commit and the sealed blob of bodies it enacts. Reads bytes,
470
+ // decrypts NOTHING: a peer walking the log reaches frames sealed under epochs it does not
471
+ // hold (a late joiner reaches the commit that added it), and a blob it cannot open is
472
+ // history, not poison. Opening it follows from "I can apply this commit", never precedes
473
+ // reading it.
474
+ let commitFrame;
475
+ try {
476
+ commitFrame = decodeCommitFrame(frame.payload);
477
+ } catch {
478
+ reconciledHead = position; // malformed: dropped, and the cursor still steps over it
479
+ continue;
480
+ }
481
+ // The commit's OWN epoch and committer, from the commit's own bytes. Never
482
+ // `message.senderDID` — the hub-authenticated publisher, the hub's word about who handed
483
+ // it over, and the hub is not trusted: a hub that could name the committer could stamp
484
+ // every recipient's own DID onto one poison frame and make the whole group heal at once.
485
+ const disposition = classifyCommit(port.readCommitHeader(commitFrame.commit), position, {
486
+ localDID,
487
+ epoch: crypto.epoch(),
488
+ appliedByEpoch
188
489
  });
189
- if (advanced) await rebuildEpoch();
190
- ack(); // durably handled
191
- return;
490
+ if (disposition.row === 'own-unmerged') {
491
+ // This peer's own commit, at the epoch it is still at: the hub took it, the group moved
492
+ // on it, and the pending state died with its process. It can never be applied — MLS
493
+ // merges a pending commit, does not process one — so the cursor stays put, the drain
494
+ // stops, no tip is taken, and the peer heals. The trigger only RECORDS; `recover()`
495
+ // takes the commit mutex this pull already holds.
496
+ healRequested = true;
497
+ stranded = true;
498
+ return advancedEpoch;
499
+ }
500
+ if (disposition.row === 'ahead') {
501
+ // The group advanced at an epoch this peer did not. Step over the frame — the heal
502
+ // repairs this, not a re-read — and ask for one.
503
+ reconciledHead = position;
504
+ healRequested = true;
505
+ stranded = true;
506
+ continue;
507
+ }
508
+ if (disposition.row === 'history') {
509
+ // A frame from an epoch below this peer's that it holds no record for. Not a fork, not
510
+ // poison, not the port's business: never handed over, its blob never touched.
511
+ reconciledHead = position;
512
+ continue;
513
+ }
514
+ if (disposition.row === 'fork') {
515
+ // Two commits at one epoch. The lower-sequenceID branch wins; the loser rejoins onto it
516
+ // (a heal). The winner just steps over the frame.
517
+ reconciledHead = position;
518
+ if (disposition.branch === 'losing') {
519
+ healRequested = true;
520
+ stranded = true;
521
+ }
522
+ continue;
523
+ }
524
+ if (disposition.row === 'poison') {
525
+ reconciledHead = position; // not a commit at all: stepped over, and never retried
526
+ continue;
527
+ }
528
+ // Framed at this peer's epoch, by somebody else: a frame it can apply. Everything below is
529
+ // the port's answer to it.
530
+ const framedEpoch = crypto.epoch();
531
+ let applied;
532
+ try {
533
+ applied = await port.processCommit(commitFrame.commit, {
534
+ senderDID: message.senderDID,
535
+ // The resolver, not the bodies: the blob is opened only if the port asks for the
536
+ // entries this commit names, and it asks only for a commit it is applying — framed at
537
+ // this peer's epoch, which is the epoch the blob is sealed under. That makes body
538
+ // delivery atomic with the commit.
539
+ resolveLedgerEntries: createLedgerEntryResolver(commitFrame.sealedEntries, crypto.unwrap)
540
+ });
541
+ } catch (error) {
542
+ if (!isMissingLedgerEntries(error)) {
543
+ // The port broke its contract. The cursor stays and the frame is re-read — the pull is
544
+ // a retry, and this is not an outcome it can name.
545
+ throw error;
546
+ }
547
+ // The commit names ledger entries whose bodies will not resolve. POISON: drop, advance,
548
+ // do NOT heal. The bodies ride the commit sealed under its framed epoch, so a blob this
549
+ // peer cannot open is one no member at this epoch can — nobody applies it, the group
550
+ // never moves past that epoch, and the next honest commit is framed at the same epoch
551
+ // and compare-and-sets behind it. Whole cost: a wasted lane slot any writer can burn
552
+ // anyway.
553
+ //
554
+ // Healing here would hand any member a group-wide recovery storm for one publish (a
555
+ // commit naming entries whose bodies it leaves out of the frame). Retrying, bounded or
556
+ // not, only delays that. The one case where this peer really is the broken one
557
+ // (everyone else resolved it and moved on) announces itself later from a different
558
+ // frame: the next commit is then framed AHEAD of this peer's, and that heals it.
559
+ reconciledHead = position;
560
+ continue;
561
+ }
562
+ if (applied.advanced) {
563
+ advancedEpoch = true;
564
+ // The fork check's record; the only place it is written from the log.
565
+ appliedByEpoch.set(framedEpoch, position);
566
+ }
567
+ // `{ advanced: false }` here is the port REFUSING a well-formed commit at this peer's own
568
+ // epoch from another member: poison on the same terms as an unresolvable one — advances,
569
+ // never retried, does not heal.
570
+ reconciledHead = position;
192
571
  }
572
+ // A short page ends the log: every frame this reply named is processed, so its tip is one
573
+ // this peer has reconciled to. A full page is not — the tip may be beyond it — so loop and
574
+ // take the head from the reply that finally drains.
575
+ if (result.messages.length < COMMIT_FETCH_LIMIT) {
576
+ takeHead(result.head);
577
+ return advancedEpoch;
578
+ }
579
+ }
580
+ };
581
+ /** Pull the commit log, and rebuild the app lane if the pull moved the epoch. */ const reconcileCommits = async ()=>{
582
+ const advanced = await pullCommits();
583
+ if (advanced) await rebuildEpoch();
584
+ };
585
+ /**
586
+ * A commit-topic delivery is a WAKEUP, nothing more. Frames come from the pull, never the push:
587
+ * an accepted log publish is pushed AND retained, so processing the pushed copy too would apply
588
+ * every commit twice. The payload is not read; its sequenceID is a delivery position and can
589
+ * never become the cursor.
590
+ */ const onCommitDelivery = (_message, ack)=>{
591
+ ack();
592
+ void runSerial(async ()=>{
593
+ await ready;
594
+ // A wakeup is a lane operation: step 0, the ledger invariant, then the pull. No return
595
+ // value, so anything found is stashed for the next call that has one.
596
+ const replayed = await replayJournal();
597
+ await ensureLedger(Date.now() + recoveryTimeoutMs);
598
+ const pulled = await pullCommits();
599
+ if (replayed || pulled) await rebuildEpoch();
600
+ }).catch(()=>{
601
+ // pull failed (e.g. processCommit threw); the cursor did not advance, so the next wakeup
602
+ // re-reads those frames
603
+ })// Outside the mutex, once the pull released it: a heal is its own lane operation and takes
604
+ // that mutex itself.
605
+ .then(()=>healIfRequested());
606
+ };
607
+ const onRendezvousMessage = (message, ack)=>{
608
+ ack();
609
+ if (mls == null) return;
610
+ let frame;
611
+ try {
612
+ frame = decodeHandshakeFrame(message.payload);
613
+ } catch {
614
+ return; // malformed frames are dropped
615
+ }
616
+ try {
193
617
  if (frame.kind === HANDSHAKE_KIND.recoveryRequest) {
194
618
  handleRecoveryRequest(decodeRecoveryRequest(frame.payload));
195
- ack();
196
- return;
197
- }
198
- if (frame.kind === HANDSHAKE_KIND.recoveryReply) {
619
+ } else if (frame.kind === HANDSHAKE_KIND.recoveryReply) {
199
620
  handleRecoveryReply(decodeRecoveryReply(frame.payload));
200
- ack();
201
- return;
621
+ } else if (frame.kind === HANDSHAKE_KIND.ledgerRequest) {
622
+ handleLedgerRequest(decodeLedgerRequest(frame.payload));
623
+ } else if (frame.kind === HANDSHAKE_KIND.ledgerReply) {
624
+ handleLedgerReply(decodeLedgerReply(frame.payload));
202
625
  }
203
- ack();
204
- }).catch(()=>{
205
- // processing failed (e.g. processCommit threw) — do NOT ack, so the hub
206
- // redelivers and we retry.
207
- });
626
+ } catch {
627
+ // malformed payloads are dropped
628
+ }
208
629
  };
209
- const initHandshake = async ()=>{
630
+ const initControlLanes = async ()=>{
210
631
  if (mls == null) return;
211
632
  const recoverySecret = await mls.exportRecoverySecret();
212
- const topicID = handshakeTopic(recoverySecret);
213
- handshakeTopicID = topicID;
214
- // Subscribed once for the peer's whole life — deliberately NOT rebuilt on
215
- // resync, so a peer stranded on a stale epoch always shares this rendezvous
216
- // with the live group. Released only on dispose.
217
- handshakeUnsubscribe = mux.onInbound(topicID, onHandshakeMessage);
633
+ commitTopicID = commitTopic(recoverySecret);
634
+ rendezvousTopicID = rendezvousTopic(recoverySecret);
635
+ // Both topics subscribed once for the peer's whole life — NOT rebuilt on resync, so a peer
636
+ // stranded on a stale epoch still shares both rendezvous with the live group. Released only on
637
+ // dispose. Subscribe BEFORE the first pull: the hub gates a topic fetch on the caller's own
638
+ // subscription, and the subscription is also what asks it to hold the log.
639
+ commitUnsubscribe = mux.onInbound(commitTopicID, onCommitDelivery, {
640
+ retention: commitLogRetentionSeconds
641
+ });
642
+ rendezvousUnsubscribe = mux.onInbound(rendezvousTopicID, onRendezvousMessage);
643
+ // Then seed the cursor by READING the log — commits published before this peer subscribed are
644
+ // exactly the ones no push will bring it. The seed is a lane operation, so the journal replays
645
+ // AHEAD of it: a peer coming up after a crash settles its own pending commit before it reads a
646
+ // log that may contain it. Neither step rebuilds the epoch — buildEpoch runs next.
647
+ await runSerial(async ()=>{
648
+ await replayJournal();
649
+ // A peer restored with an incomplete ledger was killed between rejoining and bootstrapping:
650
+ // empty ledger against a live head, nothing remembering it was mid-heal. The invariant finds
651
+ // it, here and at every later lane operation, with no memory of how it got there.
652
+ await ensureLedger(Date.now() + recoveryTimeoutMs);
653
+ await pullCommits();
654
+ }).catch(()=>{
655
+ // a failed seed leaves the cursor put; the next wakeup replays and pulls again
656
+ });
218
657
  };
219
- // Fan out a locally-produced Commit and rebuild this peer's app topics. The
220
- // publish + rebuild ride the same serial tail as inbound processing so they
221
- // never interleave with a concurrently-received Commit.
222
- const localCommitted = async (commit)=>{
658
+ /**
659
+ * Frame a commit for the log: `[commit][wrap(bodies)]`, bodies sealed under the epoch secret the
660
+ * commit is FRAMED at — the epoch every member that can apply it is at, and the one this group
661
+ * stays at until the commit is adopted. A host that adopted first has rotated past it and can
662
+ * seal for nobody, so it is told rather than publishing a blob no member can open.
663
+ */ const frameCommit = async (commit, bodies)=>{
664
+ if (crypto.epoch() !== epoch) {
665
+ throw new Error('commit: the local group has already advanced past the epoch this commit was framed at. A commit is adopted in onAccepted, never before.');
666
+ }
667
+ const sealedEntries = await crypto.wrap(encodeLedgerEntries(bodies));
668
+ return encodeHandshakeFrame(HANDSHAKE_KIND.commit, encodeCommitFrame(commit, sealedEntries));
669
+ };
670
+ /**
671
+ * Step 0 of every lane operation, strictly ahead of the pull. Settle any journalled commit:
672
+ * adopt it if the slot records it landed, else republish under its ORIGINAL publishID and
673
+ * expectedHead and let the store's idempotency decide — no responder, no network, no rendezvous.
674
+ *
675
+ * Ahead of the pull, load-bearing: a peer that pulls first meets its own un-merged commit in the
676
+ * log and must reason about a frame it produced and never adopted — the expensive path the
677
+ * journal exists to avoid.
678
+ *
679
+ * Returns whether it moved the epoch. Any loss is stashed, not thrown or called back: the host's
680
+ * to act on, and its action is to commit.
681
+ */ const replayJournal = async ()=>{
682
+ journalReplayed = true;
683
+ if (mls == null || journal == null || commitTopicID == null) return false;
684
+ const entry = await journal.get();
685
+ if (entry == null) return false;
686
+ if (entry.acceptedAs != null) {
687
+ // It landed and this peer recorded that before adopting. Nothing to ask: no republish, no
688
+ // re-seal, no network. The recorded sequenceID is both the last position processed and the
689
+ // log's tip as of that frame — a stale tip is safe (a commit racing it just loses the
690
+ // compare-and-set and rebases), where a WRONG one would win a race it had no right to.
691
+ const accepted = asLogPosition(entry.acceptedAs);
692
+ reconciledHead = accepted;
693
+ commitLogHead = accepted;
694
+ appliedByEpoch.set(entry.epoch, accepted);
695
+ await adoptJournalled(entry.journal);
696
+ await journal.clear(entry.publishID);
697
+ return true;
698
+ }
699
+ // Republishing means RE-SEALING the bodies, sealable only under the host's current epoch. That
700
+ // equals the framed epoch only while onAccepted is the sole place the host adopts — and an
701
+ // entry with no recorded acceptance at any other epoch proves it is not. Sealing anyway
702
+ // publishes a blob no member can open and wedges the lane for the whole group, so the peer
703
+ // refuses and keeps the slot.
704
+ if (crypto.epoch() !== entry.epoch) {
705
+ throw new JournalEpochError(`commit replay: the journalled commit was framed at epoch ${entry.epoch}, and this group is now at ${crypto.epoch()}. A commit is adopted in onAccepted, and nowhere else.`);
706
+ }
707
+ const payload = await frameCommit(entry.commit, entry.bodies);
708
+ let sequenceID;
709
+ try {
710
+ sequenceID = (await mux.publish({
711
+ topicID: commitTopicID,
712
+ payload,
713
+ retain: 'log',
714
+ expectedHead: entry.expectedHead,
715
+ publishID: entry.publishID
716
+ })).sequenceID;
717
+ } catch (error) {
718
+ if (!isHeadMismatch(error)) {
719
+ // Outcome UNKNOWN — the hub may have accepted and failed to say so. Leave the slot
720
+ // exactly as it is: the next lane operation asks again.
721
+ throw error;
722
+ }
723
+ // It never landed and someone else's commit is at the head. There is no `build()` to call
724
+ // again — the process that held it is gone — so hand back what survived and clear the slot:
725
+ // the notice must not be lost, never the slot.
726
+ await journal.clear(entry.publishID);
727
+ lostCommit = entry.kind === 'ledger' ? {
728
+ kind: 'ledger',
729
+ tokens: entry.bodies
730
+ } : {
731
+ kind: entry.kind
732
+ };
733
+ return false;
734
+ }
735
+ // Accepted — just now, or by the process that published it and died; the store's dedup makes
736
+ // those indistinguishable, which is the point.
737
+ //
738
+ // Record acceptance BEFORE adopting, as `commit()` does: adopting moves the handle past the
739
+ // framed epoch, and a crash between the two would leave a journalled commit indistinguishable
740
+ // from a host that adopted out of band. Written first, replay is idempotent — the next one
741
+ // adopts from the slot and never republishes.
742
+ await journal.markAccepted(entry.publishID, sequenceID);
743
+ // This peer's own accepted frame is BOTH the last thing it processed and the log's tip — one
744
+ // position, two names, genuinely coinciding for this one frame; otherwise a `commit()` right
745
+ // after a `replay()` would anchor on a tip from before its own commit landed.
746
+ const accepted = asLogPosition(sequenceID);
747
+ reconciledHead = accepted;
748
+ commitLogHead = accepted;
749
+ appliedByEpoch.set(entry.epoch, accepted);
750
+ await adoptJournalled(entry.journal);
751
+ await journal.clear(entry.publishID);
752
+ return true;
753
+ };
754
+ /**
755
+ * Hand the host what a lane operation found and cannot act on itself — this operation's or an
756
+ * earlier wakeup's: work that survived a commit that did not, which only the host can re-issue.
757
+ */ const takeLost = ()=>{
758
+ const lost = lostCommit;
759
+ lostCommit = undefined;
760
+ const reenact = pendingReenact;
761
+ pendingReenact = [];
762
+ return {
763
+ ...lost != null ? {
764
+ lost
765
+ } : {},
766
+ ...reenact.length > 0 ? {
767
+ reenact
768
+ } : {}
769
+ };
770
+ };
771
+ /**
772
+ * The ledger completeness invariant, checked before every lane operation and repaired on the
773
+ * spot. Purely local (the head folded from the handle's entries against the authenticated head
774
+ * its own group state carries) and needs no memory of how the peer got here, which is what makes
775
+ * the state it detects self-healing.
776
+ *
777
+ * A handle that rejoined by external commit holds an EMPTY ledger against a live head, not a
778
+ * neutral start: the roster folds from the entries, so with none the creator is the only admin.
779
+ * Every admin promoted since is invisible and the peer REJECTS the next commit any of them
780
+ * authors — it re-strands itself. A crash between rejoin and bootstrap leaves exactly that on
781
+ * disk, and this finds it on the next lane operation.
782
+ *
783
+ * Returns whether the ledger is complete. Never throws: an incomplete ledger is a persistent,
784
+ * retryable, degraded state, not an error the host can act on.
785
+ */ const ensureLedger = async (deadline)=>{
786
+ if (mls == null || rendezvousTopicID == null) return true;
787
+ const port = mls;
788
+ const topicID = rendezvousTopicID;
789
+ if (await port.isLedgerComplete()) return true;
790
+ // Gather the WHOLE ordered ledger — not "the missing ids", which nothing enumerates: the
791
+ // authenticated head is a chain digest, not a list, and the rejoined handle has no entries to
792
+ // diff. Every responder with a complete ledger answers, each answer checked against the head
793
+ // this handle carries: a lying responder can withhold, never rewrite, and one that fails is
794
+ // dropped for the next reply.
795
+ //
796
+ // The request is the port's signed blob (same one a rejoin carries, same call). It names this
797
+ // peer inside a signature (what a responder authorizes against) and carries an ephemeral
798
+ // public key (the only key a responder seals to). Both matter: without the first any stranger
799
+ // gets the group's whole authority state for one publish; without the second, so does the hub.
800
+ const requestID = newPublishID();
801
+ const request = await port.createRecoveryRequest(requestID);
802
+ return await new Promise((resolve)=>{
803
+ let settled = false;
804
+ const finish = (complete)=>{
805
+ if (settled) return;
806
+ settled = true;
807
+ ledgerWaiters.delete(requestID);
808
+ clearTimeout(timer);
809
+ resolve(complete);
810
+ };
811
+ const timer = setTimeout(()=>finish(false), Math.max(0, deadline - Date.now()));
812
+ ledgerWaiters.set(requestID, (sealed)=>{
813
+ void (async ()=>{
814
+ if (settled) return;
815
+ try {
816
+ // Bytes this peer cannot open: another member's reply to another request, or a
817
+ // hub-injected forgery. Dropped, gather waits — the per-request key is NOT consumed
818
+ // here, since the next responder's reply is sealed to the same key.
819
+ const tokens = await port.openSealedLedger(sealed, requestID);
820
+ if (tokens == null) return;
821
+ await port.bootstrapLedger(tokens);
822
+ finish(true);
823
+ } catch {
824
+ // Recomputed head does not match the authenticated one: this responder withheld,
825
+ // reordered or truncated an entry. Nothing folded. Wait for the next reply.
826
+ }
827
+ })();
828
+ });
829
+ void mux.publish({
830
+ topicID,
831
+ payload: encodeHandshakeFrame(HANDSHAKE_KIND.ledgerRequest, encodeLedgerRequest(requestID, request))
832
+ }).catch(()=>{});
833
+ });
834
+ };
835
+ /**
836
+ * Commit to the group, rebasing until it lands or the deadline passes. Runs under the commit
837
+ * mutex for its whole life, so `build()` never races another `build()` on this device.
838
+ */ const commit = async (build)=>{
223
839
  await ready;
224
- if (mls == null || handshakeTopicID == null) return;
225
- const topicID = handshakeTopicID;
226
- const frame = encodeHandshakeFrame(HANDSHAKE_KIND.commit, commit);
227
- const op = handshakeTail.then(async ()=>{
228
- await mux.bus.publish(topicID, frame);
229
- await rebuildEpoch();
840
+ if (mls == null || journal == null || commitTopicID == null) {
841
+ throw new Error('commit: this peer has no MLS port, so it has no group to commit to');
842
+ }
843
+ const slot = journal;
844
+ const topicID = commitTopicID;
845
+ const op = runSerial(async ()=>{
846
+ // 0. Replay the journal, ahead of the pull.
847
+ if (await replayJournal()) await rebuildEpoch();
848
+ // 0.5. Refuse on an incomplete ledger. A rejoin whose bootstrap never finished leaves a
849
+ // reset roster: the fold sees only the genesis creator as admin, every promotion since
850
+ // is invisible, and a commit built now acts on authority it cannot verify.
851
+ // `ensureLedger` repairs it in place when a responder answers; when none does it stays
852
+ // incomplete, and the peer must publish and advance NOTHING.
853
+ //
854
+ // Same refusal the `stranded` gate below makes. It THROWS rather than returning because
855
+ // `commit()` returns only when the commit LANDED (onAccepted ran, epoch moved) — a peer
856
+ // that cannot commit says so by throwing, as for a strand or spent deadline. `recover()`
857
+ // answers `advanced: false` instead because its contract carries that flag; `commit()`'s
858
+ // does not. NO heal is scheduled: this peer holds its leaf, so an external-commit rejoin
859
+ // would rotate the tree for nothing — the gather that just failed for want of a
860
+ // responder IS the repair, re-running at the head of the next lane operation.
861
+ if (!await ensureLedger(Date.now() + recoveryTimeoutMs)) {
862
+ throw new RecoveryRequiredError('commit: the ledger is incomplete, so this handle rejoined the group and its bootstrap has not completed — its roster has reset, and a commit built now would be judged against a group whose admins it cannot see. It must finish bootstrapping its ledger before it can commit again.');
863
+ }
864
+ const deadline = Date.now() + commitDeadlineMs;
865
+ for(let attempt = 0; attempt < COMMIT_ATTEMPT_CEILING; attempt++){
866
+ // 1. Pull the log to the end: every frame processed, and the tip to race at learned from
867
+ // the store's own reply.
868
+ await reconcileCommits();
869
+ // The pull found positive evidence this peer is off the group's line (own un-merged
870
+ // commit, a frame framed ahead, or the losing side of a fork), and that stands whether or
871
+ // not the following heal lands. Unwind rather than race: on the `ahead` path the pull
872
+ // drained to the end and took the live tip, so a commit here would win the compare-and-set
873
+ // at an epoch it never caught up to. The lane releases, the heal runs as its own
874
+ // operation, the host's commit is later. Gating on `stranded` not `healRequested` is what
875
+ // makes this survive a heal that found no responder — a `commit()` right after must refuse.
876
+ if (stranded) {
877
+ throw new RecoveryRequiredError('commit: the log holds a frame this peer cannot reconcile with — its own un-merged commit, or a commit from an epoch ahead of it. It must recover before it can commit again.');
878
+ }
879
+ // 2. Build against the host's CURRENT handle, adopting nothing. `build` closes over that
880
+ // handle, so a rebased retry frames at the rebased epoch.
881
+ const pending = await build();
882
+ // 3. Journal BEFORE publishing, durably: from here to the hub's answer is the crash
883
+ // window, and the slot is the only thing that survives it.
884
+ //
885
+ // Anchor on the log's TIP, not the cursor. The cursor names the last frame PROCESSED,
886
+ // which need not be one the head can ever name — anchoring there stakes every commit on
887
+ // the two never diverging, a property of the store not this peer.
888
+ const publishID = newPublishID();
889
+ const expectedHead = commitLogHead;
890
+ const framedEpoch = crypto.epoch();
891
+ const payload = await frameCommit(pending.commit, pending.bodies);
892
+ await slot.put({
893
+ publishID,
894
+ expectedHead,
895
+ // The framed epoch, and the only one its bodies can be sealed under. A replay at any
896
+ // other epoch with no recorded acceptance knows the host adopted where it must not have.
897
+ epoch: framedEpoch,
898
+ commit: pending.commit,
899
+ bodies: pending.bodies,
900
+ kind: pending.kind,
901
+ journal: pending.journal
902
+ });
903
+ // 4. Publish, conditional on the head the pull reached.
904
+ let sequenceID;
905
+ try {
906
+ sequenceID = (await mux.publish({
907
+ topicID,
908
+ payload,
909
+ retain: 'log',
910
+ expectedHead,
911
+ publishID
912
+ })).sequenceID;
913
+ } catch (error) {
914
+ if (!isHeadMismatch(error)) {
915
+ // Unknown outcome: the frame may be in the log. The slot STAYS — the next lane
916
+ // operation replays it and asks the store which it was.
917
+ throw error;
918
+ }
919
+ // 6. Lost the compare-and-set: someone committed first — the expected path, not an
920
+ // error. Drop the pending commit untouched (costs nothing, pre-commit key material
921
+ // retained), clear the slot, and go back to step 1 against the winner.
922
+ await slot.clear(publishID);
923
+ if (Date.now() >= deadline) {
924
+ throw new CommitDeadlineError(`commit: still rebasing after ${commitDeadlineMs}ms and ${attempt + 1} attempts`);
925
+ }
926
+ continue;
927
+ }
928
+ // 5. Accepted. Record it in the slot BEFORE the host adopts, while the group is still at
929
+ // the framed epoch. That ordering makes a crash legible: an entry carrying its
930
+ // acceptance landed and can be adopted on restart; an entry carrying none, at an epoch
931
+ // past the framed one, is a host that adopted outside `onAccepted`. Recorded after the
932
+ // adopt, the two would be indistinguishable and the peer would have to re-seal a commit
933
+ // it can seal for no one.
934
+ await slot.markAccepted(publishID, sequenceID);
935
+ // The commit is the group's now — this frame is both the last position processed and the
936
+ // log's new tip.
937
+ const accepted = asLogPosition(sequenceID);
938
+ reconciledHead = accepted;
939
+ commitLogHead = accepted;
940
+ // A commit this peer made and adopted was enacted at that epoch, like an applied one, so
941
+ // it joins the fork record on the same terms. Without it a second commit at an epoch this
942
+ // peer OWNS would read as history.
943
+ appliedByEpoch.set(framedEpoch, accepted);
944
+ await pending.onAccepted();
945
+ await slot.clear(publishID);
946
+ await rebuildEpoch();
947
+ return takeLost();
948
+ }
949
+ throw new CommitDeadlineError(`commit: gave up after ${COMMIT_ATTEMPT_CEILING} attempts inside its deadline`);
230
950
  });
231
- handshakeTail = op.catch(()=>{});
232
- await op;
951
+ // A heal the pull asked for runs once this operation released the lane, never inside it: the
952
+ // host is told its commit did not land, and the peer repairs itself.
953
+ void op.catch(()=>{}).then(()=>healIfRequested());
954
+ return op;
233
955
  };
234
- const recover = async ()=>{
956
+ const replay = async ()=>{
235
957
  await ready;
236
- if (mls == null || handshakeTopicID == null) return {
237
- advanced: false
238
- };
239
- const port = mls;
240
- const topicID = handshakeTopicID;
241
- const requestID = (getRandomID ?? defaultRandomID)();
242
- const groupInfo = await new Promise((resolve)=>{
958
+ return runSerial(async ()=>{
959
+ if (await replayJournal()) await rebuildEpoch();
960
+ await ensureLedger(Date.now() + recoveryTimeoutMs);
961
+ return takeLost();
962
+ });
963
+ };
964
+ /**
965
+ * Ask the group for its state and wait for one member to answer, bounded by the deadline.
966
+ * `null` when nobody does — heal is a rendezvous and cannot work without a responder.
967
+ */ const requestGroupInfo = async (request, requestID, topicID, deadline)=>{
968
+ const wait = Math.max(0, Math.min(recoveryTimeoutMs, deadline - Date.now()));
969
+ return await new Promise((resolve)=>{
243
970
  recoveryWaiters.set(requestID, resolve);
244
971
  recoveryTimers.set(requestID, setTimeout(()=>{
245
972
  recoveryTimers.delete(requestID);
246
973
  if (recoveryWaiters.delete(requestID)) resolve(null);
247
- }, recoveryTimeoutMs));
248
- void Promise.resolve(mux.bus.publish(topicID, encodeHandshakeFrame(HANDSHAKE_KIND.recoveryRequest, encodeRecoveryRequest(requestID)))).catch(()=>{});
974
+ }, wait));
975
+ void Promise.resolve(mux.publish({
976
+ topicID,
977
+ payload: encodeHandshakeFrame(HANDSHAKE_KIND.recoveryRequest, encodeRecoveryRequest(requestID, request))
978
+ })).catch(()=>{});
249
979
  });
250
- if (groupInfo == null) return {
251
- advanced: false
252
- };
253
- let result = {
254
- advanced: false
255
- };
256
- const op = handshakeTail.then(async ()=>{
257
- const r = await port.applyRecovery(groupInfo);
258
- if (r.advanced) await rebuildEpoch();
259
- result = r;
980
+ };
981
+ /**
982
+ * The commit log's TIP from the store's own reply — the head an external commit races at.
983
+ *
984
+ * Deliberately NOT the cursor, and the one place the two must come apart: a healing peer cannot
985
+ * process the frames at the head, so its cursor is stuck behind them forever, and a rejoin
986
+ * anchored there would lose the compare-and-set forever. The external commit rebuilds this
987
+ * peer's place from a GroupInfo that already describes the head, so racing there is right.
988
+ */ const readCommitHead = async (topicID)=>{
989
+ const result = await mux.fetchTopic({
990
+ topicID,
991
+ ...reconciledHead != null ? {
992
+ after: reconciledHead
993
+ } : {},
994
+ limit: 1
995
+ });
996
+ return result.head == null ? null : asLogPosition(result.head);
997
+ };
998
+ /**
999
+ * Heal by external-commit rejoin: a top-level lane operation with a compare-and-set loop of its
1000
+ * own. NEVER calls `commit()` and `commit()` never calls it — both take the same non-reentrant
1001
+ * mutex, so either nesting deadlocks. The re-enactment a heal owes is a SUBSEQUENT `commit()` the
1002
+ * host makes once this releases the lane.
1003
+ */ const recover = async ()=>{
1004
+ await ready;
1005
+ if (mls == null || commitTopicID == null || rendezvousTopicID == null) {
1006
+ return {
1007
+ advanced: false,
1008
+ reenact: []
1009
+ };
1010
+ }
1011
+ const port = mls;
1012
+ const commits = commitTopicID;
1013
+ const rendezvous = rendezvousTopicID;
1014
+ return runSerial(async ()=>{
1015
+ // 0. Replay the journal ahead of everything, as every lane operation does: a peer holding a
1016
+ // commit whose fate it never learned settles that first, and may find nothing left to heal.
1017
+ if (await replayJournal()) await rebuildEpoch();
1018
+ const deadline = Date.now() + recoveryDeadlineMs;
1019
+ while(Date.now() < deadline){
1020
+ // 1. Pull to the end. It may resolve the strand outright (the missing frames may just be
1021
+ // there), and a heal it no longer needs must NOT run: the external commit would rotate
1022
+ // the tree for the whole group. Rebuild if it moved the epoch, before anything is
1023
+ // framed: the peer that lost a heal race applies the winner's commit HERE, and a frame
1024
+ // sealed against an app lane that had not caught up would seal under an epoch the group
1025
+ // left.
1026
+ healRequested = false;
1027
+ await reconcileCommits();
1028
+ // 2. The head to race at, from the store's own reply.
1029
+ const expectedHead = await readCommitHead(commits);
1030
+ // 3. Mint a request and rendezvous for a sealed GroupInfo. Fresh request per attempt: the
1031
+ // ephemeral key is minted with it, and a reply to an already-used request is one this
1032
+ // peer can no longer open.
1033
+ const requestID = newPublishID();
1034
+ const request = await port.createRecoveryRequest(requestID);
1035
+ const sealed = await requestGroupInfo(request, requestID, rendezvous, deadline);
1036
+ if (sealed == null) {
1037
+ break;
1038
+ }
1039
+ // 4. Open it and BUILD the external commit, adopting nothing. Bytes this peer cannot open
1040
+ // are a hub-injected or misaddressed reply: ask again.
1041
+ let pending;
1042
+ try {
1043
+ pending = await port.applyRecovery(sealed, requestID);
1044
+ } catch {
1045
+ pending = null;
1046
+ }
1047
+ if (pending == null) continue;
1048
+ // 5. The entries this peer holds, snapshotted BEFORE the rejoined handle replaces them —
1049
+ // the last moment they can be read (a rejoin's handle holds an EMPTY ledger). Kept
1050
+ // across a failed attempt, so a retry filters the same entries rather than snapshotting
1051
+ // the empty ledger a failed bootstrap left.
1052
+ if (inFlightEntries == null) inFlightEntries = await port.getLedger();
1053
+ const inFlight = inFlightEntries;
1054
+ // 6. Publish the external commit, compare-and-set at the head. It changes the ratchet tree,
1055
+ // so it races like any commit — publishing unconditionally would re-open the very fork
1056
+ // the log's compare-and-set closes, on the worst path.
1057
+ const publishID = newPublishID();
1058
+ const payload = await frameCommit(pending.commit, []);
1059
+ let sequenceID;
1060
+ try {
1061
+ sequenceID = (await mux.publish({
1062
+ topicID: commits,
1063
+ payload,
1064
+ retain: 'log',
1065
+ expectedHead,
1066
+ publishID
1067
+ })).sequenceID;
1068
+ } catch (error) {
1069
+ if (!isHeadMismatch(error)) throw error;
1070
+ continue;
1071
+ }
1072
+ // 7. Accepted: the group has this peer's new leaf. Adopt the rejoined handle — the only
1073
+ // place it may be adopted. Deliberately UNJOURNALLED: a crash here leaves an orphaned
1074
+ // external commit in the log, which repairs itself. On restart the orphan is framed at
1075
+ // the group's epoch, not this peer's, so the own-commit trigger (tests authorship AND
1076
+ // current epoch) stays quiet; the original heal condition still holds, the peer rejoins
1077
+ // again, and `resync` collects the leaf the orphan added. Leaves do not accumulate.
1078
+ const rejoinedAtEpoch = port.readCommitHeader(pending.commit)?.epoch;
1079
+ await pending.onAccepted();
1080
+ const accepted = asLogPosition(sequenceID);
1081
+ reconciledHead = accepted;
1082
+ commitLogHead = accepted;
1083
+ // Enacted at that epoch, like an applied commit: without the record a second commit at
1084
+ // that epoch reads as history rather than the fork it is.
1085
+ if (rejoinedAtEpoch != null) appliedByEpoch.set(rejoinedAtEpoch, sequenceID);
1086
+ healRequested = false;
1087
+ // The one place the commit gate is released: the rejoin landed, so this peer's leaf is
1088
+ // back in the tree at the group's epoch and the stale-epoch fork it guards is closed. A
1089
+ // bootstrap that still fails below is a roster-repair problem `commit()`'s own
1090
+ // ledger-completeness check handles — not a reason to keep refusing every commit.
1091
+ stranded = false;
1092
+ await rebuildEpoch();
1093
+ // 8. Bootstrap: REQUIRED, not a formality. Until it runs, the ledger is empty against a
1094
+ // live head — a roster reset where every admin promoted since genesis is invisible and
1095
+ // the next commit is rejected. Failure here is a persistent degraded state, NOT a heal:
1096
+ // keep the condition, keep the snapshotted entries, never report advanced with a ledger
1097
+ // known incomplete.
1098
+ if (!await ensureLedger(deadline)) {
1099
+ healRequested = true;
1100
+ return {
1101
+ advanced: false,
1102
+ reenact: []
1103
+ };
1104
+ }
1105
+ // 9. Re-enact by MEMBERSHIP, never by the failure that brought this peer here. Bootstrap
1106
+ // just fetched the whole ordered, head-verified ledger, so the filter is local and
1107
+ // free: keep only entries the group's ledger does NOT hold.
1108
+ //
1109
+ // An entry it DOES hold was enacted for everyone (that is what the authenticated ledger
1110
+ // means), and appending it again puts it at the END of the log where the fold is
1111
+ // last-write-wins by position: it would win, reverting whatever a later admin wrote over
1112
+ // the same subject, with no error or signal anywhere. A token's content id is its
1113
+ // digest, so token equality IS id equality and this set-difference is the id one.
1114
+ const held = new Set(await port.getLedger());
1115
+ const reenact = inFlight.filter((token)=>!held.has(token));
1116
+ inFlightEntries = null;
1117
+ return {
1118
+ advanced: true,
1119
+ reenact
1120
+ };
1121
+ }
1122
+ return {
1123
+ advanced: false,
1124
+ reenact: []
1125
+ };
260
1126
  });
261
- handshakeTail = op.catch(()=>{});
262
- await op;
263
- return result;
1127
+ };
1128
+ /**
1129
+ * Run a heal the lane asked for, never from inside the lane. `recover()` takes the commit mutex,
1130
+ * so the trigger records and the caller runs this once it releases the mutex. A heal already in
1131
+ * flight absorbs any trigger raised while it runs: the frame that raised it is still in the log,
1132
+ * and the next pull raises it again if the heal did not settle it.
1133
+ */ const healIfRequested = async ()=>{
1134
+ if (!healRequested || healing) return;
1135
+ healing = true;
1136
+ healRequested = false;
1137
+ try {
1138
+ // Still two commits; the second is the host's. No return value to put the entries in, so
1139
+ // they wait for a lane operation that has one — same as a lost commit.
1140
+ const { reenact } = await recover();
1141
+ if (reenact.length > 0) pendingReenact = [
1142
+ ...pendingReenact,
1143
+ ...reenact
1144
+ ];
1145
+ } catch {
1146
+ // No responder, or a reply that would not open. The peer stays degraded, and the frame that
1147
+ // asked for the heal is still in the log: the next pull asks again.
1148
+ } finally{
1149
+ healing = false;
1150
+ }
264
1151
  };
265
1152
  const ready = (async ()=>{
266
- await initHandshake();
1153
+ await initControlLanes();
267
1154
  await buildEpoch();
268
1155
  })();
1156
+ // A failed init rejects every public call, but must not raise an unhandled rejection before the
1157
+ // first is made.
1158
+ const settled = ready.catch(()=>{});
1159
+ // The seed pull runs inside init, where the crash victim whose journal was lost meets its own
1160
+ // un-merged commit. Its heal waits for init to finish, since every lane operation (`recover()`
1161
+ // included) waits on `ready`.
1162
+ void settled.then(()=>healIfRequested());
269
1163
  const withReady = async (fn)=>{
270
1164
  await ready;
271
1165
  return fn();
@@ -280,19 +1174,34 @@ export function createGroupPeer(params) {
280
1174
  to: (memberDID)=>surfaceFor(key).to(memberDID)
281
1175
  };
282
1176
  },
283
- localCommitted,
1177
+ commit,
1178
+ replay,
284
1179
  recover,
285
1180
  resync: async ()=>{
286
1181
  await ready;
287
1182
  await rebuildEpoch();
288
1183
  },
289
1184
  dispose: async ()=>{
290
- await ready;
291
- handshakeUnsubscribe?.();
1185
+ // Tear down even a peer whose init failed — it still holds a hub drain.
1186
+ await settled;
1187
+ commitUnsubscribe?.();
1188
+ rendezvousUnsubscribe?.();
1189
+ // Resolve any in-flight recovery rendezvous FIRST, before clearing its timers. A `recover()`
1190
+ // blocked in `requestGroupInfo` is settled by exactly two things — a reply or its timeout —
1191
+ // and dispose is about to clear that timeout; drain the waiters here or the heal never
1192
+ // settles, `commitTail` never resolves, and every lane operation queued behind it hangs.
1193
+ // Resolve, then clear, so a fired timer cannot race a half-drained map. (The ledger gather
1194
+ // needs no such drain: its timeout is a local held in none of these maps, so it fires and
1195
+ // settles `ensureLedger` on its own.)
1196
+ for (const waiter of recoveryWaiters.values())waiter(null);
1197
+ recoveryWaiters.clear();
292
1198
  for (const timer of recoveryTimers.values())clearTimeout(timer);
293
1199
  for (const timer of pendingReplies.values())clearTimeout(timer);
1200
+ for (const timer of pendingLedgerReplies)clearTimeout(timer);
294
1201
  recoveryTimers.clear();
295
1202
  pendingReplies.clear();
1203
+ pendingLedgerReplies.clear();
1204
+ ledgerWaiters.clear();
296
1205
  suppressedRequests.clear();
297
1206
  await teardownEpoch();
298
1207
  await mux.dispose();