@kumiai/rpc 0.9.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/app-lane.js CHANGED
@@ -1,27 +1,44 @@
1
1
  import { normalizeDID } from '@kokuin/token';
2
- import { fromUTF, toUTF } from '@sozai/codec';
3
- import { asLogPosition } from './cursor.js';
2
+ import { sha256 } from '@noble/hashes/sha2.js';
3
+ import { fromUTF, toB64U, toUTF } from '@sozai/codec';
4
+ import { decodeAppAAD, encodeAppAAD } from './app-aad.js';
5
+ import { isAppFrameStorageError, isFrameAhead } from './crypto.js';
6
+ import { asLogPosition, assertForwardPage } from './cursor.js';
4
7
  import { retentionOf } from './protocol.js';
5
8
  import { protocolTopic } from './topic.js';
6
9
  const APP_FETCH_LIMIT = 100;
10
+ function frameID(topicID, bytes) {
11
+ const topic = fromUTF(topicID);
12
+ const input = new Uint8Array(4 + topic.length + bytes.length);
13
+ new DataView(input.buffer).setUint32(0, topic.length, false);
14
+ input.set(topic, 4);
15
+ input.set(bytes, 4 + topic.length);
16
+ return toB64U(sha256(input));
17
+ }
7
18
  /**
8
19
  * Take one frame into the buffer at its place in the log, or reconcile it with the copy already
9
20
  * there. The ONE way a frame enters the buffer, from either deliverer.
10
21
  *
11
- * A POSITION IS TAKEN ONCE: the live lane is pushed a frame and the pull reads it back out of the
12
- * log, so a second entry for a position already held is a second delivery of one message — the
13
- * duplicate the cursor exists to make impossible. A repeat is a reconcile, never an append, and
14
- * only ever marks a frame DONE, never undoes it: `sealed: null` says the live lane had this frame
15
- * at its seal epoch, and a pull reading it back afterwards must not redeliver it.
22
+ * A POSITION IS TAKEN ONCE. In durable mode, pending wins over every duplicate and sealed wins
23
+ * over done. Without durable delivery, a live done observation still wins as before.
16
24
  *
17
25
  * Kept in log order by insertion, not append, since the two deliverers do not arrive in one order:
18
26
  * a pull runs from behind the live stream and returns frames the pushes already brought.
19
- */ function takeAppFrame(frames, incoming) {
27
+ */ function takeAppFrame(frames, incoming, durable) {
20
28
  let index = frames.length;
21
29
  while(index > 0 && frames[index - 1].position > incoming.position)index -= 1;
22
30
  const existing = index > 0 ? frames[index - 1] : undefined;
23
31
  if (existing?.position === incoming.position) {
24
- if (incoming.sealed == null) existing.sealed = null;
32
+ if (!durable) {
33
+ if (incoming.sealed.state === 'done') existing.sealed = incoming.sealed;
34
+ return;
35
+ }
36
+ if (existing.sealed.state === 'pending') return;
37
+ if (incoming.sealed.state === 'pending') {
38
+ existing.sealed = incoming.sealed;
39
+ } else if (existing.sealed.state === 'done') {
40
+ existing.sealed = incoming.sealed;
41
+ }
25
42
  return;
26
43
  }
27
44
  frames.splice(index, 0, incoming);
@@ -34,12 +51,31 @@ const APP_FETCH_LIMIT = 100;
34
51
  * outside it may touch the buffer. That rule was a comment when this state sat in the peer's own
35
52
  * closure; here it is the module boundary.
36
53
  */ export function createAppLane(params) {
37
- const { mux, crypto, localDID, protocols, eventHandlers: appEventHandlers, retentionSeconds, appCursorStore, onAppWindowPruned, anchor, groupID, justifiedEpochCeiling } = params;
54
+ const { mux, crypto, localDID, protocols, eventHandlers: appEventHandlers, retentionSeconds, appCursorStore, onAppWindowPruned, onAppDeliveryStalled, scheduleDelivery = (start)=>start(), anchor, groupID } = params;
38
55
  /**
39
56
  * The current SEGMENT's retained app frames, per protocol, in log order. A segment is the run of
40
57
  * epochs between two roster changes — exactly the run one app topic spans — so it is pulled once
41
58
  * (below) and dispensed epoch by epoch as the commit walk passes through it.
42
59
  */ let segment = new Map();
60
+ const pendingRecords = [];
61
+ const blockingFrames = new Map();
62
+ let disposed = false;
63
+ const reportedUnknown = new Set();
64
+ const reportUnknown = (record)=>{
65
+ if (disposed || protocols[record.frame.protocol] != null || reportedUnknown.has(record.frame.id)) return;
66
+ const group = groupID();
67
+ if (group == null) return;
68
+ reportedUnknown.add(record.frame.id);
69
+ onAppDeliveryStalled?.({
70
+ groupID: group,
71
+ protocol: record.frame.protocol,
72
+ topicID: record.frame.topicID,
73
+ position: record.frame.position,
74
+ error: new Error(`unknown app protocol: ${record.frame.protocol}`),
75
+ reason: 'unknown-protocol'
76
+ });
77
+ };
78
+ const workers = new Map();
43
79
  /** The current segment's read positions, per protocol. See {@link AppCursor}. */ let cursors = new Map();
44
80
  /**
45
81
  * Log-class app frames the LIVE lane was pushed and the buffer has not taken in yet, per
@@ -159,7 +195,7 @@ const APP_FETCH_LIMIT = 100;
159
195
  // A push landed on a topic this peer has since rotated off names a position in a log this
160
196
  // segment's cursor knows nothing about. Dropped, not merged.
161
197
  for (const push of staged.get(name) ?? []){
162
- if (push.topicID === topicID) takeAppFrame(frames, push.frame);
198
+ if (push.topicID === topicID) takeAppFrame(frames, push.frame, crypto.pending != null);
163
199
  }
164
200
  staged.delete(name);
165
201
  // The gap question is asked on the segment's FIRST pull only: it compares where this peer
@@ -175,6 +211,7 @@ const APP_FETCH_LIMIT = 100;
175
211
  } : {},
176
212
  limit: APP_FETCH_LIMIT
177
213
  });
214
+ assertForwardPage(after, result.messages);
178
215
  if (!reported) {
179
216
  // `result.oldest` is where the hub's retention begins, and only the FIRST page's reply is
180
217
  // asked: every later page reports the same floor, and a gap is one gap.
@@ -183,19 +220,27 @@ const APP_FETCH_LIMIT = 100;
183
220
  }
184
221
  for (const message of result.messages){
185
222
  const position = asLogPosition(message.sequenceID);
223
+ const restored = pendingRecords.find((record)=>record.frame.protocol === name && record.frame.topicID === topicID && record.frame.position === position);
186
224
  takeAppFrame(frames, {
187
225
  position,
188
- sealed: message.payload
189
- });
226
+ sealed: restored == null ? {
227
+ state: 'sealed',
228
+ bytes: message.payload
229
+ } : {
230
+ state: 'pending',
231
+ id: restored.frame.id
232
+ }
233
+ }, crypto.pending != null);
190
234
  after = position;
191
235
  }
192
236
  cursor.fetched = after;
193
237
  if (result.messages.length < APP_FETCH_LIMIT) break;
194
238
  }
195
239
  };
196
- // NOT `allSettled`: a failed pull must reach the caller, whose walk stops on it rather than
197
- // stepping over an epoch whose frames were never read.
198
- await Promise.all(Object.keys(protocols).map(loadOne));
240
+ // Keep the app-lane mutex until every fetch has stopped mutating its buffer.
241
+ const results = await Promise.allSettled(Object.keys(protocols).map(loadOne));
242
+ const failure = results.find((result)=>result.status === 'rejected');
243
+ if (failure?.status === 'rejected') throw failure.reason;
199
244
  };
200
245
  /**
201
246
  * Move this topic's read position over the frames the drain has finished with, and persist it.
@@ -211,7 +256,7 @@ const APP_FETCH_LIMIT = 100;
211
256
  if (cursor == null) return;
212
257
  let passed = 0;
213
258
  let position = null;
214
- while(passed < frames.length && frames[passed].sealed == null){
259
+ while(passed < frames.length && frames[passed].sealed.state === 'done'){
215
260
  position = frames[passed].position;
216
261
  passed += 1;
217
262
  }
@@ -220,6 +265,100 @@ const APP_FETCH_LIMIT = 100;
220
265
  cursor.position = position;
221
266
  await appCursorStore?.save(cursor.topicID, position);
222
267
  };
268
+ const orderedRecords = (name)=>pendingRecords.filter((record)=>record.frame.protocol === name).sort((a, b)=>a.frame.segment - b.frame.segment || a.frame.position.localeCompare(b.frame.position));
269
+ const blockedByEarlierSealed = (record)=>{
270
+ const cursor = cursors.get(record.frame.protocol);
271
+ if (cursor?.topicID !== record.frame.topicID) return false;
272
+ return (segment.get(record.frame.protocol) ?? []).some((frame)=>frame.position < record.frame.position && frame.sealed.state === 'sealed');
273
+ };
274
+ const finishRecord = async (record)=>{
275
+ if (disposed) return;
276
+ await crypto.pending?.complete(record.frame.id);
277
+ if (disposed) return;
278
+ await runAppLane(async ()=>{
279
+ const index = pendingRecords.findIndex((item)=>item.frame.id === record.frame.id);
280
+ if (index !== -1) pendingRecords.splice(index, 1);
281
+ const cursor = cursors.get(record.frame.protocol);
282
+ if (cursor?.topicID !== record.frame.topicID) return;
283
+ const frames = segment.get(record.frame.protocol);
284
+ if (frames == null) return;
285
+ const buffered = frames.find((frame)=>frame.position === record.frame.position);
286
+ if (buffered?.sealed.state === 'pending' && buffered.sealed.id === record.frame.id) {
287
+ buffered.sealed = {
288
+ state: 'done'
289
+ };
290
+ }
291
+ await advanceCursor(record.frame.protocol, frames);
292
+ });
293
+ };
294
+ const deliverRecord = async (record)=>{
295
+ if (disposed) return;
296
+ if (protocols[record.frame.protocol] == null) return;
297
+ let message;
298
+ try {
299
+ message = JSON.parse(toUTF(record.payload));
300
+ } catch {
301
+ // A malformed durable frame is acknowledged without reaching the host.
302
+ }
303
+ const prc = message?.payload?.prc;
304
+ const protocol = protocols[record.frame.protocol];
305
+ const events = appEventHandlers.get(record.frame.protocol);
306
+ if (normalizeDID(record.senderDID) !== localDID && message?.payload?.typ === 'event' && typeof prc === 'string' && protocol != null && retentionOf(protocol, prc) === 'log' && events != null) {
307
+ const event = {
308
+ data: message.payload.data ?? {},
309
+ senderDID: normalizeDID(record.senderDID),
310
+ frame: record.frame
311
+ };
312
+ await events.emit(prc, event);
313
+ }
314
+ if (!disposed) await finishRecord(record);
315
+ };
316
+ const scheduleWorker = (name, delay = 0)=>{
317
+ if (disposed || crypto.pending == null) return;
318
+ let worker = workers.get(name);
319
+ if (worker == null) {
320
+ worker = {
321
+ running: false,
322
+ requested: false,
323
+ backoff: 1000
324
+ };
325
+ workers.set(name, worker);
326
+ }
327
+ worker.requested = true;
328
+ if (worker.running || worker.timer != null) return;
329
+ worker.timer = setTimeout(()=>{
330
+ if (disposed) return;
331
+ worker.timer = undefined;
332
+ worker.running = true;
333
+ worker.requested = false;
334
+ void (async ()=>{
335
+ let failed = false;
336
+ try {
337
+ while(!disposed){
338
+ const record = orderedRecords(name)[0];
339
+ if (record == null || protocols[record.frame.protocol] == null || await runAppLane(async ()=>blockedByEarlierSealed(record))) break;
340
+ if (disposed) break;
341
+ try {
342
+ await deliverRecord(record);
343
+ worker.backoff = 1000;
344
+ } catch {
345
+ failed = true;
346
+ break;
347
+ }
348
+ }
349
+ } finally{
350
+ worker.running = false;
351
+ if (failed) {
352
+ const retry = worker.backoff;
353
+ worker.backoff = Math.min(worker.backoff * 2, 60_000);
354
+ scheduleWorker(name, retry);
355
+ } else if (worker.requested) {
356
+ scheduleWorker(name);
357
+ }
358
+ }
359
+ })();
360
+ }, delay);
361
+ };
223
362
  /**
224
363
  * Take the staged pushes into the buffer and move the durable cursor over them, off the back of
225
364
  * live traffic alone — a peer that is online and walks no commit still has to keep its position,
@@ -248,34 +387,33 @@ const APP_FETCH_LIMIT = 100;
248
387
  });
249
388
  };
250
389
  /**
251
- * Record a log-class frame the LIVE lane was pushed, at the moment it arrives.
390
+ * Record a log-class frame the LIVE lane was pushed, once the live open of it settles.
252
391
  *
253
392
  * THE OTHER DELIVERER TAKING THE SAME READ POSITION: before the push carried its own log
254
393
  * position there was nothing for the live path to write down, so the cursor sat behind every
255
394
  * frame an online peer had already been given and every re-pull read them all back.
256
395
  *
257
396
  * WHAT IS RECORDED IS DONE-NESS, NOT DELIVERY — the same thing here, since the transport that
258
- * carries this frame to the host unwraps with the same handle:
397
+ * carries this frame to the host unwraps with the same handle. The open's own outcome decides,
398
+ * never the epoch hint:
259
399
  *
260
- * - AT the handle's epoch: this is the live lane's one chance, now — whatever the outcome, the
261
- * frame is DONE (the drain's own paths deliver or drop exactly as the transport does).
262
- * - ABOVE it: ahead of the walk. The transport cannot open it, so its bytes are kept for the
263
- * drain to deliver once the walk reaches that epoch — whether the claim is justified is the
264
- * drain's question, asked with a network read this path must not make.
265
- * - BELOW it, or unreadable: dead. MLS ratchets forward, so no epoch this peer will ever hold
266
- * again opens those bytes.
267
- *
268
- * Read HERE, not at the merge: the handle moves under this mutex-free push loop, so the answer
269
- * is only true of the moment the frame arrived.
400
+ * - OPENED, or refused at the handle's epoch: the live lane's one chance, taken — DONE.
401
+ * - Refused as AHEAD ({@link FrameEpochError}): its bytes are kept for the drain to deliver
402
+ * once the walk reaches that epoch.
403
+ * - Refused as past, or unreadable: dead. MLS ratchets forward.
270
404
  *
271
405
  * A MAILBOX frame is skipped outright — nothing to advance over. The class travels with the push
272
406
  * because ephemeral and logged app traffic share one topic, and guessing from the topic would
273
407
  * move the cursor over frames the log does not contain.
274
- */ const note = (name, topicID, message)=>{
408
+ */ const note = (name, topicID, message, failure)=>{
275
409
  const position = message.logPosition;
276
410
  if (position == null) return;
277
- const sealedAt = crypto.frameEpoch(message.payload);
278
- const ahead = sealedAt != null && sealedAt > crypto.epoch();
411
+ if (crypto.pending != null) {
412
+ // Pushed positions are unauthenticated metadata. Only fetches may populate this buffer.
413
+ scheduleSync();
414
+ return;
415
+ }
416
+ const ahead = isFrameAhead(failure);
279
417
  let pushes = staged.get(name);
280
418
  if (pushes == null) {
281
419
  pushes = [];
@@ -285,56 +423,129 @@ const APP_FETCH_LIMIT = 100;
285
423
  topicID,
286
424
  frame: {
287
425
  position: asLogPosition(position),
288
- sealed: ahead ? message.payload : null
426
+ sealed: ahead ? {
427
+ state: 'sealed',
428
+ bytes: message.payload
429
+ } : {
430
+ state: 'done'
431
+ }
289
432
  }
290
433
  });
291
434
  scheduleSync();
292
435
  };
293
436
  const drain = async ()=>{
294
437
  await loadSegment();
295
- // Read once per drain and only if a frame actually claims to be ahead: the log is a network
296
- // read, the honest buffer holds no such claim, and this handle's epoch does not move under a
297
- // single drain.
298
- let ceiling = null;
299
- const justifies = async (claim)=>{
300
- ceiling ??= await justifiedEpochCeiling();
301
- return claim <= ceiling;
302
- };
303
438
  for (const [name, frames] of segment){
304
439
  const events = appEventHandlers.get(name);
305
440
  const cursor = cursors.get(name);
306
- if (events == null || cursor == null || frames.length === 0) continue;
441
+ if (cursor == null || frames.length === 0 || events == null && crypto.pending == null) {
442
+ continue;
443
+ }
307
444
  for (const frame of frames){
308
- const sealed = frame.sealed;
309
- if (sealed == null) continue; // done on an earlier pass, and only holding its place
310
- const sealedAt = crypto.frameEpoch(sealed);
311
- if (sealedAt !== crypto.epoch()) {
312
- // Not sealed at the handle's current epoch. Ahead of the walk AND justified by the
313
- // commit log: keep its bytes and place. Otherwise — below the walk, an epoch no member
314
- // could have sealed at, or unreadable — it is dead, and dead is done.
315
- if (sealedAt != null && sealedAt > crypto.epoch() && await justifies(sealedAt)) continue;
316
- frame.sealed = null;
445
+ if (frame.sealed.state !== 'sealed') continue;
446
+ const sealed = frame.sealed.bytes;
447
+ // Unreadable bytes are dead. Past and future are the open's locked answer, below.
448
+ if (crypto.frameEpoch(sealed) == null) {
449
+ frame.sealed = {
450
+ state: 'done'
451
+ };
317
452
  continue;
318
453
  }
454
+ if (crypto.pending != null) {
455
+ const decoded = decodeAppAAD(crypto.frameAAD(sealed) ?? new Uint8Array());
456
+ if (decoded?.topicID !== cursor.topicID || decoded.intent !== 'log') {
457
+ frame.sealed = {
458
+ state: 'done'
459
+ };
460
+ continue;
461
+ }
462
+ }
463
+ const ref = crypto.pending == null ? undefined : {
464
+ id: frameID(cursor.topicID, sealed),
465
+ topicID: cursor.topicID,
466
+ protocol: name,
467
+ segment: anchor().epoch,
468
+ position: frame.position
469
+ };
319
470
  let opened;
320
471
  try {
321
472
  // `crypto.unwrap` always returns the full result — `senderDID` is REQUIRED — so there is
322
473
  // no bare-`Uint8Array` shortcut left to normalize away here. `expectedAAD` is bound to
323
474
  // the cursor's own topic, the authoritative answer to "what lane is this drain reading".
324
475
  opened = await crypto.unwrap(sealed, {
325
- expectedAAD: fromUTF(cursor.topicID)
476
+ expectedAAD: encodeAppAAD({
477
+ topicID: cursor.topicID,
478
+ intent: 'log'
479
+ }),
480
+ ...ref == null ? {} : {
481
+ frame: ref
482
+ }
326
483
  });
327
- } catch {
484
+ } catch (error) {
485
+ if (isFrameAhead(error)) {
486
+ // A future claim keeps its bytes and position even when the hub omits its commit.
487
+ if (crypto.pending != null) {
488
+ const key = `future\u0000${cursor.topicID}\u0000${frame.position}`;
489
+ if (blockingFrames.get(name) !== key) {
490
+ blockingFrames.set(name, key);
491
+ const group = groupID();
492
+ if (group != null) onAppDeliveryStalled?.({
493
+ groupID: group,
494
+ protocol: name,
495
+ topicID: cursor.topicID,
496
+ position: frame.position,
497
+ error: new Error(`frame claims future epoch ${error.frameEpoch}`),
498
+ reason: 'future-epoch'
499
+ });
500
+ }
501
+ }
502
+ continue;
503
+ }
504
+ if (crypto.pending != null && isAppFrameStorageError(error)) {
505
+ const key = `storage\u0000${cursor.topicID}\u0000${frame.position}`;
506
+ if (blockingFrames.get(name) !== key) {
507
+ blockingFrames.set(name, key);
508
+ const group = groupID();
509
+ if (group != null) {
510
+ onAppDeliveryStalled?.({
511
+ groupID: group,
512
+ protocol: name,
513
+ topicID: cursor.topicID,
514
+ position: frame.position,
515
+ error
516
+ });
517
+ }
518
+ }
519
+ throw error;
520
+ }
328
521
  // Claimed this epoch and the handle refused it — OR its AAD did not match this topic (a
329
522
  // wrong-topic frame, or a pre-upgrade empty-AAD frame). Either way, dead: the handle
330
523
  // never returns to this epoch and the topic binding never changes. Retained history from
331
524
  // before this bind existed is DELIBERATELY invalidated, not silently re-offered.
332
- frame.sealed = null;
525
+ frame.sealed = {
526
+ state: 'done'
527
+ };
528
+ continue;
529
+ }
530
+ if (ref != null) {
531
+ const record = {
532
+ frame: ref,
533
+ payload: opened.payload,
534
+ senderDID: opened.senderDID
535
+ };
536
+ frame.sealed = {
537
+ state: 'pending',
538
+ id: record.frame.id
539
+ };
540
+ pendingRecords.push(record);
333
541
  continue;
334
542
  }
335
543
  // Opened, so it is done whatever the payload turns out to be — every path below either
336
544
  // delivers it or drops it exactly as the live transport would.
337
- frame.sealed = null;
545
+ frame.sealed = {
546
+ state: 'done'
547
+ };
548
+ if (events == null) continue;
338
549
  // This `unwrap` is its own ingress — not fed by `peer.ts`'s normalized inbound path — so
339
550
  // the recovered sender is normalized HERE, once, before either use below: `localDID` (the
340
551
  // param above) is already normalized at peer construction, and the two must compare on
@@ -351,7 +562,9 @@ const APP_FETCH_LIMIT = 100;
351
562
  if (message.payload?.typ !== 'event' || typeof prc !== 'string') continue;
352
563
  // A retained frame naming an EPHEMERAL procedure was published `retain: 'log'` by a member
353
564
  // whose dispatch would never do that. Retention is the protocol's word, not the frame's.
354
- if (retentionOf(protocols[name], prc) !== 'log') continue;
565
+ const protocol = protocols[name];
566
+ if (protocol === undefined) continue;
567
+ if (retentionOf(protocol, prc) !== 'log') continue;
355
568
  try {
356
569
  // Same door as the live push: emit the retained frame's plaintext into the
357
570
  // per-protocol emitter the live bus is also built from. No listener → no-op.
@@ -368,16 +581,40 @@ const APP_FETCH_LIMIT = 100;
368
581
  }
369
582
  };
370
583
  return {
584
+ dropFrame: (topicID, position)=>runAppLane(async ()=>{
585
+ if (crypto.pending == null) throw new Error('durable app delivery is disabled');
586
+ const unknown = pendingRecords.find((record)=>protocols[record.frame.protocol] == null && record.frame.topicID === topicID && record.frame.position === position);
587
+ if (unknown != null) {
588
+ await crypto.pending.complete(unknown.frame.id);
589
+ pendingRecords.splice(pendingRecords.indexOf(unknown), 1);
590
+ return;
591
+ }
592
+ const entry = [
593
+ ...cursors.entries()
594
+ ].find(([, cursor])=>cursor.topicID === topicID);
595
+ if (entry == null) throw new Error('app frame is not buffered');
596
+ const [name] = entry;
597
+ const frames = segment.get(name);
598
+ const frame = frames?.find((item)=>item.position === position);
599
+ if (frames == null || frame == null) throw new Error('app frame is not buffered');
600
+ if (frame.sealed.state === 'pending') throw new Error('app frame is pending');
601
+ if (frame.sealed.state !== 'sealed') throw new Error('app frame is already done');
602
+ if (frames.some((item)=>item.position < position && item.sealed.state !== 'done')) {
603
+ throw new Error('an earlier pending or sealed frame blocks the durable cursor');
604
+ }
605
+ frame.sealed = {
606
+ state: 'done'
607
+ };
608
+ await advanceCursor(name, frames);
609
+ }),
371
610
  /**
372
611
  * MUST run BEFORE the apply, never after: once the commit applies the handle holds different
373
612
  * key material, and those bytes are ciphertext forever. Per-FRAME-EPOCH, not per-rotation:
374
613
  * every epoch inside a segment is dispensed as the walk passes through it.
375
614
  *
376
- * Which frames are this epoch's is read from their own cleartext (`crypto.frameEpoch`), not
377
- * found by trying every frame and catching, since `unwrap` throwing cannot distinguish "not my
378
- * epoch yet" from "never again". A FUTURE-epoch claim is bounded by
379
- * {@link AppLaneParams.justifiedEpochCeiling} for the same reason — unbounded, it would pin
380
- * the cursor behind it forever.
615
+ * Which frames are this epoch's is the open's own answer: `unwrap` refuses another epoch with
616
+ * `FrameEpochError` before decrypting, and only its "ahead" answer keeps a frame. A forged
617
+ * future-epoch claim can hold the cursor until an operator drops it.
381
618
  *
382
619
  * The buffer is walked whole, not stopped at the first frame that is not this epoch's, since
383
620
  * the front can still hold a frame from an epoch the handle already passed (a journal replay
@@ -398,12 +635,40 @@ const APP_FETCH_LIMIT = 100;
398
635
  * the ordered buffer mid-walk re-reads or steps over a frame, and a sync landing between
399
636
  * {@link advanceCursor}'s read of a done run and its splice silently drops frames.
400
637
  *
401
- * NO DEADLOCK against the peer's commit mutex: every call here is from inside `runSerial`,
402
- * taking the app lane second, and nothing inside it takes `runSerial` back — the one path that
403
- * could, a host handler re-entering from the delivery below, already deadlocks on `runSerial`
404
- * itself.
405
- */ deliver: ()=>runAppLane(drain),
638
+ * The peer starts workers after its commit operation releases; direct lanes start them here.
639
+ */ deliver: async ()=>{
640
+ try {
641
+ await runAppLane(drain);
642
+ } finally{
643
+ if (crypto.pending != null && !disposed) {
644
+ for (const record of pendingRecords)reportUnknown(record);
645
+ for (const name of new Set(pendingRecords.map((record)=>record.frame.protocol))){
646
+ scheduleDelivery(()=>scheduleWorker(name));
647
+ }
648
+ }
649
+ }
650
+ },
406
651
  note,
652
+ pendingRecords: ()=>[
653
+ ...pendingRecords
654
+ ],
655
+ restore: async (records)=>{
656
+ await runAppLane(async ()=>{
657
+ for (const record of records){
658
+ reportUnknown(record);
659
+ if (!pendingRecords.some((item)=>item.frame.id === record.frame.id)) {
660
+ pendingRecords.push(record);
661
+ }
662
+ }
663
+ pendingRecords.sort((a, b)=>a.frame.segment - b.frame.segment || a.frame.position.localeCompare(b.frame.position));
664
+ });
665
+ },
666
+ dispose: ()=>{
667
+ disposed = true;
668
+ for (const worker of workers.values()){
669
+ if (worker.timer != null) clearTimeout(worker.timer);
670
+ }
671
+ },
407
672
  reset: ()=>{
408
673
  segment = new Map();
409
674
  cursors = new Map();
@@ -74,6 +74,9 @@ const HEADER_BYTES = VERSION_BYTES + COMMIT_LENGTH_BYTES;
74
74
  throw new Error('commit frame is too short');
75
75
  }
76
76
  const version = frame[0];
77
+ if (version === undefined) {
78
+ throw new Error('commit frame is too short');
79
+ }
77
80
  if (version !== COMMIT_FRAME_VERSION) {
78
81
  throw new UnsupportedCommitFrameVersionError(version);
79
82
  }