@kumiai/rpc 0.10.2 → 0.10.3

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,52 +1,31 @@
1
1
  import { normalizeDID } from '@kokuin/token';
2
- import { BroadcastClient, createBroadcastResponder, createBroadcastTransport, defaultJitter, encodeEventFrame } from '@kumiai/broadcast';
2
+ import { defaultJitter, encodeEventFrame } from '@kumiai/broadcast';
3
3
  import { createRuntime } from '@sozai/runtime';
4
- import { decodeAppAAD, encodeAppAAD } from './app-aad.js';
5
4
  import { createAppLane } from './app-lane.js';
5
+ import { createAppOutboxAcceptance } from './app-outbox.js';
6
6
  import { classifyCommit, digestAppliedCommit, UNKNOWN_FRAME_VERSION } from './classify.js';
7
7
  import { CommitDeadlineError, isHeadMismatch, JournalEpochError, RecoveryRequiredError } from './commit.js';
8
8
  import { decodeCommitFrame, encodeCommitFrame, isUnsupportedCommitFrameVersion } from './commit-frame.js';
9
- import { isFrameAhead, isMissingLedgerEntries } from './crypto.js';
9
+ import { isMissingLedgerEntries } from './crypto.js';
10
10
  import { asLogPosition, assertForwardPage } from './cursor.js';
11
- import { createDirectedClient, createInboxAcceptor, createInboxPath, createUnroutedTagResponder } from './directed.js';
12
11
  import { PeerDisposedError } from './errors.js';
12
+ import { assertFrameFits } from './frame-size.js';
13
13
  import { adaptBusHandlers } from './handlers.js';
14
14
  import { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND, HANDSHAKE_VERSION } from './handshake.js';
15
+ import { createHostBoundary, wrapCommitBuild, wrapPeerHost, wrapPendingCommit, wrapPendingRecovery } from './host-boundary.js';
15
16
  import { notifyHost } from './host-notice.js';
16
17
  import { createHubMux } from './hub-mux.js';
17
18
  import { createLedgerEntryResolver, encodeLedgerEntries } from './ledger-entries.js';
18
- import { createOpenOncePath } from './open-once.js';
19
+ import { checkedFetchResult, createLogDelivery } from './log-delivery.js';
20
+ import { createEpochRuntime } from './peer-epoch.js';
21
+ import { DEFAULT_APP_LOG_RETENTION_SECONDS, DEFAULT_COMMIT_DEADLINE_MS, DEFAULT_COMMIT_LOG_RETENTION_SECONDS, DEFAULT_RECOVERY_DEADLINE_MS, DEFAULT_RECOVERY_JITTER_MS, DEFAULT_RECOVERY_TIMEOUT_MS } from './peer-types.js';
19
22
  import { retentionOf } from './protocol.js';
20
- import { decodeLedgerReply, decodeLedgerRequest, decodeRecoveryReply, decodeRecoveryRequest, encodeLedgerReply, encodeLedgerRequest, encodeRecoveryReply, encodeRecoveryRequest } from './recovery.js';
23
+ import { decodeLedgerReply, decodeLedgerRequest, decodeRecoveryConfirmRequest, decodeRecoveryReply, decodeRecoveryRequest, decodeRecoveryVerdict, encodeLedgerReply, encodeLedgerRequest, encodeRecoveryConfirmRequest, encodeRecoveryReply, encodeRecoveryRequest, encodeRecoveryVerdict } from './recovery.js';
24
+ import { confirmationTag, createRecoveryCache, waitForRecoveryConfirmation } from './recovery-confirmation.js';
21
25
  import { detectRosterChange } from './roster.js';
22
26
  import { APP_TOPIC_LABEL, commitTopic, inboxTopic, protocolTopic, rendezvousTopic } from './topic.js';
23
- const DEFAULT_RECOVERY_TIMEOUT_MS = 5000;
24
- const DEFAULT_RECOVERY_JITTER_MS = 250;
25
- /**
26
- * How long `recover()` keeps rejoining before giving up and leaving the peer degraded. A
27
- * deadline, not an attempt count: losing the compare-and-set is expected — a heal runs under
28
- * commit pressure and two peers healing at once race each other.
29
- */ const DEFAULT_RECOVERY_DEADLINE_MS = 30_000;
30
- /**
31
- * How long the hub is asked to keep the commit log: **28 days**. Bounds how long a member may be
32
- * offline and still converge by pulling alone, without another member awake to heal it.
33
- *
34
- * Deliberately below the reference hub ceiling (`createMemoryStore`'s `DEFAULT_MAX_RETENTION`, 30
35
- * days): a hub refuses a retention above its ceiling rather than clamping it, so a default sitting
36
- * exactly on the ceiling would leave no room for an upward override — refused outright, and the
37
- * peer not a subscriber of its own commit topic. Asserted in `peer-control-lanes.test.ts`, since a
38
- * tighter operator cap still refuses this default (reported via `hub-mux`).
39
- */ export const DEFAULT_COMMIT_LOG_RETENTION_SECONDS = 28 * 24 * 60 * 60;
40
- /**
41
- * How long the hub is asked to keep an app topic's log. Aligned to the commit window so a
42
- * returning member never rebuilds its membership without also recovering its messages. A separate
43
- * dial, not the commit one reused — the alignment is a choice a host may override.
44
- */ export const DEFAULT_APP_LOG_RETENTION_SECONDS = DEFAULT_COMMIT_LOG_RETENTION_SECONDS;
27
+ export { DEFAULT_APP_LOG_RETENTION_SECONDS, DEFAULT_COMMIT_LOG_RETENTION_SECONDS } from './peer-types.js';
45
28
  /** How many commit frames a single pull asks for. Pull loops until the log is drained. */ const COMMIT_FETCH_LIMIT = 100;
46
- /**
47
- * How long `commit` keeps rebasing before giving up. A deadline, not an attempt count: several
48
- * consecutive lost compare-and-sets on a busy group is ordinary contention.
49
- */ const DEFAULT_COMMIT_DEADLINE_MS = 30_000;
50
29
  /**
51
30
  * Runaway guard only. The deadline is the real bound; this stops a hub that accepts nothing and
52
31
  * never advances its head from spinning the loop forever inside a clock tick.
@@ -64,8 +43,58 @@ const CONFIDENCE_RANK = {
64
43
  observed: 1,
65
44
  authenticated: 2
66
45
  };
67
- export function createGroupPeer(params) {
68
- const { hub, crypto, mls, journal, adoptJournalled, anchorStore, appCursorStore, protocols, handlers, suppress } = params;
46
+ function verdictForOutcome(binding, outcome) {
47
+ switch(outcome.kind){
48
+ case 'applied':
49
+ return {
50
+ ...binding,
51
+ verdict: 'confirmed',
52
+ epoch: outcome.epoch,
53
+ tag: confirmationTag(outcome.key, binding.requestID)
54
+ };
55
+ case 'superseded':
56
+ return {
57
+ ...binding,
58
+ verdict: 'superseded'
59
+ };
60
+ case 'refused':
61
+ return {
62
+ ...binding,
63
+ verdict: 'refused',
64
+ reason: outcome.reason
65
+ };
66
+ }
67
+ }
68
+ export function createGroupPeer(input) {
69
+ const boundary = createHostBoundary();
70
+ const params = wrapPeerHost(boundary, input);
71
+ const { hub, crypto, mls, journal: hostJournal, adoptJournalled, anchorStore, appCursorStore, protocols, handlers, suppress } = params;
72
+ let revokeHolds = 0;
73
+ let heldJournalID;
74
+ const logSubmissions = new Set();
75
+ const journal = hostJournal == null ? undefined : {
76
+ get: async ()=>{
77
+ const entry = await hostJournal.get();
78
+ heldJournalID = entry?.holdsLogSends === true ? entry.publishID : undefined;
79
+ return entry;
80
+ },
81
+ put: async (entry)=>{
82
+ await hostJournal.put(entry);
83
+ heldJournalID = entry.holdsLogSends === true ? entry.publishID : undefined;
84
+ },
85
+ markAccepted: (publishID, sequenceID)=>hostJournal.markAccepted(publishID, sequenceID),
86
+ clear: async (publishID)=>{
87
+ await hostJournal.clear(publishID);
88
+ if (heldJournalID === publishID) heldJournalID = undefined;
89
+ logDelivery?.trigger();
90
+ }
91
+ };
92
+ const logSendsHeld = ()=>revokeHolds > 0 || heldJournalID != null;
93
+ const settleLogSubmissions = async ()=>{
94
+ await Promise.allSettled([
95
+ ...logSubmissions
96
+ ]);
97
+ };
69
98
  if (crypto.pending != null && mls == null) {
70
99
  throw new Error('GroupCrypto.pending requires mls and the durable commit lane');
71
100
  }
@@ -94,18 +123,6 @@ export function createGroupPeer(params) {
94
123
  onReceiveEnded: params.onReceiveEnded
95
124
  } : {}
96
125
  });
97
- let runtimes = new Map();
98
- /**
99
- * The epoch's self-inbox topic and the one path that opens its frames. Held per peer rather
100
- * than per protocol because the topic is not per protocol, and rebuilt with the epoch — the
101
- * topic is anchor-bound, so a roster change moves it.
102
- */ let inboxLane;
103
- /**
104
- * The one peer-level consumer of the shared inbox path that NACKs a frame tagged for a protocol
105
- * no acceptor here serves — every acceptor filters on its own tag, so such a frame would
106
- * otherwise be dropped silently. Rebuilt with the epoch, since it replies on the anchor-bound
107
- * inbox topics the rotation moves.
108
- */ let unroutedTagResponder;
109
126
  /**
110
127
  * The host's app event handlers, per protocol, as the drain calls them — the same adaptation
111
128
  * the live bus server is built from, so a drained frame and a pushed one reach the host by the
@@ -167,14 +184,14 @@ export function createGroupPeer(params) {
167
184
  ...params.onAppDeliveryStalled != null ? {
168
185
  onAppDeliveryStalled: (event)=>{
169
186
  hostOutbox.push(()=>{
170
- if (!disposed) notifyHost(params.onAppDeliveryStalled, event);
187
+ if (!disposed) notifyHost((value)=>params.onAppDeliveryStalled?.(value), event);
171
188
  });
172
189
  }
173
190
  } : {},
174
191
  ...params.onAppDeliveryResumed != null ? {
175
192
  onAppDeliveryResumed: (event)=>{
176
193
  const notify = ()=>{
177
- if (!disposed) notifyHost(params.onAppDeliveryResumed, event);
194
+ if (!disposed) notifyHost((value)=>params.onAppDeliveryResumed?.(value), event);
178
195
  };
179
196
  if (appNoticeInSerial) hostOutbox.push(notify);
180
197
  else queueMicrotask(notify);
@@ -186,53 +203,86 @@ export function createGroupPeer(params) {
186
203
  });
187
204
  let sealBarrier;
188
205
  let releaseSealBarrier;
206
+ let anchorPending;
207
+ let anchorRecoveryPending = false;
189
208
  let sealError;
190
209
  const finishSealBarrier = ()=>{
191
210
  sealBarrier = undefined;
192
211
  releaseSealBarrier?.();
193
212
  releaseSealBarrier = undefined;
194
213
  };
195
- /**
196
- * Capture the anchor from the port's post-commit handle and persist it. The one place the
197
- * anchor is written from the live epoch, and the one place it is saved.
198
- *
199
- * KNOWN BOUND: `processCommit` is durable before this runs, so a crash between the two leaves a
200
- * persisted anchor one rotation stale, and the restarted peer stays off the group's topic until
201
- * the next roster change rotates it again. Closing it needs the anchor inside the same durable
202
- * write as the handle, which this layer cannot reach.
203
- */ const captureAnchor = async ()=>{
204
- // Secret and epoch from one export: a pair from two reads can straddle a handle move.
214
+ /** The advance whose anchor rotation was last captured, so a retry never captures it twice. */ let capturedAdvance;
215
+ const captureAnchor = async (advance)=>{
205
216
  const { secret, epoch } = await crypto.exportSecret(APP_TOPIC_LABEL);
206
217
  if (disposed) return;
218
+ for (const name of Object.keys(protocols)){
219
+ mux.retainTopic(protocolTopic(secret, epoch, name), {
220
+ retention: appLogRetentionSeconds
221
+ });
222
+ }
223
+ mux.retainTopic(inboxTopic(secret, epoch, localDID), {
224
+ retention: appLogRetentionSeconds
225
+ });
207
226
  anchor = {
208
227
  secret,
209
228
  epoch
210
229
  };
230
+ // Marked with the anchor, before persistence can fail, so a retry never captures it twice.
231
+ if (advance != null) capturedAdvance = advance;
232
+ anchorPending = undefined;
211
233
  sealError = undefined;
212
234
  finishSealBarrier();
213
- await anchorStore?.save(anchor);
214
- if (disposed) return;
215
- // The anchor moving IS the segment boundary, so every capture ends the segment the buffer
216
- // belongs to. AFTER the assignment above: the lane rebuilds its cursors off the live anchor.
235
+ await anchorStore?.save({
236
+ anchor
237
+ });
217
238
  appLane.reset();
218
239
  };
219
- /**
220
- * The opened form of a live frame, keyed by the plaintext the open produced. Written by the
221
- * inbound path below and read by every transport built on it, so one open serves all of them.
222
- *
223
- * {@link GroupUnwrapResult}, not `@kumiai/broadcast`'s `UnwrapResult`: what is stored here
224
- * reaches `BroadcastClient.gather` as the sender it keys its quorum on, and broadcast's type
225
- * says `senderDID?`. `crypto.unwrap` REQUIRES the field, so the narrowing below checks a promise
226
- * already made — a frame that breaks it is refused rather than fanned out.
227
- */ const openedFrames = new WeakMap();
228
- /**
229
- * Whether a frame `unwrap` just refused might still open once this handle catches up — read from
230
- * the refusal's locked answer ({@link "crypto".FrameEpochError}), never the epoch hint.
231
- * On the open-once failure path ({@link "open-once".OpenOncePathParams.retainOnFailure}) answering
232
- * `true` withholds the ack so the frame survives a reconnect. Mailbox-class frames have no staging
233
- * of their own (unlike `app-lane.ts`'s `note`/`ahead`), which is what made acking a transient
234
- * refusal here a permanent loss.
235
- */ const retainOnFailure = (_message, error)=>isFrameAhead(error);
240
+ /** The rotation resolved without moving the anchor: drop the record and keep the anchor. */ const keepAnchor = async ()=>{
241
+ anchorPending = undefined;
242
+ sealError = undefined;
243
+ finishSealBarrier();
244
+ await anchorStore?.save({
245
+ anchor
246
+ });
247
+ };
248
+ const requireAnchorRecovery = ()=>{
249
+ anchorRecoveryPending = true;
250
+ healRequested = true;
251
+ sealError = new Error('app anchor requires confirmed recovery');
252
+ };
253
+ const resolveAnchorRotation = async (params)=>{
254
+ const { port, knownUnlanded = false, initial = false, landed = false } = params;
255
+ const record = anchorPending;
256
+ if (record == null) return;
257
+ const epoch = await port.readEpoch();
258
+ assertLive();
259
+ // A rejoin from a losing branch can land on its old epoch number, so the number alone cannot
260
+ // say whether it landed. Only the advance that resolved knows — unless that advance already
261
+ // captured its anchor, and this record is a retry opened at the epoch it landed on.
262
+ const sameNumber = record.epochAfter === record.epochBefore;
263
+ const landedHere = sameNumber && landed && record.advance !== capturedAdvance;
264
+ if (epoch === record.epochBefore && !landedHere) {
265
+ if (!knownUnlanded && !initial) return;
266
+ if (sameNumber && !knownUnlanded) {
267
+ // Found at startup with nothing to tell the two states apart: recover rather than keep an
268
+ // anchor that may belong to the losing branch.
269
+ requireAnchorRecovery();
270
+ return;
271
+ }
272
+ await keepAnchor();
273
+ return;
274
+ }
275
+ if (epoch !== record.epochAfter) {
276
+ requireAnchorRecovery();
277
+ return;
278
+ }
279
+ const roster = (await port.rosterEntries()).map((entry)=>normalizeDID(entry.did));
280
+ if (record.forced || detectRosterChange(record.rosterBefore, roster)) {
281
+ await captureAnchor(record.advance);
282
+ } else {
283
+ await keepAnchor();
284
+ }
285
+ };
236
286
  // Live log pushes carry no authoritative bytes or position. One queued journal-first pull
237
287
  // covers a burst; a failed pull retries without waiting for another hub delivery.
238
288
  let appPullNeeded = false;
@@ -257,6 +307,7 @@ export function createGroupPeer(params) {
257
307
  await ensureLedger(Date.now() + recoveryTimeoutMs);
258
308
  await reconcileCommits();
259
309
  });
310
+ await healIfRequested();
260
311
  appPullBackoff = 1000;
261
312
  } catch {
262
313
  appPullNeeded = true;
@@ -276,6 +327,38 @@ export function createGroupPeer(params) {
276
327
  appPullNeeded = true;
277
328
  armAppPull(0);
278
329
  };
330
+ // An incomplete ledger skips the commit pull without failing it. In a quiet group no later
331
+ // delivery would retry, so the skip arms its own backoff. Each retry is a commit wakeup without
332
+ // the heal: heals keep their own triggers and backoff.
333
+ let ledgerRetryTimer;
334
+ let ledgerRetryBackoff = 1000;
335
+ const armLedgerRetry = ()=>{
336
+ if (disposed || ledgerRetryTimer != null) return;
337
+ ledgerRetryTimer = setTimeout(()=>{
338
+ ledgerRetryTimer = undefined;
339
+ if (disposed) return;
340
+ let ledgerReady = false;
341
+ void ready.then(()=>{
342
+ if (disposed) return;
343
+ return runSerial(async ()=>{
344
+ if (disposed) return;
345
+ const replayed = await replayJournal();
346
+ if (mls != null && await ensureLedger(Date.now() + recoveryTimeoutMs)) {
347
+ ledgerReady = true;
348
+ await finalizeBootstrap(mls);
349
+ }
350
+ if (disposed) return;
351
+ const pulled = await pullCommits();
352
+ if (!disposed && (replayed || pulled)) await rebuildEpoch();
353
+ });
354
+ }).catch(()=>{
355
+ // a failed retry leaves the cursor put; pullCommits re-arms while the ledger is incomplete
356
+ })// A strand the completed pull found heals outside the lane. An incomplete ledger does not
357
+ // heal here: the gather that failed is the repair, and the backoff re-runs it.
358
+ .then(()=>ledgerReady ? healIfRequested() : undefined);
359
+ }, ledgerRetryBackoff);
360
+ ledgerRetryBackoff = Math.min(ledgerRetryBackoff * 2, 60_000);
361
+ };
279
362
  const retryAppPull = ()=>{
280
363
  if (disposed) return;
281
364
  appPullBackoff = 1000;
@@ -287,312 +370,118 @@ export function createGroupPeer(params) {
287
370
  appPullRetryNow = appPullActive;
288
371
  armAppPull(0);
289
372
  };
290
- /**
291
- * The app lane's inbound path: one open per topic, fanned out as plaintext, with each frame's
292
- * log position noted once its open settles. Every consumer's own `unwrap` is then a pure lookup of the
293
- * opened result ({@link openedFrames}), and nothing downstream touches the handle.
294
- *
295
- * See {@link createOpenOncePath} for why a lane may only open a frame once.
296
- */ const createInboundPath = (name, topicID)=>{
297
- return createOpenOncePath({
298
- mux,
299
- topicID,
300
- unwrap: (b)=>{
301
- const hinted = crypto.frameAAD(b);
302
- const decoded = hinted == null ? null : decodeAppAAD(hinted);
303
- const intent = decoded?.topicID === topicID ? decoded.intent : 'ephemeral';
304
- return crypto.unwrap(b, {
305
- expectedAAD: encodeAppAAD({
306
- topicID,
307
- intent
308
- })
309
- });
310
- },
311
- retainOnFailure,
312
- project: (_message, opened)=>{
313
- const { payload, senderDID } = opened;
314
- if (typeof senderDID !== 'string' || senderDID === '') {
315
- // `project` returning `undefined` drops the frame deliberately (see
316
- // `OpenOncePathParams.project`): the app lane is always MLS-sealed, so an open that
317
- // recovers no sender is not a frame to deliver unattributed. Fails CLOSED against the
318
- // shared open-once signature's wider `UnwrapResult`.
319
- return undefined;
320
- }
321
- // Normalized at the open, before it is keyed: every consumer of `openedFrames` (the
322
- // acceptor, `gather`'s quorum) must see one canonical sender regardless of which DID form
323
- // MLS recovered this frame under.
324
- openedFrames.set(payload, {
325
- ...opened,
326
- senderDID: normalizeDID(senderDID)
373
+ const epochRuntime = createEpochRuntime({
374
+ boundary,
375
+ mux,
376
+ crypto,
377
+ localDID,
378
+ protocols,
379
+ handlers,
380
+ suppress,
381
+ runtime: params.runtime,
382
+ appLogRetentionSeconds,
383
+ anchor: ()=>anchor,
384
+ sealBarrier: ()=>sealBarrier,
385
+ sealError: ()=>sealError,
386
+ isDisposed: ()=>disposed,
387
+ note: (name, topicID, message, failure)=>appLane.note(name, topicID, message, failure),
388
+ requestAppPull
389
+ });
390
+ const { buildEpoch, teardownEpoch, rebuildEpoch, surfaceFor, sealForSegment } = epochRuntime;
391
+ const appOutboxAcceptance = mls == null ? undefined : createAppOutboxAcceptance({
392
+ outbox: params.appOutbox,
393
+ limit: params.appOutboxLimit,
394
+ admission: ()=>mls.sendAdmission()
395
+ });
396
+ let floor = {
397
+ epoch: crypto.epoch(),
398
+ position: null,
399
+ covered: true
400
+ };
401
+ let locallyRemoved = false;
402
+ const logDelivery = appOutboxAcceptance == null || mls == null ? undefined : createLogDelivery({
403
+ queue: appOutboxAcceptance,
404
+ ready: async ()=>{
405
+ await ready;
406
+ if (heldJournalID != null) {
407
+ await runSerial(async ()=>{
408
+ if (await replayJournal()) await rebuildEpoch();
327
409
  });
328
- return payload;
329
- },
330
- note: (message, failure)=>appLane.note(name, topicID, message, failure),
331
- wakeup: (message)=>{
332
- if (crypto.pending == null) return false;
333
- const aad = crypto.frameAAD(message.payload);
334
- if (aad == null || decodeAppAAD(aad)?.intent !== 'log') return false;
335
- requestAppPull();
336
- return true;
337
410
  }
338
- });
339
- };
340
- /**
341
- * One protocol's live-lane transport: LISTENS on the topic the runtime is built for, and
342
- * PUBLISHES to the segment that contains each frame's own seal epoch — see
343
- * {@link sealForSegment} for why those can differ mid-rotation.
344
- *
345
- * The topic is decided by the SEAL and carried to the publish, since the two are separate calls
346
- * with an anchor that can move between them: `wrap` records the topic under the ciphertext it
347
- * produced, keyed by the bytes' own identity rather than a slot, since two transports share this
348
- * lane and interleave their writes.
349
- *
350
- * The subscribe keeps the runtime's topic — a rotation rebuilds the listeners, but a topic stays
351
- * subscribed at the mux for the member's whole life either way.
352
- */ const segmentBoundTransport = (name, topicID, inbound)=>{
353
- const sealedOn = new WeakMap();
354
- return createBroadcastTransport({
355
- topicID,
356
- bus: {
357
- // `builtFor` is the topic this transport was constructed with, and it is the fallback
358
- // rather than the answer: anything published through here was sealed by the `wrap` below,
359
- // so the recorded topic is the one that agrees with the seal.
360
- publish: async (builtFor, payload)=>{
361
- await mux.bus.publish(sealedOn.get(payload) ?? builtFor, payload);
362
- },
363
- // Already-opened plaintext, from the topic's one inbound path. The `unwrap` below only
364
- // recovers the sender the open already authenticated.
365
- subscribe: (_listenOn, onMessage)=>inbound(onMessage)
366
- },
367
- wrap: async (bytes)=>{
368
- const sealed = await sealForSegment(name, bytes);
369
- sealedOn.set(sealed.payload, sealed.topicID);
370
- return sealed.payload;
371
- },
372
- unwrap: (payload)=>openedFrames.get(payload) ?? payload
373
- });
374
- };
375
- const buildEpoch = async ()=>{
376
- const next = new Map();
377
- // ONE inbox lane for the whole peer, not one per protocol: the topic does not name a
378
- // protocol, so every acceptor and directed client opening its own frames is the defect this
379
- // shape prevents.
380
- const selfInbox = inboxTopic(anchor.secret, anchor.epoch, localDID);
381
- inboxLane = {
382
- topicID: selfInbox,
383
- path: createInboxPath({
384
- mux,
385
- topicID: selfInbox,
386
- unwrap: (b)=>crypto.unwrap(b, {
387
- expectedAAD: encodeAppAAD({
388
- topicID: selfInbox,
389
- intent: 'ephemeral'
390
- })
391
- }),
392
- retainOnFailure
393
- })
394
- };
395
- // ONE responder for the whole peer, on the shared path: it NACKs any frame whose tag names a
396
- // protocol not in `protocols`, restoring the legible reply an acceptor's own filter drops.
397
- unroutedTagResponder = createUnroutedTagResponder({
398
- mux,
399
- localDID,
400
- inbound: inboxLane.path,
401
- isRegistered: (name)=>Object.hasOwn(protocols, name),
402
- sealReply: sealDirectedReply
403
- });
404
- for (const [name, protocol] of Object.entries(protocols)){
405
- // The app topic is bound to the ANCHOR, not the live epoch — see {@link sealForSegment}.
406
- // Content stays sealed under the live epoch crypto below; only the topic ID is anchor-bound.
407
- const topicID = protocolTopic(anchor.secret, anchor.epoch, name);
408
- // Subscribed for the member's whole life, like the commit and rendezvous topics: the mux
409
- // never unsubscribes on rotation, only tears down the LISTENERS on the epoch left.
410
- // Unsubscribing would tell the hub to drop this member's pending deliveries and free any
411
- // frame it was the last reader of — deleting unread messages for everyone.
412
- //
413
- // Subscribed HERE, not left to the transports below, because the subscription is also what
414
- // asks the hub how long to hold the log; a bus is a fan-out abstraction with no such request.
415
- mux.retainTopic(topicID, {
416
- retention: appLogRetentionSeconds
417
- });
418
- // One path, two consumers: the frame is opened once here and both are given the plaintext.
419
- const inbound = createInboundPath(name, topicID);
420
- const client = new BroadcastClient({
421
- transport: segmentBoundTransport(name, topicID, inbound),
422
- ...params.runtime != null ? {
423
- runtime: params.runtime
424
- } : {}
425
- });
426
- const { events, requestHandlers } = adaptBusHandlers(protocol, handlers[name], suppress);
427
- const busServer = createBroadcastResponder({
428
- transport: segmentBoundTransport(name, topicID, inbound),
429
- from: localDID,
430
- requestHandlers,
431
- events
432
- });
433
- const acceptor = createInboxAcceptor({
434
- mux,
435
- localDID,
436
- selfInboxTopic: selfInbox,
437
- inbound: inboxLane.path,
438
- resolveSendTopic: (senderDID)=>inboxTopic(anchor.secret, anchor.epoch, senderDID),
439
- protocol: protocol,
440
- protocolName: name,
441
- handlers: handlers[name],
442
- wrap: crypto.wrap
443
- });
444
- next.set(name, {
445
- client,
446
- busServer,
447
- acceptor,
448
- directed: new Map()
411
+ },
412
+ floor: ()=>floor,
413
+ held: ()=>logSendsHeld() || locallyRemoved || stranded || anchorRecoveryPending || sealBarrier != null || sealError != null || activeRecovery != null || !mls.sendAdmission().admissible,
414
+ probe: async ()=>{
415
+ if (commitTopicID == null) throw new Error('Commit topic is unavailable');
416
+ const result = checkedFetchResult(await mux.fetchTopic({
417
+ topicID: commitTopicID,
418
+ ...floor.position != null ? {
419
+ after: floor.position
420
+ } : {},
421
+ limit: 1
422
+ }));
423
+ commitLogHead = result.head == null ? null : asLogPosition(result.head);
424
+ return result;
425
+ },
426
+ pull: async ()=>{
427
+ await runSerial(async ()=>{
428
+ await replayJournal();
429
+ await ensureLedger(Date.now() + recoveryTimeoutMs);
430
+ await reconcileCommits();
449
431
  });
450
- }
451
- runtimes = next;
452
- };
453
- const teardownEpoch = async ()=>{
454
- // Disposal order is independent, so tear everything down concurrently and surface every
455
- // failure rather than dying on the first.
456
- const disposals = [];
457
- // A bare unsubscribe of the shared path — synchronous, cannot reject — dropped alongside the
458
- // acceptor consumers of that same path.
459
- unroutedTagResponder?.dispose();
460
- unroutedTagResponder = undefined;
461
- for (const runtime of runtimes.values()){
462
- for (const directed of runtime.directed.values())disposals.push(directed.dispose());
463
- runtime.directed.clear();
464
- disposals.push(runtime.busServer.dispose());
465
- disposals.push(runtime.acceptor.dispose());
466
- disposals.push(runtime.client.dispose());
467
- }
468
- runtimes = new Map();
469
- const results = await Promise.allSettled(disposals);
470
- const reasons = results.flatMap((r)=>r.status === 'rejected' ? [
471
- r.reason
472
- ] : []);
473
- // Defensive: no child rejects today — all are enkaku `Disposer`-based (a failing dispose is
474
- // swallowed to `console.warn`, the promise still resolves) or a refcount decrement that cannot
475
- // throw — so this guards a future non-`Disposer` child. Kept live because rotation shares this
476
- // path, and a `BroadcastClient.prototype.dispose` spy forces it in test.
477
- if (reasons.length > 0) {
478
- throw new AggregateError(reasons, 'Group epoch teardown failed');
479
- }
480
- };
481
- /** Wait while an advance can move the handle before its new anchor is captured. */ const sealForSegment = async (name, bytes, intent = 'ephemeral')=>{
482
- while(true){
483
- if (sealError != null) throw sealError;
484
- if (sealBarrier != null) {
485
- await sealBarrier;
486
- continue;
432
+ await healIfRequested();
433
+ },
434
+ heal: async ()=>{
435
+ healRequested = true;
436
+ await healIfRequested();
437
+ },
438
+ seal: async (entry)=>{
439
+ while(true){
440
+ const at = anchor;
441
+ const frame = await sealForSegment(entry.protocol, entry.data, 'log');
442
+ const epoch = crypto.frameEpoch(frame.payload);
443
+ const snapshot = floor;
444
+ const admission = mls.sendAdmission();
445
+ if (anchor !== at || sealBarrier != null || snapshot.epoch !== epoch) continue;
446
+ if (sealError != null) throw sealError;
447
+ if (!admission.admissible || admission.epoch !== epoch) {
448
+ throw new Error('Application admission snapshot moved');
449
+ }
450
+ return {
451
+ ...frame,
452
+ floor: snapshot
453
+ };
487
454
  }
488
- const at = anchor;
489
- const topicID = protocolTopic(at.secret, at.epoch, name);
490
- const payload = await crypto.wrap(bytes, {
491
- aad: encodeAppAAD({
492
- topicID,
493
- intent
494
- })
495
- });
496
- if (sealError != null) throw sealError;
497
- if (anchor === at && sealBarrier == null) return {
498
- topicID,
499
- payload
500
- };
501
- }
502
- };
503
- /**
504
- * Seal a directed reply (the unrouted-tag NACK) to a recipient's inbox under ONE anchor snapshot.
505
- * The reply topic and the seal must agree on the epoch: were the topic read from the live anchor
506
- * and the seal taken as a separate step, a rotation landing between them would address an
507
- * old-epoch inbox with new-epoch ciphertext, published onto a topic the recipient no longer reads
508
- * and silently lost. Re-read the anchor after the seal and re-seal if it moved — same identity
509
- * (not epoch-equality) guard as {@link sealForSegment}.
510
- */ const sealDirectedReply = async (recipientDID, tagged)=>{
511
- while(true){
512
- const at = anchor;
513
- const topicID = inboxTopic(at.secret, at.epoch, recipientDID);
514
- const payload = await crypto.wrap(tagged, {
515
- aad: encodeAppAAD({
516
- topicID,
517
- intent: 'ephemeral'
518
- })
455
+ },
456
+ put: (entry)=>params.appOutbox.put(entry),
457
+ publish: (frame)=>{
458
+ // No await between the hold check, registration and transport handoff.
459
+ if (logSendsHeld()) return null;
460
+ let settle = ()=>{};
461
+ const completion = new Promise((resolve)=>{
462
+ settle = resolve;
519
463
  });
520
- if (anchor === at) return {
521
- topicID,
522
- payload
464
+ logSubmissions.add(completion);
465
+ const finish = ()=>{
466
+ logSubmissions.delete(completion);
467
+ settle();
523
468
  };
524
- }
525
- };
526
- const surfaceFor = (name)=>{
527
- const runtime = runtimes.get(name);
528
- if (runtime == null) throw new Error(`Unknown protocol: ${name}`);
529
- return {
530
- dispatch: async (prc, config)=>{
531
- const data = config?.data ?? {};
532
- // Route by the procedure's declared retention. A `log` event goes to the app topic's log
533
- // lane (retained, pullable); ephemeral events and RPC stay on the live mailbox lane. The
534
- // log payload is byte-identical to what the broadcast transport would produce, so online
535
- // subscribers still receive it through the same drain.
536
- const protocol = protocols[name];
537
- if (protocol === undefined) throw new Error(`Unknown protocol: ${name}`);
538
- if (retentionOf(protocol, prc) === 'log') {
539
- const { topicID, payload } = await sealForSegment(name, encodeEventFrame(prc, data), 'log');
540
- await mux.publish({
541
- topicID,
542
- payload,
543
- retain: 'log'
544
- });
545
- return;
546
- }
547
- await runtime.client.dispatch(prc, data);
548
- },
549
- request: (prc, config)=>runtime.client.request(prc, config?.param, {
550
- errorThreshold: config?.errorThreshold,
551
- timeoutMs: config?.timeoutMs
552
- }),
553
- gather: (prc, config)=>runtime.client.gather(prc, config?.param, {
554
- quorum: config?.quorum,
555
- timeoutMs: config?.timeoutMs,
556
- onReply: config?.onReply,
557
- signal: config?.signal
558
- }),
559
- to: async (memberDID)=>{
560
- // Normalized ONCE, at the ingress: the cache key, the topic derivation and the
561
- // directed client's own filter (`senderDID !== memberDID`) must all see one canonical
562
- // form, or a long-form caller never converges onto the short form MLS actually replies
563
- // under.
564
- const member = normalizeDID(memberDID);
565
- const cached = runtime.directed.get(member);
566
- if (cached != null) return cached.client;
567
- const lane = inboxLane;
568
- if (lane == null) throw new Error('Peer is not started');
569
- const created = createDirectedClient({
570
- mux,
571
- localDID,
572
- memberDID: member,
573
- sendTopicID: inboxTopic(anchor.secret, anchor.epoch, member),
574
- // The epoch's own inbox topic and its one open path: reading replies through a path
575
- // built for a topic this client does not receive on would spend keys opening frames for
576
- // a lane nobody listens to.
577
- receiveTopicID: lane.topicID,
578
- inbound: lane.path,
579
- wrap: crypto.wrap,
580
- protocol: name,
581
- ...params.runtime != null ? {
582
- runtime: params.runtime
583
- } : {}
469
+ try {
470
+ const submission = mux.publish({
471
+ ...frame,
472
+ retain: 'log'
584
473
  });
585
- runtime.directed.set(member, created);
586
- return created.client;
474
+ void submission.then(finish, finish);
475
+ return submission;
476
+ } catch (error) {
477
+ finish();
478
+ throw error;
587
479
  }
588
- };
589
- };
590
- const rebuildEpoch = async ()=>{
591
- if (disposed) return;
592
- await teardownEpoch();
593
- if (disposed) return;
594
- await buildEpoch();
595
- };
480
+ },
481
+ remove: (seq)=>params.appOutbox.remove(seq),
482
+ clear: ()=>params.appOutbox.clear(),
483
+ cleared: (notice)=>notifyHost(params.onAppOutboxCleared, notice)
484
+ });
596
485
  /**
597
486
  * Set as `dispose()`'s FIRST statement. The peer's post-dispose rule has two forms and this is
598
487
  * the host-facing one: everything a HOST asks of a disposed peer is refused, loudly. The inbound
@@ -624,6 +513,36 @@ export function createGroupPeer(params) {
624
513
  * malformed. Not a delivery position: read only out of a `fetchTopic` result or a log publish
625
514
  * (see `cursor.ts`). `null` means nothing processed — read the log from its oldest retained frame.
626
515
  */ let reconciledHead = null;
516
+ let durableCursor = null;
517
+ /**
518
+ * Persist the strand before anything steps past its evidence. The durable position stays where
519
+ * it was, so a restart re-reads an ahead frame; a losing fork was applied before its winner was
520
+ * seen, so only the flag carries it across a restart.
521
+ */ const persistStrand = async ()=>{
522
+ if (mls == null || params.appOutbox == null) return;
523
+ const epoch = await mls.readEpoch();
524
+ if (durableCursor?.stranded === true && durableCursor.epoch === epoch) return;
525
+ const cursor = {
526
+ position: durableCursor?.epoch === epoch ? durableCursor.position : null,
527
+ epoch,
528
+ stranded: true
529
+ };
530
+ await params.appOutbox.putCommitCursor(cursor);
531
+ durableCursor = cursor;
532
+ };
533
+ const saveCommitCursor = async (position)=>{
534
+ if (mls == null) return;
535
+ if (stranded) await persistStrand();
536
+ else if (params.appOutbox != null) {
537
+ const cursor = {
538
+ position,
539
+ epoch: await mls.readEpoch()
540
+ };
541
+ await params.appOutbox.putCommitCursor(cursor);
542
+ durableCursor = cursor;
543
+ }
544
+ reconciledHead = position;
545
+ };
627
546
  /**
628
547
  * The commit log's TIP as the last complete drain reported it — the anchor every commit
629
548
  * compare-and-sets against.
@@ -650,6 +569,25 @@ export function createGroupPeer(params) {
650
569
  * operation. An active recovery absorbs concurrent requests.
651
570
  */ let healRequested = false;
652
571
  let activeRecovery = null;
572
+ let refusalHeld = false;
573
+ let pendingRecovery = null;
574
+ let retryRecoveryAdoption = null;
575
+ let recoveryRetryTimer;
576
+ let recoveryBackoff = 1000;
577
+ const clearRecoveryRetry = ()=>{
578
+ if (recoveryRetryTimer != null) clearTimeout(recoveryRetryTimer);
579
+ recoveryRetryTimer = undefined;
580
+ };
581
+ const retryRecovery = ()=>{
582
+ if (disposed || recoveryRetryTimer != null || renewalHeld() || refusalHeld) return;
583
+ recoveryRetryTimer = setTimeout(()=>{
584
+ recoveryRetryTimer = undefined;
585
+ if (disposed || renewalHeld() || refusalHeld || activeRecovery != null) return;
586
+ healRequested = true;
587
+ void healIfRequested();
588
+ }, recoveryBackoff);
589
+ recoveryBackoff = Math.min(recoveryBackoff * 2, 60_000);
590
+ };
653
591
  let recoveryGeneration = 0;
654
592
  let bootstrapHealRequested = false;
655
593
  let episode = null;
@@ -670,6 +608,11 @@ export function createGroupPeer(params) {
670
608
  * either. Gating on poison would rebuild the group-death hazard the classifier's `poison` row
671
609
  * refuses.
672
610
  */ let stranded = false;
611
+ let renewalRequiredEpoch = null;
612
+ const renewalHeld = ()=>{
613
+ if (renewalRequiredEpoch != null && crypto.epoch() !== renewalRequiredEpoch) renewalRequiredEpoch = null;
614
+ return renewalRequiredEpoch != null;
615
+ };
673
616
  /**
674
617
  * A commit this peer journalled that never landed and cannot re-issue itself: held until a lane
675
618
  * operation with a return value can hand it to the host. Dropping it is the one thing that must
@@ -680,8 +623,8 @@ export function createGroupPeer(params) {
680
623
  * The ledger entries this peer held when it rejoined — snapshotted BEFORE the rejoined handle
681
624
  * replaces them, since a handle that rejoined by external commit holds an EMPTY ledger.
682
625
  *
683
- * The peer's own LEDGER, not its journal (always settled by the time a heal runs). What a
684
- * healing peer holds that the group may not is its ledger: entries enacted on a discarded
626
+ * A lost anchor secret also defers journal bodies into this set. Other entries come from the
627
+ * peer's ledger: entries enacted on a discarded
685
628
  * branch, or kept while the group moved on. Filtering that against the group's authenticated
686
629
  * ledger is the membership rule as a set-difference: re-enact iff the group's ledger does not
687
630
  * already contain it.
@@ -690,7 +633,6 @@ export function createGroupPeer(params) {
690
633
  * entries rather than snapshotting an empty ledger.
691
634
  */ let inFlightEntries = null;
692
635
  let awaitingBootstrap = null;
693
- let rejoinAnchorNeedsCapture = false;
694
636
  let rejoinRuntimeNeedsBuild = false;
695
637
  /**
696
638
  * Entries a heal decided must be re-enacted, waiting for a lane operation with a return value —
@@ -698,11 +640,12 @@ export function createGroupPeer(params) {
698
640
  * re-enacts with an ordinary `commit()`.
699
641
  */ let pendingReenact = [];
700
642
  let hostOutbox = [];
643
+ let recoveryNotices = [];
701
644
  const emitStrand = (observation)=>{
702
- hostOutbox.push(()=>notifyHost(params.onStrand, observation));
645
+ hostOutbox.push(()=>notifyHost((value)=>params.onStrand?.(value), observation));
703
646
  };
704
647
  const emitRecovery = (event)=>{
705
- hostOutbox.push(()=>notifyHost(params.onRecovery, event));
648
+ recoveryNotices.push(()=>notifyHost((value)=>params.onRecovery?.(value), event));
706
649
  };
707
650
  const observeStrand = (observation)=>{
708
651
  bootstrapHealRequested = false;
@@ -723,6 +666,11 @@ export function createGroupPeer(params) {
723
666
  const batch = hostOutbox;
724
667
  hostOutbox = [];
725
668
  for (const notice of batch)notice();
669
+ if (activeRecovery == null) {
670
+ const recoveries = recoveryNotices;
671
+ recoveryNotices = [];
672
+ for (const notice of recoveries)notice();
673
+ }
726
674
  };
727
675
  /**
728
676
  * The group's commit mutex: every commit-lane operation serialized through one tail. The
@@ -737,6 +685,7 @@ export function createGroupPeer(params) {
737
685
  journalReplayed = false;
738
686
  appNoticeInSerial = true;
739
687
  try {
688
+ if (retryRecoveryAdoption != null) await retryRecoveryAdoption();
740
689
  return await fn();
741
690
  } finally{
742
691
  appNoticeInSerial = false;
@@ -745,9 +694,11 @@ export function createGroupPeer(params) {
745
694
  commitTail = op.then(()=>{}, ()=>{});
746
695
  return op.then((value)=>{
747
696
  flushHostOutbox();
697
+ logDelivery?.trigger();
748
698
  return value;
749
699
  }, (error)=>{
750
700
  flushHostOutbox();
701
+ logDelivery?.trigger();
751
702
  throw error;
752
703
  });
753
704
  };
@@ -766,6 +717,19 @@ export function createGroupPeer(params) {
766
717
  const pendingReplies = new Map();
767
718
  const inFlightBootstraps = new Set();
768
719
  const suppressedRequests = new Set();
720
+ const confirmationWaiters = new Map();
721
+ const commitOutcomes = createRecoveryCache((outcome)=>{
722
+ if (outcome.kind === 'applied') outcome.key.fill(0);
723
+ });
724
+ const recordCommitOutcome = (position, outcome)=>{
725
+ if (commitOutcomes.get(position) != null) {
726
+ if (outcome.kind === 'applied') outcome.key.fill(0);
727
+ return;
728
+ }
729
+ commitOutcomes.set(position, outcome, Date.now() + recoveryDeadlineMs);
730
+ };
731
+ const verdictCache = createRecoveryCache();
732
+ const verdictTimers = new Set();
769
733
  /**
770
734
  * Ledger-gather waiters, keyed by requestID. Called for EVERY reply, not just the first: a
771
735
  * responder whose ledger fails the head check withheld an entry, so the requester falls through
@@ -773,12 +737,73 @@ export function createGroupPeer(params) {
773
737
  */ const ledgerWaiters = new Map();
774
738
  const ledgerGatherFinishes = new Set();
775
739
  const pendingLedgerReplies = new Set();
740
+ const handleRecoveryConfirmRequest = (request)=>{
741
+ if (mls == null || rendezvousTopicID == null || disposed) return;
742
+ const port = mls;
743
+ const topicID = rendezvousTopicID;
744
+ void (async ()=>{
745
+ const verified = await port.verifyRecoveryRequest(request.request);
746
+ if (disposed || verified == null || verified.requestID !== request.requestID || normalizeDID(verified.requesterDID) === localDID) return;
747
+ const blocked = ()=>pendingRecovery != null && request.position >= pendingRecovery.position;
748
+ if (blocked()) return;
749
+ let record = commitOutcomes.get(request.position);
750
+ if (record == null) {
751
+ await ready;
752
+ if (disposed) return;
753
+ await runSerial(async ()=>{
754
+ if (disposed) return;
755
+ await replayJournal();
756
+ await reconcileCommits();
757
+ });
758
+ if (disposed || blocked()) return;
759
+ record = commitOutcomes.get(request.position);
760
+ }
761
+ if (record == null || record.value.commitDigest !== request.commitDigest) return;
762
+ const cacheKey = JSON.stringify([
763
+ verified.requesterDID,
764
+ request.requestID,
765
+ Array.from(request.request),
766
+ request.position,
767
+ request.commitDigest
768
+ ]);
769
+ let cached = verdictCache.get(cacheKey);
770
+ if (cached == null) {
771
+ const verdict = verdictForOutcome({
772
+ groupID: verified.groupID,
773
+ requestID: request.requestID,
774
+ position: request.position,
775
+ commitDigest: request.commitDigest
776
+ }, record.value);
777
+ const sealed = port.sealRecoveryVerdict(request.request, verdict).catch((error)=>{
778
+ if (verdictCache.get(cacheKey)?.value === sealed) verdictCache.delete(cacheKey);
779
+ throw error;
780
+ });
781
+ verdictCache.set(cacheKey, sealed, record.expiresAt);
782
+ cached = {
783
+ value: sealed,
784
+ expiresAt: record.expiresAt
785
+ };
786
+ }
787
+ const sealed = await cached.value;
788
+ const expiresAt = cached.expiresAt;
789
+ if (disposed || blocked() || expiresAt <= Date.now()) return;
790
+ const timer = setTimeout(()=>{
791
+ verdictTimers.delete(timer);
792
+ if (disposed || blocked() || expiresAt <= Date.now()) return;
793
+ void mux.publish({
794
+ topicID,
795
+ payload: encodeHandshakeFrame(HANDSHAKE_KIND.recoveryVerdict, encodeRecoveryVerdict(request.requestID, sealed))
796
+ }).catch(()=>{});
797
+ }, Math.max(0, Math.min(getReplyDelayMs(), recoveryTimeoutMs, expiresAt - Date.now())));
798
+ verdictTimers.add(timer);
799
+ })().catch(()=>{});
800
+ };
776
801
  // Responder: after a jitter delay, answer a recovery request with GroupInfo sealed to the
777
802
  // ephemeral key inside the signed request — unless another responder's reply has already
778
803
  // been observed (storm-collapse), in which case the scheduled reply is cancelled.
779
804
  const handleRecoveryRequest = (request)=>{
780
805
  const { requestID } = request;
781
- if (mls == null || rendezvousTopicID == null) return;
806
+ if (mls == null || rendezvousTopicID == null || pendingRecovery != null) return;
782
807
  if (suppressedRequests.has(requestID) || pendingReplies.has(requestID)) return;
783
808
  const port = mls;
784
809
  const topicID = rendezvousTopicID;
@@ -788,11 +813,12 @@ export function createGroupPeer(params) {
788
813
  try {
789
814
  // The port verifies the request and checks the requester's leaf against its own current
790
815
  // tree. A refused request raises, and this peer stays silent.
816
+ if (pendingRecovery != null) return;
791
817
  const groupInfo = await port.sealGroupInfo(request.request);
792
818
  // Same window as `handleLedgerRequest`'s guard: a timer that fired before dispose is
793
819
  // gone from `pendingReplies` by the time the clear sweep runs, and is then an await
794
820
  // away from here. Silent, for the same reason.
795
- if (disposed) return;
821
+ if (disposed || pendingRecovery != null) return;
796
822
  // Mailbox class, deliberately: a rendezvous frame must never move the commit topic's
797
823
  // head, and its reader — the requester — subscribed before it asked.
798
824
  await mux.publish({
@@ -880,69 +906,80 @@ export function createGroupPeer(params) {
880
906
  const handleLedgerReply = (reply)=>{
881
907
  ledgerWaiters.get(reply.requestID)?.(reply.sealed);
882
908
  };
883
- /**
884
- * THE ONE PATH THE HANDLE RATCHETS ON, and the invariant it holds: a handle does not ratchet
885
- * past an epoch until that epoch's frames are read and its anchor is taken. Both are one-way
886
- * doors — after the advance those frames are ciphertext forever, and that epoch's secret can
887
- * never be exported again.
888
- *
889
- * A seam, not a rule: the peer ratchets in four far-apart places (applied from the log, authored
890
- * by this peer, adopted from the journal on restart, and a rejoin), each free to uphold half of
891
- * this or none of it. Routing them all through here means the fifth site cannot get it wrong.
892
- * `advance` does the ratcheting and nothing else; everything around it is this function's.
893
- *
894
- * The ROSTER DIFF decides the rotation — see {@link anchor} for why. The before-read is
895
- * unconditional, since whether the diff will be needed is not knowable until the advance has
896
- * already destroyed the answer. `rotatesAnyway` is the one thing no diff can see: an
897
- * external-commit rejoin by a member the roster still holds replaces that member's leaf and
898
- * moves no DID, yet must rotate all the same (see {@link anchor}).
899
- *
900
- * The anchor is captured from the port's POST-advance handle — the epoch every member lands on
901
- * by making this same advance — which is what makes it agreed rather than local.
902
- */ const advanceHandle = async (port, advance, rotatesAnyway = ()=>false, appliedEpochs)=>{
903
- // Read this epoch's app frames BEFORE the advance that leaves it — the last moment they can
904
- // be read, since the advance ratchets the handle on and takes this epoch's key material with
905
- // it. Per frame-epoch, not per rotation: a segment spanning five epochs is dispensed five
906
- // times off the one pull.
907
- await appLane.deliver();
909
+ /** Read the departing epoch's frames and persist its rotation record before ratcheting. */ const advanceHandle = async (params)=>{
910
+ const { port, ratchet, identity, floorPosition } = params;
911
+ await resolveAnchorRotation({
912
+ port
913
+ });
908
914
  assertLive();
909
- // Normalized at this ingress so an MLS-recovered form flip between the two reads (never a
910
- // real membership change) does not read as one — see {@link detectRosterChange}.
911
- const rosterBefore = (await port.rosterEntries()).map((e)=>normalizeDID(e.did));
915
+ const pending = anchorPending;
916
+ const retry = pending?.advance === identity.advance;
917
+ const confirmedRecovery = identity.recovery === true && anchorRecoveryPending;
918
+ if (anchorRecoveryPending && !confirmedRecovery || anchorPending != null && !retry && !confirmedRecovery) {
919
+ throw new RecoveryRequiredError('an earlier anchor rotation is unresolved');
920
+ }
921
+ if (!confirmedRecovery) await appLane.deliver();
912
922
  assertLive();
923
+ const rosterBefore = retry && pending != null ? pending.rosterBefore : (await port.rosterEntries()).map((entry)=>normalizeDID(entry.did));
913
924
  const epochBefore = await port.readEpoch();
914
925
  assertLive();
915
- sealBarrier = new Promise((resolve)=>{
926
+ const record = retry && pending != null ? pending : {
927
+ epochBefore,
928
+ epochAfter: identity.epochAfter,
929
+ rosterBefore,
930
+ forced: identity.forced,
931
+ advance: identity.advance
932
+ };
933
+ await anchorStore?.save({
934
+ anchor,
935
+ pending: record
936
+ });
937
+ assertLive();
938
+ anchorPending = record;
939
+ if (sealBarrier == null) sealBarrier = new Promise((resolve)=>{
916
940
  releaseSealBarrier = resolve;
917
941
  });
918
- try {
919
- const advanced = await advance();
920
- const epochs = appliedEpochs?.(advanced);
921
- const actualBefore = epochs?.epochBefore ?? epochBefore;
922
- const epochAfter = epochs?.epochAfter ?? await port.readEpoch();
923
- // GATED ON THE HANDLE ACTUALLY RATCHETING: a roster diff alone is not evidence that it did. A
924
- // commit that REMOVES this member does not advance its handle (there is no epoch to move to,
925
- // since the commit's path excludes the dropped leaf), yet real MLS still applies proposals to
926
- // the tree — so the roster comes back WITHOUT this member at an epoch that did not move.
927
- // (Measured against ts-mls: `processMessage` returns without throwing, epoch stays,
928
- // `listMembers()` has lost the leaf.) Undiscriminated, that reads as a rotation.
929
- //
930
- // An ungated capture would clear the segment buffer while the handle still holds its epoch,
931
- // dropping frames that can still be opened.
932
- const ratcheted = epochAfter !== actualBefore;
933
- if (ratcheted && (detectRosterChange(rosterBefore, (await port.rosterEntries()).map((e)=>normalizeDID(e.did))) || rotatesAnyway(advanced))) {
934
- await captureAnchor();
942
+ const observe = async ()=>{
943
+ const epoch = await port.readEpoch();
944
+ const roster = (await port.rosterEntries()).map((entry)=>normalizeDID(entry.did));
945
+ if (rosterBefore.includes(localDID) && !roster.includes(localDID)) {
946
+ locallyRemoved = true;
947
+ logDelivery?.removed();
935
948
  }
949
+ if (epoch === identity.epochAfter && epoch !== record.epochBefore && floorPosition != null) floor = {
950
+ epoch,
951
+ position: floorPosition,
952
+ covered: true
953
+ };
954
+ };
955
+ try {
956
+ const advanced = await ratchet();
957
+ if (floorPosition != null) await saveCommitCursor(floorPosition);
958
+ await observe();
959
+ await resolveAnchorRotation({
960
+ port,
961
+ knownUnlanded: true,
962
+ landed: true
963
+ });
964
+ if (confirmedRecovery && anchorPending == null) anchorRecoveryPending = false;
936
965
  return advanced;
937
966
  } catch (error) {
938
- if (await port.readEpoch() !== epochBefore && sealBarrier != null) {
967
+ try {
968
+ await observe();
969
+ await resolveAnchorRotation({
970
+ port
971
+ });
972
+ } catch {
973
+ // The record keeps the exact epoch available for the next repair.
974
+ }
975
+ if (anchorPending != null) {
939
976
  sealError = new Error('app anchor unavailable after failed epoch advance', {
940
977
  cause: error
941
978
  });
942
979
  }
943
980
  throw error;
944
981
  } finally{
945
- finishSealBarrier();
982
+ if (anchorPending == null && !anchorRecoveryPending) finishSealBarrier();
946
983
  }
947
984
  };
948
985
  /**
@@ -964,15 +1001,25 @@ export function createGroupPeer(params) {
964
1001
  * `own-unmerged` stops early and takes no tip; `ahead` steps over its frame and drains to the
965
1002
  * end, so it DOES record one — the `stranded` flag, not a withheld tip, then stops `commit()`.
966
1003
  */ const walkCommits = async (port, topicID)=>{
1004
+ if (anchorRecoveryPending) return false;
967
1005
  let advancedEpoch = false;
1006
+ const started = logDelivery?.beginWalk() ?? 0;
1007
+ let covered = true;
968
1008
  // The tip from the SAME reply whose frames were processed, so it can never run ahead of them.
969
1009
  const takeHead = (head)=>{
970
1010
  commitLogHead = head == null ? null : asLogPosition(head);
1011
+ if (covered && !stranded && floor.covered) {
1012
+ if (!advancedEpoch) floor = {
1013
+ ...floor,
1014
+ position: reconciledHead
1015
+ };
1016
+ logDelivery?.certify(floor.epoch, started);
1017
+ }
971
1018
  };
972
1019
  while(true){
973
1020
  if (disposed) return false;
974
1021
  const pageAfter = reconciledHead;
975
- const result = await mux.fetchTopic({
1022
+ const result = checkedFetchResult(await mux.fetchTopic({
976
1023
  topicID,
977
1024
  // From the cursor. With no cursor (fresh member, trimmed backlog, just rejoined) read
978
1025
  // from the OLDEST retained frame — seeding from the topic's `head` would be a guess.
@@ -980,8 +1027,33 @@ export function createGroupPeer(params) {
980
1027
  after: reconciledHead
981
1028
  } : {},
982
1029
  limit: COMMIT_FETCH_LIMIT
983
- });
1030
+ }));
984
1031
  if (disposed) return false;
1032
+ const gap = result.gap || result.messages.length === 0 && result.head != null && pageAfter != null && result.head > pageAfter;
1033
+ if (pageAfter == null) {
1034
+ covered = false;
1035
+ floor = {
1036
+ ...floor,
1037
+ covered: false
1038
+ };
1039
+ } else if (gap) {
1040
+ floor = {
1041
+ ...floor,
1042
+ covered: false
1043
+ };
1044
+ stranded = true;
1045
+ healRequested = true;
1046
+ await persistStrand();
1047
+ observeStrand({
1048
+ position: pageAfter,
1049
+ commitDigest: null,
1050
+ localEpoch: await port.readEpoch(),
1051
+ claimedEpoch: null,
1052
+ kind: 'retention-gap',
1053
+ confidence: 'claimed'
1054
+ });
1055
+ return advancedEpoch;
1056
+ }
985
1057
  // A short page may carry a one-shot fork reveal below the cursor. Only a full page loops.
986
1058
  if (result.messages.length === COMMIT_FETCH_LIMIT) {
987
1059
  assertForwardPage(pageAfter, result.messages);
@@ -1002,7 +1074,7 @@ export function createGroupPeer(params) {
1002
1074
  try {
1003
1075
  frame = decodeHandshakeFrame(message.payload);
1004
1076
  } catch {
1005
- reconciledHead = position; // malformed: dropped, and the cursor still steps over it
1077
+ await saveCommitCursor(position); // malformed: dropped, and the cursor still steps over it
1006
1078
  continue;
1007
1079
  }
1008
1080
  // A wire version this build does not know, settled BEFORE the kind byte: nothing behind
@@ -1023,12 +1095,12 @@ export function createGroupPeer(params) {
1023
1095
  appliedByEpoch
1024
1096
  }
1025
1097
  });
1026
- reconciledHead = position;
1098
+ if (unreadable.row === 'ahead') stranded = true;
1099
+ await saveCommitCursor(position);
1027
1100
  // Do what the classifier said, not what this branch assumes: it answers `ahead` today,
1028
1101
  // and any other answer just steps over the frame, matching the bare advance above.
1029
1102
  if (unreadable.row === 'ahead') {
1030
1103
  healRequested = true;
1031
- stranded = true;
1032
1104
  observeStrand({
1033
1105
  position,
1034
1106
  commitDigest: null,
@@ -1041,7 +1113,7 @@ export function createGroupPeer(params) {
1041
1113
  continue;
1042
1114
  }
1043
1115
  if (frame.kind !== HANDSHAKE_KIND.commit) {
1044
- reconciledHead = position; // the commit lane carries commits, and nothing else
1116
+ await saveCommitCursor(position); // the commit lane carries commits, and nothing else
1045
1117
  continue;
1046
1118
  }
1047
1119
  // Split the frame into the commit and the sealed blob of bodies it enacts. Reads bytes,
@@ -1067,11 +1139,11 @@ export function createGroupPeer(params) {
1067
1139
  appliedByEpoch
1068
1140
  }
1069
1141
  });
1070
- reconciledHead = position;
1142
+ if (unreadable.row === 'ahead') stranded = true;
1143
+ await saveCommitCursor(position);
1071
1144
  // The classifier's answer, not this branch's assumption — as above.
1072
1145
  if (unreadable.row === 'ahead') {
1073
1146
  healRequested = true;
1074
- stranded = true;
1075
1147
  observeStrand({
1076
1148
  position,
1077
1149
  commitDigest: null,
@@ -1085,13 +1157,14 @@ export function createGroupPeer(params) {
1085
1157
  }
1086
1158
  // Too short, or a commit length running past the end: genuinely not a frame, and
1087
1159
  // nothing a future build would have written. Dropped, and the cursor steps over it.
1088
- reconciledHead = position;
1160
+ await saveCommitCursor(position);
1089
1161
  continue;
1090
1162
  }
1091
1163
  // Identify the commit by its own bytes, for the fork check — the COMMIT, not the frame:
1092
1164
  // the sealed blob is derived and re-sealing is legal, so a frame-wide digest would fork
1093
1165
  // the group on a legitimate re-seal.
1094
1166
  const commitDigest = digestAppliedCommit(commitFrame.commit);
1167
+ if (pendingRecovery?.position === position && pendingRecovery.commitDigest === commitDigest) return advancedEpoch;
1095
1168
  // The commit's OWN epoch and committer, from the commit's own bytes. Never
1096
1169
  // `message.senderDID` — the hub's word about who handed it over, and the hub is not
1097
1170
  // trusted: it could stamp every recipient's own DID onto one poison frame and make the
@@ -1124,6 +1197,7 @@ export function createGroupPeer(params) {
1124
1197
  // so the drain stops here and it heals.
1125
1198
  healRequested = true;
1126
1199
  stranded = true;
1200
+ await persistStrand();
1127
1201
  observeStrand({
1128
1202
  position,
1129
1203
  commitDigest,
@@ -1137,9 +1211,9 @@ export function createGroupPeer(params) {
1137
1211
  if (disposition.row === 'ahead') {
1138
1212
  // The group advanced at an epoch this peer did not. Step over the frame — the heal
1139
1213
  // repairs this, not a re-read — and ask for one.
1140
- reconciledHead = position;
1141
- healRequested = true;
1142
1214
  stranded = true;
1215
+ await saveCommitCursor(position);
1216
+ healRequested = true;
1143
1217
  observeStrand({
1144
1218
  position,
1145
1219
  commitDigest,
@@ -1154,16 +1228,20 @@ export function createGroupPeer(params) {
1154
1228
  // A frame from an epoch below this peer's, with no record for it or a record naming
1155
1229
  // this same commit. Not a fork, not poison, not the port's business — its blob is never
1156
1230
  // touched.
1157
- reconciledHead = position;
1231
+ await saveCommitCursor(position);
1158
1232
  break;
1159
1233
  }
1160
1234
  if (disposition.row === 'fork') {
1235
+ if (header?.external && disposition.branch !== 'losing' && !stranded) recordCommitOutcome(position, {
1236
+ commitDigest,
1237
+ kind: 'superseded'
1238
+ });
1161
1239
  // Two commits at one epoch. The lower-sequenceID branch wins; the loser rejoins onto it
1162
1240
  // (a heal). The winner just steps over the frame.
1163
- reconciledHead = position;
1241
+ if (disposition.branch === 'losing') stranded = true;
1242
+ await saveCommitCursor(position);
1164
1243
  if (disposition.branch === 'losing') {
1165
1244
  healRequested = true;
1166
- stranded = true;
1167
1245
  observeStrand({
1168
1246
  position,
1169
1247
  commitDigest,
@@ -1176,7 +1254,7 @@ export function createGroupPeer(params) {
1176
1254
  break;
1177
1255
  }
1178
1256
  if (disposition.row === 'poison') {
1179
- reconciledHead = position; // not a commit at all: stepped over, and never retried
1257
+ await saveCommitCursor(position); // not a commit at all: stepped over, and never retried
1180
1258
  break;
1181
1259
  }
1182
1260
  // Framed at this peer's epoch, by somebody else: a frame it can apply. Everything below is
@@ -1187,27 +1265,45 @@ export function createGroupPeer(params) {
1187
1265
  try {
1188
1266
  // Through the seam, like every other site that ratchets the handle: it reads this
1189
1267
  // epoch's app frames ahead of the apply and takes the anchor if the roster moved.
1190
- applied = await advanceHandle(port, async ()=>{
1191
- if (disposed) {
1192
- return {
1193
- advanced: false,
1194
- epochBefore: framedEpoch,
1195
- epochAfter: framedEpoch
1196
- };
1197
- }
1198
- return port.processCommit(commitFrame.commit, {
1199
- senderDID: message.senderDID,
1200
- // The resolver, not the bodies: the blob opens only if the port asks for entries
1201
- // this commit names, and only for a commit it applies — framed at this peer's
1202
- // epoch, the epoch the blob is sealed under, making body delivery atomic with the
1203
- // commit. Called from INSIDE the apply, so the open must not touch the handle's
1204
- // ratchet: `openEntries` reads only the epoch's exporter secret and is pure.
1205
- resolveLedgerEntries: createLedgerEntryResolver(commitFrame.sealedEntries, crypto.openEntries)
1206
- });
1207
- }, // A REJOIN rotates the anchor too, from a member the roster diff cannot see: an
1208
- // external commit by a member the roster still holds leaves every DID where it was.
1209
- // Only an APPLIED commit says anything about the group.
1210
- (result)=>result.advanced && header?.external === true, (result)=>result);
1268
+ applied = await advanceHandle({
1269
+ port,
1270
+ ratchet: async ()=>{
1271
+ if (disposed) {
1272
+ return {
1273
+ advanced: false,
1274
+ epochBefore: framedEpoch,
1275
+ epochAfter: framedEpoch
1276
+ };
1277
+ }
1278
+ const result = await port.processCommit(commitFrame.commit, {
1279
+ senderDID: message.senderDID,
1280
+ // The resolver, not the bodies: the blob opens only if the port asks for entries
1281
+ // this commit names, and only for a commit it applies — framed at this peer's
1282
+ // epoch, the epoch the blob is sealed under, making body delivery atomic with the
1283
+ // commit. Called from INSIDE the apply, so the open must not touch the handle's
1284
+ // ratchet: `openEntries` reads only the epoch's exporter secret and is pure.
1285
+ resolveLedgerEntries: createLedgerEntryResolver(commitFrame.sealedEntries, crypto.openEntries)
1286
+ });
1287
+ if (header?.external && result.advanced && !stranded) {
1288
+ const derived = await port.confirmationKey(position, commitDigest);
1289
+ recordCommitOutcome(position, {
1290
+ kind: 'applied',
1291
+ commitDigest,
1292
+ ...derived
1293
+ });
1294
+ }
1295
+ return result;
1296
+ },
1297
+ // A REJOIN rotates the anchor too, from a member the roster diff cannot see: an
1298
+ // external commit by a member the roster still holds leaves every DID where it was.
1299
+ // Only an APPLIED commit says anything about the group.
1300
+ identity: {
1301
+ epochAfter: (header?.epoch ?? framedEpoch) + 1,
1302
+ forced: header?.external === true,
1303
+ advance: commitDigest
1304
+ },
1305
+ floorPosition: position
1306
+ });
1211
1307
  } catch (error) {
1212
1308
  if (disposed) return false;
1213
1309
  if (!isMissingLedgerEntries(error)) {
@@ -1215,6 +1311,16 @@ export function createGroupPeer(params) {
1215
1311
  // a retry, and this is not an outcome it can name.
1216
1312
  throw error;
1217
1313
  }
1314
+ if (await port.readEpoch() !== framedEpoch) {
1315
+ await resolveAnchorRotation({
1316
+ port
1317
+ });
1318
+ throw error;
1319
+ }
1320
+ await resolveAnchorRotation({
1321
+ port,
1322
+ knownUnlanded: true
1323
+ });
1218
1324
  // The commit names ledger entries whose bodies will not resolve. POISON: drop, advance,
1219
1325
  // do NOT heal. The bodies ride the commit sealed under its framed epoch, so a blob this
1220
1326
  // peer cannot open is one no member at this epoch can — nobody applies it, and the next
@@ -1224,7 +1330,7 @@ export function createGroupPeer(params) {
1224
1330
  // Retrying only delays that. The one case where this peer really is the broken one
1225
1331
  // announces itself later: the next commit is then framed AHEAD of this peer's, which
1226
1332
  // heals it.
1227
- reconciledHead = position;
1333
+ await saveCommitCursor(position);
1228
1334
  break;
1229
1335
  }
1230
1336
  if (disposed) return false;
@@ -1241,9 +1347,14 @@ export function createGroupPeer(params) {
1241
1347
  digest: commitDigest
1242
1348
  });
1243
1349
  }
1350
+ if (header?.external && !applied.advanced && !stranded) recordCommitOutcome(position, {
1351
+ kind: 'refused',
1352
+ commitDigest,
1353
+ reason: applied.refusal ?? 'invalid'
1354
+ });
1244
1355
  // `{ advanced: false }` here is the port REFUSING a well-formed commit at this peer's own
1245
1356
  // epoch from another member: poison on the same terms as an unresolvable one.
1246
- reconciledHead = position;
1357
+ await saveCommitCursor(position);
1247
1358
  break;
1248
1359
  }
1249
1360
  }
@@ -1268,6 +1379,11 @@ export function createGroupPeer(params) {
1268
1379
  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');
1269
1380
  }
1270
1381
  if (mls == null || commitTopicID == null) return false;
1382
+ if (!await mls.isLedgerComplete()) {
1383
+ armLedgerRetry();
1384
+ return false;
1385
+ }
1386
+ ledgerRetryBackoff = 1000;
1271
1387
  const epochBefore = await mls.readEpoch();
1272
1388
  if (disposed) return false;
1273
1389
  const anchorBefore = anchor;
@@ -1280,7 +1396,7 @@ export function createGroupPeer(params) {
1280
1396
  } catch (error) {
1281
1397
  if (disposed) return false;
1282
1398
  // A failed final drain can follow applied commits. Refresh the runtime before a retry.
1283
- if (inboxLane != null) {
1399
+ if (epochRuntime.hasInboxLane()) {
1284
1400
  const epochAfter = await mls.readEpoch();
1285
1401
  if (disposed) return false;
1286
1402
  if (epochAfter !== epochBefore || anchor !== anchorBefore) {
@@ -1360,6 +1476,11 @@ export function createGroupPeer(params) {
1360
1476
  handleLedgerRequest(decodeLedgerRequest(frame.payload));
1361
1477
  } else if (frame.kind === HANDSHAKE_KIND.ledgerReply) {
1362
1478
  handleLedgerReply(decodeLedgerReply(frame.payload));
1479
+ } else if (frame.kind === HANDSHAKE_KIND.recoveryConfirmRequest) {
1480
+ handleRecoveryConfirmRequest(decodeRecoveryConfirmRequest(frame.payload));
1481
+ } else if (frame.kind === HANDSHAKE_KIND.recoveryVerdict) {
1482
+ const verdict = decodeRecoveryVerdict(frame.payload);
1483
+ confirmationWaiters.get(verdict.requestID)?.receive(verdict.sealed);
1363
1484
  }
1364
1485
  } catch {
1365
1486
  // malformed payloads are dropped
@@ -1378,11 +1499,32 @@ export function createGroupPeer(params) {
1378
1499
  retention: commitLogRetentionSeconds
1379
1500
  });
1380
1501
  rendezvousUnsubscribe = mux.onInbound(rendezvousTopicID, onRendezvousMessage);
1502
+ if (anchorRecoveryPending) return;
1381
1503
  // Then seed the cursor by READING the log — commits published before this peer subscribed are
1382
1504
  // exactly the ones no push will bring it. A lane operation, so the journal replays AHEAD of
1383
1505
  // it. Neither step rebuilds the epoch — buildEpoch runs next.
1384
1506
  await runSerial(async ()=>{
1385
1507
  if (disposed) return;
1508
+ if (params.appOutbox != null) {
1509
+ const cursor = await params.appOutbox.getCommitCursor();
1510
+ if (cursor != null && cursor.epoch === await mls.readEpoch()) {
1511
+ durableCursor = cursor;
1512
+ if (cursor.position != null) {
1513
+ reconciledHead = asLogPosition(cursor.position);
1514
+ floor = {
1515
+ epoch: cursor.epoch,
1516
+ position: reconciledHead,
1517
+ covered: true
1518
+ };
1519
+ }
1520
+ if (cursor.stranded === true) {
1521
+ stranded = true;
1522
+ healRequested = true;
1523
+ }
1524
+ } else if (cursor != null) {
1525
+ await params.appOutbox.putCommitCursor(null);
1526
+ }
1527
+ }
1386
1528
  await replayJournal();
1387
1529
  if (disposed) return;
1388
1530
  // A peer restored with an incomplete ledger was killed between rejoining and bootstrapping.
@@ -1410,8 +1552,10 @@ export function createGroupPeer(params) {
1410
1552
  if (framedAt != null && epoch !== framedAt) {
1411
1553
  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.');
1412
1554
  }
1555
+ const payload = encodeHandshakeFrame(HANDSHAKE_KIND.commit, encodeCommitFrame(commit, sealedEntries));
1556
+ assertFrameFits(payload);
1413
1557
  return {
1414
- payload: encodeHandshakeFrame(HANDSHAKE_KIND.commit, encodeCommitFrame(commit, sealedEntries)),
1558
+ payload,
1415
1559
  epoch
1416
1560
  };
1417
1561
  };
@@ -1428,9 +1572,12 @@ export function createGroupPeer(params) {
1428
1572
  * to act on, and its action is to commit.
1429
1573
  */ const replayJournal = async ()=>{
1430
1574
  journalReplayed = true;
1575
+ if (anchorRecoveryPending) return false;
1431
1576
  if (mls == null || journal == null || commitTopicID == null) return false;
1432
1577
  const entry = await journal.get();
1433
1578
  if (disposed || entry == null) return false;
1579
+ if (entry.holdsLogSends === true) await settleLogSubmissions();
1580
+ if (disposed) return false;
1434
1581
  const adoptIfLive = async ()=>{
1435
1582
  if (disposed) return;
1436
1583
  await adoptJournalled(entry.journal);
@@ -1449,7 +1596,16 @@ export function createGroupPeer(params) {
1449
1596
  });
1450
1597
  // Through the seam: the adopt ratchets the handle, so this epoch's app frames are read
1451
1598
  // first and the anchor is taken if the journalled commit moved the roster.
1452
- await advanceHandle(mls, adoptIfLive);
1599
+ await advanceHandle({
1600
+ port: mls,
1601
+ ratchet: adoptIfLive,
1602
+ identity: {
1603
+ epochAfter: entry.epoch + 1,
1604
+ forced: false,
1605
+ advance: digestAppliedCommit(entry.commit)
1606
+ },
1607
+ floorPosition: accepted
1608
+ });
1453
1609
  if (disposed) return false;
1454
1610
  await journal.clear(entry.publishID);
1455
1611
  return true;
@@ -1513,7 +1669,16 @@ export function createGroupPeer(params) {
1513
1669
  sequenceID: accepted,
1514
1670
  digest: digestAppliedCommit(entry.commit)
1515
1671
  });
1516
- await advanceHandle(mls, adoptIfLive);
1672
+ await advanceHandle({
1673
+ port: mls,
1674
+ ratchet: adoptIfLive,
1675
+ identity: {
1676
+ epochAfter: entry.epoch + 1,
1677
+ forced: false,
1678
+ advance: digestAppliedCommit(entry.commit)
1679
+ },
1680
+ floorPosition: accepted
1681
+ });
1517
1682
  if (disposed) return false;
1518
1683
  await journal.clear(entry.publishID);
1519
1684
  return true;
@@ -1539,11 +1704,10 @@ export function createGroupPeer(params) {
1539
1704
  if (disposed || awaitingBootstrap == null) return;
1540
1705
  // Restore the subscription before gathering the ledger: responders may already have
1541
1706
  // rotated to the new app anchor. A failed repair remains pending for the next lane call.
1542
- if (rejoinAnchorNeedsCapture) {
1543
- await captureAnchor();
1544
- if (disposed) return;
1545
- rejoinAnchorNeedsCapture = false;
1546
- }
1707
+ if (mls != null) await resolveAnchorRotation({
1708
+ port: mls
1709
+ });
1710
+ if (disposed) return;
1547
1711
  if (rejoinRuntimeNeedsBuild) {
1548
1712
  await rebuildEpoch();
1549
1713
  if (disposed) return;
@@ -1612,7 +1776,7 @@ export function createGroupPeer(params) {
1612
1776
  // responder seals to) — without the first any stranger gets the group's whole authority state
1613
1777
  // for one publish; without the second, so does the hub.
1614
1778
  const requestID = newPublishID();
1615
- const request = await port.createRecoveryRequest(requestID);
1779
+ const request = await port.createRecoveryRequest(requestID, Math.max(recoveryTimeoutMs, recoveryDeadlineMs));
1616
1780
  if (disposed) return false;
1617
1781
  return await new Promise((resolve)=>{
1618
1782
  let settled = false;
@@ -1670,9 +1834,21 @@ export function createGroupPeer(params) {
1670
1834
  /**
1671
1835
  * Commit to the group, rebasing until it lands or the deadline passes. Runs under the commit
1672
1836
  * mutex for its whole life, so `build()` never races another `build()` on this device.
1673
- */ const commit = async (build)=>{
1837
+ */ const commit = async (buildInput, options)=>{
1838
+ if (options?.holdLogSends === true) revokeHolds++;
1839
+ try {
1840
+ return await commitHeld(buildInput, options);
1841
+ } finally{
1842
+ if (options?.holdLogSends === true) revokeHolds--;
1843
+ logDelivery?.trigger();
1844
+ }
1845
+ };
1846
+ const commitHeld = async (buildInput, options)=>{
1847
+ const build = wrapCommitBuild(boundary, buildInput);
1674
1848
  await ready;
1675
1849
  assertLive();
1850
+ if (anchorRecoveryPending) throw new RecoveryRequiredError('commit: app anchor requires confirmed recovery');
1851
+ if (activeRecovery != null) await activeRecovery;
1676
1852
  if (mls == null || journal == null || commitTopicID == null) {
1677
1853
  throw new Error('commit: this peer has no MLS port, so it has no group to commit to');
1678
1854
  }
@@ -1710,12 +1886,12 @@ export function createGroupPeer(params) {
1710
1886
  // pull already took the live tip, so a commit here would win at an epoch it never caught
1711
1887
  // up to. Gating on `stranded`, not `healRequested`, is what survives a heal that found no
1712
1888
  // responder.
1713
- if (stranded) {
1889
+ if (stranded || anchorRecoveryPending) {
1714
1890
  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.');
1715
1891
  }
1716
1892
  // 2. Build against the host's CURRENT handle, adopting nothing. `build` closes over that
1717
1893
  // handle, so a rebased retry frames at the rebased epoch.
1718
- const pending = await build();
1894
+ const pending = wrapPendingCommit(boundary, await build());
1719
1895
  assertLive();
1720
1896
  // 3. Journal BEFORE publishing, durably: from here to the hub's answer is the crash
1721
1897
  // window, and the slot is the only thing that survives it.
@@ -1726,6 +1902,8 @@ export function createGroupPeer(params) {
1726
1902
  const expectedHead = commitLogHead;
1727
1903
  const { payload, epoch: framedEpoch } = await frameCommit(pending.commit, pending.bodies, crypto.frameEpoch(pending.commit));
1728
1904
  assertLive();
1905
+ if (options?.holdLogSends === true) await settleLogSubmissions();
1906
+ assertLive();
1729
1907
  await slot.put({
1730
1908
  publishID,
1731
1909
  expectedHead,
@@ -1735,7 +1913,10 @@ export function createGroupPeer(params) {
1735
1913
  commit: pending.commit,
1736
1914
  bodies: pending.bodies,
1737
1915
  kind: pending.kind,
1738
- journal: pending.journal
1916
+ journal: pending.journal,
1917
+ ...options?.holdLogSends === true ? {
1918
+ holdsLogSends: true
1919
+ } : {}
1739
1920
  });
1740
1921
  assertLive();
1741
1922
  // 4. Publish, conditional on the head the pull reached.
@@ -1794,7 +1975,16 @@ export function createGroupPeer(params) {
1794
1975
  // Remove keeps publishing to a topic the removed member still holds, and the author of an
1795
1976
  // Add sits on a topic the new member's handle cannot derive — silently, and no restart
1796
1977
  // heals it.
1797
- await advanceHandle(mls, ()=>pending.onAccepted());
1978
+ await advanceHandle({
1979
+ port: mls,
1980
+ ratchet: ()=>pending.onAccepted(),
1981
+ identity: {
1982
+ epochAfter: framedEpoch + 1,
1983
+ forced: false,
1984
+ advance: digestAppliedCommit(pending.commit)
1985
+ },
1986
+ floorPosition: accepted
1987
+ });
1798
1988
  assertLive();
1799
1989
  await slot.clear(publishID);
1800
1990
  assertLive();
@@ -1860,13 +2050,13 @@ export function createGroupPeer(params) {
1860
2050
  * anchored there would lose the compare-and-set forever. The external commit rebuilds this
1861
2051
  * peer's place from a GroupInfo that already describes the head, so racing there is right.
1862
2052
  */ const readCommitHead = async (topicID)=>{
1863
- const result = await mux.fetchTopic({
2053
+ const result = checkedFetchResult(await mux.fetchTopic({
1864
2054
  topicID,
1865
2055
  ...reconciledHead != null ? {
1866
2056
  after: reconciledHead
1867
2057
  } : {},
1868
2058
  limit: 1
1869
- });
2059
+ }));
1870
2060
  return result.head == null ? null : asLogPosition(result.head);
1871
2061
  };
1872
2062
  /**
@@ -1876,26 +2066,22 @@ export function createGroupPeer(params) {
1876
2066
  * host makes once this releases the lane.
1877
2067
  */ const attemptBody = async (trigger, generation, port, commits, rendezvous)=>{
1878
2068
  assertLive();
1879
- if (recoveryGeneration !== generation && !stranded && !healRequested) {
1880
- return {
1881
- advanced: true
1882
- };
1883
- }
1884
2069
  const attemptID = newPublishID();
1885
2070
  const base = {
1886
2071
  groupID: commits,
1887
2072
  attemptID,
1888
2073
  trigger
1889
2074
  };
1890
- queueMicrotask(()=>notifyHost(params.onRecovery, {
1891
- ...base,
1892
- phase: 'started'
1893
- }));
1894
- const failed = (reason)=>{
2075
+ const failed = (reason, details = {})=>{
2076
+ if (reason === 'renewal-required') renewalRequiredEpoch = crypto.epoch();
2077
+ if (reason === 'refused') refusalHeld = true;
2078
+ if (reason === 'renewal-required' || reason === 'refused') clearRecoveryRetry();
2079
+ if (reason === 'unconfirmed' || reason === 'no-responder' || reason === 'deadline') retryRecovery();
1895
2080
  emitRecovery({
1896
2081
  ...base,
1897
2082
  phase: 'failed',
1898
- reason
2083
+ reason,
2084
+ ...details
1899
2085
  });
1900
2086
  return {
1901
2087
  advanced: false
@@ -1904,166 +2090,295 @@ export function createGroupPeer(params) {
1904
2090
  try {
1905
2091
  // 0. Replay the journal ahead of everything, as every lane operation does: a peer holding a
1906
2092
  // commit whose fate it never learned settles that first, and may find nothing left to heal.
1907
- if (await replayJournal()) await rebuildEpoch();
1908
- assertLive();
1909
- if (await ensureLedger(Date.now() + recoveryTimeoutMs)) await finalizeBootstrap(port);
1910
- assertLive();
1911
- const deadline = Date.now() + recoveryDeadlineMs;
1912
- while(Date.now() < deadline){
1913
- // 1. Pull to the end. It may resolve the strand outright, and a heal it no longer needs
1914
- // must NOT run: the external commit would rotate the tree for the whole group. Rebuild
1915
- // if it moved the epoch, before anything is framed: the peer that lost a heal race
1916
- // applies the winner's commit HERE.
1917
- healRequested = false;
1918
- await reconcileCommits();
1919
- assertLive();
1920
- // 2. The head to race at, from the store's own reply.
1921
- const expectedHead = await readCommitHead(commits);
1922
- assertLive();
1923
- // 3. Mint a request and rendezvous for a sealed GroupInfo. Fresh request per attempt: the
1924
- // ephemeral key is minted with it, and a reply to an already-used request is unopenable.
1925
- const requestID = newPublishID();
1926
- const request = await port.createRecoveryRequest(requestID);
1927
- assertLive();
1928
- const outcome = await requestGroupInfo(request, requestID, rendezvous, deadline);
1929
- if (outcome.kind === 'disposed' || disposed) throw new PeerDisposedError('Peer is disposed');
1930
- if (outcome.kind === 'publish-failed') throw outcome.error;
1931
- if (outcome.kind === 'timeout') {
1932
- // Nobody answered. Heal REQUIRES another online member that can seal a GroupInfo;
1933
- // without one it cannot work. The peer stays degraded and asks again later.
1934
- return failed(outcome.atDeadline ? 'deadline' : 'no-responder');
1935
- }
1936
- // 4. Open it and BUILD the external commit, adopting nothing. Bytes this peer cannot open
1937
- // are a hub-injected or misaddressed reply: ask again.
1938
- let pending;
1939
- try {
1940
- pending = await port.applyRecovery(outcome.sealed, requestID);
1941
- } catch {
1942
- pending = null;
1943
- }
1944
- assertLive();
1945
- if (pending == null) continue;
1946
- // 5. The entries this peer holds, snapshotted BEFORE the rejoined handle replaces them —
1947
- // the last moment they can be read. Kept across a failed attempt, so a retry filters
1948
- // the same entries rather than snapshotting the empty ledger a failed bootstrap left.
1949
- inFlightEntries = [
1950
- ...new Set([
1951
- ...inFlightEntries ?? awaitingBootstrap?.entries ?? [],
1952
- ...await port.getLedger()
1953
- ])
1954
- ];
1955
- assertLive();
1956
- const inFlight = inFlightEntries;
1957
- // 6. Publish the external commit, compare-and-set at the head: it changes the ratchet
1958
- // tree, so it races like any commit.
1959
- const publishID = newPublishID();
1960
- const { payload } = await frameCommit(pending.commit, [], null);
1961
- assertLive();
1962
- let sequenceID;
1963
- try {
1964
- sequenceID = (await mux.publish({
1965
- topicID: commits,
1966
- payload,
1967
- retain: 'log',
1968
- expectedHead,
1969
- publishID
1970
- })).sequenceID;
1971
- } catch (error) {
1972
- if (disposed) throw new PeerDisposedError('Peer is disposed', {
1973
- cause: error
1974
- });
1975
- if (!isHeadMismatch(error)) throw error;
1976
- continue;
1977
- }
2093
+ const started = await runSerial(async ()=>{
2094
+ if (recoveryGeneration !== generation && !stranded && !healRequested) return false;
2095
+ queueMicrotask(()=>notifyHost((value)=>params.onRecovery?.(value), {
2096
+ ...base,
2097
+ phase: 'started'
2098
+ }));
2099
+ if (await replayJournal()) await rebuildEpoch();
1978
2100
  assertLive();
1979
- // 7. Accepted: the group has this peer's new leaf. Adopt the rejoined handle — the only
1980
- // place it may be adopted. Deliberately UNJOURNALLED: a crash here leaves an orphaned
1981
- // external commit that repairs itself — framed at the group's epoch, not this peer's,
1982
- // so the own-commit trigger stays quiet, the heal condition still holds, and `resync`
1983
- // later collects the leaf the orphan added.
1984
- const rejoinedAtEpoch = (await port.readCommitHeader(pending.commit))?.epoch;
2101
+ if (await ensureLedger(Date.now() + recoveryTimeoutMs)) await finalizeBootstrap(port);
1985
2102
  assertLive();
1986
- const epochBeforeRejoin = await port.readEpoch();
1987
- // Through the seam, like every other site that ratchets the handle — and it rotates
1988
- // ANYWAY: this is the rejoin, which no roster diff can see (see {@link anchor}). The
1989
- // anchor is the POST-commit epoch: the handle advances inside the seam and only then is
1990
- // the anchor captured, exactly where an applying member lands.
1991
- await advanceHandle(port, async ()=>{
2103
+ return true;
2104
+ });
2105
+ if (!started) return {
2106
+ advanced: true
2107
+ };
2108
+ const deadline = Date.now() + recoveryDeadlineMs;
2109
+ let prepared = false;
2110
+ while(Date.now() < deadline){
2111
+ const publication = await runSerial(async ()=>{
2112
+ if (await replayJournal()) await rebuildEpoch();
2113
+ // 1. Pull to the end. It may resolve the strand outright, and a heal it no longer needs
2114
+ // must NOT run: the external commit would rotate the tree for the whole group. Rebuild
2115
+ // if it moved the epoch, before anything is framed: the peer that lost a heal race
2116
+ // applies the winner's commit HERE.
2117
+ if (!anchorRecoveryPending) {
2118
+ healRequested = false;
2119
+ await reconcileCommits();
2120
+ }
2121
+ assertLive();
2122
+ // 2. The head to race at, from the store's own reply.
2123
+ const expectedHead = await readCommitHead(commits);
2124
+ assertLive();
2125
+ // 3. Mint a request and rendezvous for a sealed GroupInfo. Fresh request per attempt: the
2126
+ // ephemeral key is minted with it, and a reply to an already-used request is unopenable.
2127
+ if (!prepared) {
2128
+ prepared = true;
2129
+ if (await port.prepareRecovery() === 'renewal-required') return failed('renewal-required');
2130
+ assertLive();
2131
+ }
2132
+ const requestID = newPublishID();
2133
+ const request = await port.createRecoveryRequest(requestID, Math.max(0, deadline - Date.now()));
2134
+ assertLive();
2135
+ const outcome = await requestGroupInfo(request, requestID, rendezvous, deadline);
2136
+ if (outcome.kind === 'disposed' || disposed) throw new PeerDisposedError('Peer is disposed');
2137
+ if (outcome.kind === 'publish-failed') throw outcome.error;
2138
+ if (outcome.kind === 'timeout') {
2139
+ // Nobody answered. Heal REQUIRES another online member that can seal a GroupInfo;
2140
+ // without one it cannot work. The peer stays degraded and asks again later.
2141
+ return failed(outcome.atDeadline ? 'deadline' : 'no-responder');
2142
+ }
2143
+ // 4. Open it and BUILD the external commit, adopting nothing. Bytes this peer cannot open
2144
+ // are a hub-injected or misaddressed reply: ask again.
2145
+ // The reply may include an advance that landed between the pull and the head read.
2146
+ await reconcileCommits();
2147
+ assertLive();
2148
+ let pending;
1992
2149
  try {
1993
- await pending.onAccepted();
1994
- } finally{
1995
- // The adapter may adopt the handle and then fail to persist it. Observe the
1996
- // ratchet itself: a pre-adoption failure leaves this snapshot with the retry.
1997
- if (await port.readEpoch() !== epochBeforeRejoin) {
1998
- awaitingBootstrap = {
1999
- attemptID,
2000
- trigger,
2001
- entries: inFlight
2002
- };
2003
- // Adoption enacted these bytes even if persistence rejected afterward.
2004
- if (rejoinedAtEpoch != null) {
2005
- appliedByEpoch.set(rejoinedAtEpoch, {
2006
- sequenceID,
2007
- digest: digestAppliedCommit(pending.commit)
2008
- });
2009
- }
2010
- stranded = false;
2011
- rejoinAnchorNeedsCapture = true;
2012
- rejoinRuntimeNeedsBuild = true;
2150
+ pending = await port.applyRecovery(outcome.sealed, requestID);
2151
+ if (pending != null && !('renewalRequired' in pending)) {
2152
+ pending = wrapPendingRecovery(boundary, pending);
2013
2153
  }
2154
+ } catch {
2155
+ pending = null;
2014
2156
  }
2015
- }, ()=>true);
2016
- rejoinAnchorNeedsCapture = false;
2017
- assertLive();
2018
- const accepted = asLogPosition(sequenceID);
2019
- reconciledHead = accepted;
2020
- commitLogHead = accepted;
2021
- healRequested = false;
2022
- // The one place the commit gate is released: the rejoin landed, so this peer's leaf is
2023
- // back in the tree and the stale-epoch fork it guards is closed. A bootstrap that still
2024
- // fails below is `commit()`'s own ledger-completeness check to handle.
2025
- await rebuildEpoch();
2026
- rejoinRuntimeNeedsBuild = false;
2027
- assertLive();
2028
- // 8. Bootstrap: REQUIRED, not a formality. Until it runs, the ledger is empty against a
2029
- // live head — every admin promoted since genesis is invisible and the next commit is
2030
- // rejected. Failure here is a persistent degraded state, NOT a heal.
2031
- if (!await ensureLedger(deadline)) {
2032
2157
  assertLive();
2033
- awaitingBootstrap = {
2034
- attemptID,
2035
- trigger,
2036
- entries: inFlight
2158
+ if (pending == null) return null;
2159
+ if ('renewalRequired' in pending) return failed('renewal-required');
2160
+ // 5. The entries this peer holds, snapshotted BEFORE the rejoined handle replaces them —
2161
+ // the last moment they can be read. Kept across a failed attempt, so a retry filters
2162
+ // the same entries rather than snapshotting the empty ledger a failed bootstrap left.
2163
+ inFlightEntries = [
2164
+ ...new Set([
2165
+ ...inFlightEntries ?? awaitingBootstrap?.entries ?? [],
2166
+ ...await port.getLedger(),
2167
+ ...anchorRecoveryPending ? (await journal?.get())?.bodies ?? [] : []
2168
+ ])
2169
+ ];
2170
+ assertLive();
2171
+ const inFlight = inFlightEntries;
2172
+ // 6. Publish the external commit, compare-and-set at the head: it changes the ratchet
2173
+ // tree, so it races like any commit.
2174
+ const publishID = newPublishID();
2175
+ const epochBeforeRejoin = await port.readEpoch();
2176
+ const headBeforeRejoin = reconciledHead;
2177
+ const { payload } = await frameCommit(pending.commit, [], null);
2178
+ assertLive();
2179
+ let sequenceID;
2180
+ try {
2181
+ sequenceID = (await mux.publish({
2182
+ topicID: commits,
2183
+ payload,
2184
+ retain: 'log',
2185
+ expectedHead,
2186
+ publishID
2187
+ })).sequenceID;
2188
+ } catch (error) {
2189
+ if (disposed) throw new PeerDisposedError('Peer is disposed', {
2190
+ cause: error
2191
+ });
2192
+ if (!isHeadMismatch(error)) throw error;
2193
+ // Lost the race — the likely outcome. DISCARD THE GROUPINFO, not merely the commit: it
2194
+ // describes a tree the winning commit already changed, so a commit rebuilt from it is
2195
+ // one no member at the new epoch can apply. Re-request and rebuild from a fresh one.
2196
+ return null;
2197
+ }
2198
+ assertLive();
2199
+ const commitDigest = digestAppliedCommit(pending.commit);
2200
+ pendingRecovery = {
2201
+ position: sequenceID,
2202
+ commitDigest,
2203
+ pending
2037
2204
  };
2038
- healRequested = true;
2039
- bootstrapHealRequested = true;
2040
- return failed('bootstrap-failed');
2041
- }
2042
- assertLive();
2043
- // 9. Re-enact by MEMBERSHIP, never by the failure that brought this peer here: keep only
2044
- // entries the group's ledger does NOT hold. An entry it DOES hold was enacted for
2045
- // everyone, and appending it again puts it at the END of the log where the fold is
2046
- // last-write-wins — it would win, silently reverting whatever a later admin wrote over
2047
- // the same subject.
2048
- const held = new Set(await port.getLedger());
2205
+ const key = await pending.confirmationKey(sequenceID, commitDigest);
2206
+ const verified = await port.verifyRecoveryRequest(request);
2207
+ if (verified == null) throw new Error('The recovery request did not verify');
2208
+ return {
2209
+ pending,
2210
+ sequenceID,
2211
+ commitDigest,
2212
+ key,
2213
+ requestID,
2214
+ request,
2215
+ groupID: verified.groupID,
2216
+ epochBeforeRejoin,
2217
+ headBeforeRejoin,
2218
+ inFlight
2219
+ };
2220
+ });
2221
+ if (publication == null) continue;
2222
+ if ('advanced' in publication) return publication;
2223
+ const { pending, sequenceID, commitDigest, key, requestID, request, groupID, epochBeforeRejoin, headBeforeRejoin, inFlight } = publication;
2224
+ const confirmation = await waitForRecoveryConfirmation({
2225
+ port,
2226
+ pending,
2227
+ groupID,
2228
+ requestID,
2229
+ position: sequenceID,
2230
+ commitDigest,
2231
+ key,
2232
+ deadline,
2233
+ timeoutMs: recoveryTimeoutMs,
2234
+ waiters: confirmationWaiters,
2235
+ send: ()=>mux.publish({
2236
+ topicID: rendezvous,
2237
+ payload: encodeHandshakeFrame(HANDSHAKE_KIND.recoveryConfirmRequest, encodeRecoveryConfirmRequest({
2238
+ requestID,
2239
+ request,
2240
+ position: sequenceID,
2241
+ commitDigest
2242
+ }))
2243
+ })
2244
+ });
2049
2245
  assertLive();
2050
- const reenact = inFlight.filter((token)=>!held.has(token));
2051
- inFlightEntries = null;
2052
- awaitingBootstrap = null;
2053
- bootstrapHealRequested = false;
2054
- if (reenact.length > 0) pendingReenact = [
2055
- ...pendingReenact,
2056
- ...reenact
2057
- ];
2058
- recoveryGeneration += 1;
2059
- closeEpisode();
2060
- emitRecovery({
2061
- ...base,
2062
- phase: 'succeeded'
2246
+ if (confirmation.kind !== 'confirmed') {
2247
+ if (confirmation.kind === 'refused' && [
2248
+ 'binding',
2249
+ 'lapse',
2250
+ 'floor'
2251
+ ].includes(confirmation.refusal)) {
2252
+ pending.markBindingUnusable();
2253
+ pendingRecovery = null;
2254
+ return failed('renewal-required');
2255
+ }
2256
+ pendingRecovery = null;
2257
+ if (confirmation.kind === 'superseded') continue;
2258
+ if (confirmation.kind === 'refused') {
2259
+ return failed('refused', {
2260
+ refusal: confirmation.refusal,
2261
+ responder: confirmation.responder
2262
+ });
2263
+ }
2264
+ if (confirmation.kind === 'error') throw confirmation.error;
2265
+ if (confirmation.kind === 'disposed') throw new PeerDisposedError('Peer is disposed');
2266
+ return failed('unconfirmed', {
2267
+ advisory: confirmation.advisory
2268
+ });
2269
+ }
2270
+ return await runSerial(async ()=>{
2271
+ if (await port.readEpoch() !== epochBeforeRejoin || reconciledHead !== headBeforeRejoin || !anchorRecoveryPending && journal != null && await journal.get() != null || anchorPending != null && !anchorRecoveryPending) {
2272
+ pendingRecovery = null;
2273
+ return failed('unconfirmed', {
2274
+ advisory: []
2275
+ });
2276
+ }
2277
+ // Keep the confirmed adoption across ambiguous host failures for the next lane operation.
2278
+ const rejoinedAtEpoch = (await port.readCommitHeader(pending.commit))?.epoch;
2279
+ assertLive();
2280
+ retryRecoveryAdoption = async ()=>{
2281
+ // Through the seam, like every other site that ratchets the handle — and it rotates
2282
+ // ANYWAY: this is the rejoin, which no roster diff can see (see {@link anchor}). The
2283
+ // anchor is the POST-commit epoch: the handle advances inside the seam and only then is
2284
+ // the anchor captured, exactly where an applying member lands.
2285
+ await advanceHandle({
2286
+ port,
2287
+ ratchet: async ()=>{
2288
+ let accepted = false;
2289
+ try {
2290
+ await pending.onAccepted();
2291
+ accepted = true;
2292
+ } finally{
2293
+ // A callback can throw after replacing the handle. Observe the ratchet so
2294
+ // bootstrap survives it, while a pre-adoption failure keeps the pending retry.
2295
+ // A rejoin from a losing branch can land on its old epoch number, so a resolved
2296
+ // adoption counts even when the number did not move.
2297
+ if (accepted || await port.readEpoch() !== epochBeforeRejoin) {
2298
+ awaitingBootstrap = {
2299
+ attemptID,
2300
+ trigger,
2301
+ entries: inFlight
2302
+ };
2303
+ // Adoption enacted these bytes even if persistence rejected afterward.
2304
+ if (rejoinedAtEpoch != null) {
2305
+ appliedByEpoch.set(rejoinedAtEpoch, {
2306
+ sequenceID,
2307
+ digest: digestAppliedCommit(pending.commit)
2308
+ });
2309
+ }
2310
+ stranded = false;
2311
+ rejoinRuntimeNeedsBuild = true;
2312
+ }
2313
+ }
2314
+ },
2315
+ identity: {
2316
+ epochAfter: pending.epoch,
2317
+ forced: true,
2318
+ advance: digestAppliedCommit(pending.commit),
2319
+ recovery: true
2320
+ },
2321
+ floorPosition: asLogPosition(sequenceID)
2322
+ });
2323
+ assertLive();
2324
+ const accepted = asLogPosition(sequenceID);
2325
+ reconciledHead = accepted;
2326
+ commitLogHead = accepted;
2327
+ const deferred = await journal?.get();
2328
+ if (deferred != null) await journal?.clear(deferred.publishID);
2329
+ healRequested = false;
2330
+ // The one place the commit gate is released: the rejoin landed, so this peer's leaf is
2331
+ // back in the tree and the stale-epoch fork it guards is closed. A bootstrap that still
2332
+ // fails below is `commit()`'s own ledger-completeness check to handle.
2333
+ await rebuildEpoch();
2334
+ rejoinRuntimeNeedsBuild = false;
2335
+ assertLive();
2336
+ pendingRecovery = null;
2337
+ retryRecoveryAdoption = null;
2338
+ };
2339
+ await retryRecoveryAdoption();
2340
+ // 8. Bootstrap: REQUIRED, not a formality. Until it runs, the ledger is empty against a
2341
+ // live head — every admin promoted since genesis is invisible and the next commit is
2342
+ // rejected. Failure here is a persistent degraded state, NOT a heal.
2343
+ if (!await ensureLedger(deadline)) {
2344
+ assertLive();
2345
+ awaitingBootstrap = {
2346
+ attemptID,
2347
+ trigger,
2348
+ entries: inFlight
2349
+ };
2350
+ healRequested = true;
2351
+ bootstrapHealRequested = true;
2352
+ return failed('bootstrap-failed');
2353
+ }
2354
+ assertLive();
2355
+ // 9. Re-enact by MEMBERSHIP, never by the failure that brought this peer here: keep only
2356
+ // entries the group's ledger does NOT hold. An entry it DOES hold was enacted for
2357
+ // everyone, and appending it again puts it at the END of the log where the fold is
2358
+ // last-write-wins — it would win, silently reverting whatever a later admin wrote over
2359
+ // the same subject.
2360
+ const held = new Set(await port.getLedger());
2361
+ assertLive();
2362
+ const reenact = inFlight.filter((token)=>!held.has(token));
2363
+ inFlightEntries = null;
2364
+ awaitingBootstrap = null;
2365
+ bootstrapHealRequested = false;
2366
+ if (reenact.length > 0) pendingReenact = [
2367
+ ...pendingReenact,
2368
+ ...reenact
2369
+ ];
2370
+ recoveryGeneration += 1;
2371
+ clearRecoveryRetry();
2372
+ recoveryBackoff = 1000;
2373
+ closeEpisode();
2374
+ emitRecovery({
2375
+ ...base,
2376
+ phase: 'succeeded'
2377
+ });
2378
+ return {
2379
+ advanced: true
2380
+ };
2063
2381
  });
2064
- return {
2065
- advanced: true
2066
- };
2067
2382
  }
2068
2383
  return failed('deadline');
2069
2384
  } catch (error) {
@@ -2085,9 +2400,13 @@ export function createGroupPeer(params) {
2085
2400
  }
2086
2401
  };
2087
2402
  const runRecovery = (trigger)=>{
2403
+ if (trigger === 'automatic' && (renewalHeld() || refusalHeld)) return Promise.resolve({
2404
+ advanced: false
2405
+ });
2088
2406
  if (activeRecovery != null) return activeRecovery;
2089
2407
  const generation = recoveryGeneration;
2090
- const attempt = (async ()=>{
2408
+ let attempt;
2409
+ attempt = (async ()=>{
2091
2410
  await ready;
2092
2411
  assertLive();
2093
2412
  if (mls == null || commitTopicID == null || rendezvousTopicID == null) {
@@ -2098,15 +2417,13 @@ export function createGroupPeer(params) {
2098
2417
  const port = mls;
2099
2418
  const commits = commitTopicID;
2100
2419
  const rendezvous = rendezvousTopicID;
2101
- return runSerial(async ()=>{
2102
- try {
2103
- return await attemptBody(trigger, generation, port, commits, rendezvous);
2104
- } finally{
2105
- // The body and its mutex hold are finished before runSerial flushes terminal
2106
- // notices. A synchronous observer retry must not join this settled attempt.
2107
- if (activeRecovery === attempt) activeRecovery = null;
2108
- }
2109
- });
2420
+ try {
2421
+ return await attemptBody(trigger, generation, port, commits, rendezvous);
2422
+ } finally{
2423
+ if (retryRecoveryAdoption == null) pendingRecovery = null;
2424
+ if (activeRecovery === attempt) activeRecovery = null;
2425
+ flushHostOutbox();
2426
+ }
2110
2427
  })();
2111
2428
  activeRecovery = attempt;
2112
2429
  void attempt.then(()=>{
@@ -2117,6 +2434,9 @@ export function createGroupPeer(params) {
2117
2434
  return attempt;
2118
2435
  };
2119
2436
  const recover = async ()=>{
2437
+ renewalRequiredEpoch = null;
2438
+ refusalHeld = false;
2439
+ clearRecoveryRetry();
2120
2440
  const { advanced } = await runRecovery('consumer');
2121
2441
  const reenact = pendingReenact;
2122
2442
  pendingReenact = [];
@@ -2131,7 +2451,7 @@ export function createGroupPeer(params) {
2131
2451
  * flight absorbs any trigger raised while it runs: the frame that raised it is still in the log,
2132
2452
  * and the next pull raises it again if the heal did not settle it.
2133
2453
  */ const healIfRequested = async ()=>{
2134
- if (disposed || !healRequested || activeRecovery != null) return;
2454
+ if (disposed || !healRequested || activeRecovery != null || renewalHeld() || refusalHeld) return;
2135
2455
  healRequested = false;
2136
2456
  try {
2137
2457
  await runRecovery('automatic');
@@ -2181,10 +2501,16 @@ export function createGroupPeer(params) {
2181
2501
  // with no roster change yet must. A member booting over a handle it was just added to seeds
2182
2502
  // at its own add epoch — the same epoch every existing member rotates to on applying that
2183
2503
  // add, so the two agree with no exchange between them.
2504
+ await journal?.get();
2184
2505
  const stored = await anchorStore?.load();
2185
2506
  if (disposed) return;
2186
2507
  if (stored != null) {
2187
- anchor = stored;
2508
+ anchor = stored.anchor;
2509
+ anchorPending = stored.pending;
2510
+ if (mls != null) await resolveAnchorRotation({
2511
+ port: mls,
2512
+ initial: true
2513
+ });
2188
2514
  } else {
2189
2515
  await captureAnchor();
2190
2516
  }
@@ -2195,6 +2521,7 @@ export function createGroupPeer(params) {
2195
2521
  if (disposed) return;
2196
2522
  await buildEpoch();
2197
2523
  if (disposed) return;
2524
+ if (anchorRecoveryPending) return;
2198
2525
  // The seed pull precedes the app listeners. Read once more after registration to close
2199
2526
  // the publication gap; a failed read is retried on the same independent schedule.
2200
2527
  if (crypto.pending != null) {
@@ -2220,7 +2547,10 @@ export function createGroupPeer(params) {
2220
2547
  // The seed pull runs inside init, where the crash victim whose journal was lost meets its own
2221
2548
  // un-merged commit. Its heal waits for init to finish, since every lane operation (`recover()`
2222
2549
  // included) waits on `ready`.
2223
- void settled.then(()=>healIfRequested());
2550
+ void settled.then(()=>{
2551
+ logDelivery?.trigger();
2552
+ void healIfRequested();
2553
+ });
2224
2554
  const withReady = async (fn)=>{
2225
2555
  await ready;
2226
2556
  assertLive();
@@ -2256,7 +2586,21 @@ export function createGroupPeer(params) {
2256
2586
  const protocolMethod = (name)=>{
2257
2587
  const key = String(name);
2258
2588
  return {
2259
- dispatch: (prc, config)=>withReady(()=>surfaceFor(key).dispatch(prc, config)),
2589
+ dispatch: async (prc, config)=>{
2590
+ assertLive();
2591
+ const protocol = protocols[key];
2592
+ if (protocol == null) throw new Error(`Unknown protocol: ${key}`);
2593
+ if (appOutboxAcceptance != null && retentionOf(protocol, prc) === 'log') {
2594
+ await appOutboxAcceptance.accept({
2595
+ protocol: key,
2596
+ prc,
2597
+ data: encodeEventFrame(prc, config?.data ?? {})
2598
+ });
2599
+ logDelivery?.trigger();
2600
+ return;
2601
+ }
2602
+ return withReady(()=>surfaceFor(key).dispatch(prc, config));
2603
+ },
2260
2604
  request: (prc, config)=>withReady(()=>surfaceFor(key).request(prc, config)),
2261
2605
  gather: async (prc, config)=>{
2262
2606
  const outcome = await readyOrAbort(config?.signal);
@@ -2285,6 +2629,7 @@ export function createGroupPeer(params) {
2285
2629
  await ensureLedger(Date.now() + recoveryTimeoutMs);
2286
2630
  await reconcileCommits();
2287
2631
  });
2632
+ await healIfRequested();
2288
2633
  assertLive();
2289
2634
  },
2290
2635
  commit,
@@ -2313,13 +2658,23 @@ export function createGroupPeer(params) {
2313
2658
  // refused, so it cannot subscribe anything a normal retain would not have.
2314
2659
  mux.rearmRefusedTopics();
2315
2660
  },
2661
+ drained: ()=>{
2662
+ if (disposePromise == null) return Promise.reject(new Error('Call dispose() before drained()'));
2663
+ return boundary.drained(disposePromise);
2664
+ },
2316
2665
  dispose: ()=>{
2317
2666
  if (disposePromise != null) return disposePromise;
2318
2667
  disposed = true;
2668
+ appOutboxAcceptance?.close();
2669
+ logDelivery?.close();
2670
+ clearRecoveryRetry();
2671
+ boundary.close();
2319
2672
  abortPendingRestore?.();
2320
2673
  if (pendingRestoreTimer != null) clearTimeout(pendingRestoreTimer);
2321
2674
  appLane.dispose();
2322
2675
  if (appPullTimer != null) clearTimeout(appPullTimer);
2676
+ if (ledgerRetryTimer != null) clearTimeout(ledgerRetryTimer);
2677
+ ledgerRetryTimer = undefined;
2323
2678
  appPullTimer = undefined;
2324
2679
  // Synchronous and FIRST, before anything is awaited: a lane op that already passed its own
2325
2680
  // `assertLive` can be running inside `runSerial`, past the point this `dispose()` can reach
@@ -2332,6 +2687,11 @@ export function createGroupPeer(params) {
2332
2687
  for (const finish of [
2333
2688
  ...ledgerGatherFinishes
2334
2689
  ])finish();
2690
+ for (const waiter of confirmationWaiters.values())waiter.dispose();
2691
+ commitOutcomes.clear();
2692
+ verdictCache.clear();
2693
+ for (const timer of verdictTimers)clearTimeout(timer);
2694
+ verdictTimers.clear();
2335
2695
  disposePromise = (async ()=>{
2336
2696
  // Tear down even a peer whose init failed — it still holds a hub drain.
2337
2697
  // Initialization may be waiting on a host port that never answers. Disposal closes the
@@ -2382,7 +2742,7 @@ export function createGroupPeer(params) {
2382
2742
  } catch (error) {
2383
2743
  disposeErrors.push(error);
2384
2744
  }
2385
- inboxLane = undefined;
2745
+ epochRuntime.releaseInboxLane();
2386
2746
  if (disposeErrors.length === 1) throw disposeErrors[0];
2387
2747
  if (disposeErrors.length > 1) throw new AggregateError(disposeErrors, 'Peer dispose failed');
2388
2748
  })();