@kumiai/rpc 0.9.1 → 0.10.1

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,45 @@
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';
7
+ import { notifyHost } from './host-notice.js';
4
8
  import { retentionOf } from './protocol.js';
5
9
  import { protocolTopic } from './topic.js';
6
10
  const APP_FETCH_LIMIT = 100;
11
+ function frameID(topicID, bytes) {
12
+ const topic = fromUTF(topicID);
13
+ const input = new Uint8Array(4 + topic.length + bytes.length);
14
+ new DataView(input.buffer).setUint32(0, topic.length, false);
15
+ input.set(topic, 4);
16
+ input.set(bytes, 4 + topic.length);
17
+ return toB64U(sha256(input));
18
+ }
7
19
  /**
8
20
  * Take one frame into the buffer at its place in the log, or reconcile it with the copy already
9
21
  * there. The ONE way a frame enters the buffer, from either deliverer.
10
22
  *
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.
23
+ * A POSITION IS TAKEN ONCE. In durable mode, pending wins over every duplicate and sealed wins
24
+ * over done. Without durable delivery, a live done observation still wins as before.
16
25
  *
17
26
  * Kept in log order by insertion, not append, since the two deliverers do not arrive in one order:
18
27
  * a pull runs from behind the live stream and returns frames the pushes already brought.
19
- */ function takeAppFrame(frames, incoming) {
28
+ */ function takeAppFrame(frames, incoming, durable) {
20
29
  let index = frames.length;
21
30
  while(index > 0 && frames[index - 1].position > incoming.position)index -= 1;
22
31
  const existing = index > 0 ? frames[index - 1] : undefined;
23
32
  if (existing?.position === incoming.position) {
24
- if (incoming.sealed == null) existing.sealed = null;
33
+ if (!durable) {
34
+ if (incoming.sealed.state === 'done') existing.sealed = incoming.sealed;
35
+ return;
36
+ }
37
+ if (existing.sealed.state === 'pending') return;
38
+ if (incoming.sealed.state === 'pending') {
39
+ existing.sealed = incoming.sealed;
40
+ } else if (existing.sealed.state === 'done') {
41
+ existing.sealed = incoming.sealed;
42
+ }
25
43
  return;
26
44
  }
27
45
  frames.splice(index, 0, incoming);
@@ -34,12 +52,78 @@ const APP_FETCH_LIMIT = 100;
34
52
  * outside it may touch the buffer. That rule was a comment when this state sat in the peer's own
35
53
  * closure; here it is the module boundary.
36
54
  */ export function createAppLane(params) {
37
- const { mux, crypto, localDID, protocols, eventHandlers: appEventHandlers, retentionSeconds, appCursorStore, onAppWindowPruned, anchor, groupID, justifiedEpochCeiling } = params;
55
+ const { mux, crypto, localDID, protocols, eventHandlers: appEventHandlers, retentionSeconds, appCursorStore, onAppWindowPruned, onAppDeliveryStalled, onAppDeliveryResumed, scheduleDelivery = (start)=>start(), anchor, groupID } = params;
38
56
  /**
39
57
  * The current SEGMENT's retained app frames, per protocol, in log order. A segment is the run of
40
58
  * epochs between two roster changes — exactly the run one app topic spans — so it is pulled once
41
59
  * (below) and dispensed epoch by epoch as the commit walk passes through it.
42
60
  */ let segment = new Map();
61
+ const pendingRecords = [];
62
+ const blockingFrames = new Map();
63
+ let disposed = false;
64
+ const reportedUnknown = new Map();
65
+ let pendingNotices;
66
+ const notifyAppHost = (callback, event)=>{
67
+ if (callback == null) return;
68
+ // A notice queued behind an in-flight save is dropped if the lane is disposed meanwhile.
69
+ const notify = ()=>{
70
+ if (!disposed) notifyHost(callback, event);
71
+ };
72
+ if (pendingNotices == null) notify();
73
+ else pendingNotices.push(notify);
74
+ };
75
+ const blockingKey = (topicID, position)=>`${topicID}\u0000${position}`;
76
+ const resumeBlocked = (topicID, position)=>{
77
+ const key = blockingKey(topicID, position);
78
+ const event = blockingFrames.get(key);
79
+ if (event == null || disposed) return;
80
+ blockingFrames.delete(key);
81
+ notifyAppHost(onAppDeliveryResumed, event);
82
+ };
83
+ const resumeUnknown = (record)=>{
84
+ const event = reportedUnknown.get(record.frame.id);
85
+ if (event == null || disposed) return;
86
+ reportedUnknown.delete(record.frame.id);
87
+ notifyAppHost(onAppDeliveryResumed, event);
88
+ };
89
+ const reportBlocked = (protocol, topicID, position, error, reason)=>{
90
+ const key = blockingKey(topicID, position);
91
+ if (disposed || onAppDeliveryStalled == null || blockingFrames.has(key)) return;
92
+ const group = groupID();
93
+ if (group == null) return;
94
+ const event = {
95
+ groupID: group,
96
+ protocol,
97
+ topicID,
98
+ position,
99
+ ...reason == null ? {} : {
100
+ reason
101
+ }
102
+ };
103
+ blockingFrames.set(key, event);
104
+ notifyAppHost(onAppDeliveryStalled, {
105
+ ...event,
106
+ error
107
+ });
108
+ };
109
+ const reportUnknown = (record)=>{
110
+ if (disposed || onAppDeliveryStalled == null || protocols[record.frame.protocol] != null || reportedUnknown.has(record.frame.id)) return;
111
+ const group = groupID();
112
+ if (group == null) return;
113
+ const event = {
114
+ groupID: group,
115
+ protocol: record.frame.protocol,
116
+ topicID: record.frame.topicID,
117
+ position: record.frame.position,
118
+ reason: 'unknown-protocol'
119
+ };
120
+ reportedUnknown.set(record.frame.id, event);
121
+ notifyAppHost(onAppDeliveryStalled, {
122
+ ...event,
123
+ error: new Error(`unknown app protocol: ${record.frame.protocol}`)
124
+ });
125
+ };
126
+ const workers = new Map();
43
127
  /** The current segment's read positions, per protocol. See {@link AppCursor}. */ let cursors = new Map();
44
128
  /**
45
129
  * Log-class app frames the LIVE lane was pushed and the buffer has not taken in yet, per
@@ -65,7 +149,18 @@ const APP_FETCH_LIMIT = 100;
65
149
  * and a push splicing it mid-iteration would step over frames.
66
150
  */ let tail = Promise.resolve();
67
151
  const runAppLane = (fn)=>{
68
- const op = tail.then(fn);
152
+ const op = tail.then(async ()=>{
153
+ const notices = [];
154
+ pendingNotices = notices;
155
+ try {
156
+ return await fn();
157
+ } finally{
158
+ // State and cursor writes settle before observers can re-enter this lane.
159
+ // A reentrant reset can append more notices to this batch.
160
+ for(let index = 0; index < notices.length; index++)notices[index]?.();
161
+ pendingNotices = undefined;
162
+ }
163
+ });
69
164
  tail = op.then(()=>{}, ()=>{});
70
165
  return op;
71
166
  };
@@ -159,7 +254,7 @@ const APP_FETCH_LIMIT = 100;
159
254
  // A push landed on a topic this peer has since rotated off names a position in a log this
160
255
  // segment's cursor knows nothing about. Dropped, not merged.
161
256
  for (const push of staged.get(name) ?? []){
162
- if (push.topicID === topicID) takeAppFrame(frames, push.frame);
257
+ if (push.topicID === topicID) takeAppFrame(frames, push.frame, crypto.pending != null);
163
258
  }
164
259
  staged.delete(name);
165
260
  // The gap question is asked on the segment's FIRST pull only: it compares where this peer
@@ -175,6 +270,7 @@ const APP_FETCH_LIMIT = 100;
175
270
  } : {},
176
271
  limit: APP_FETCH_LIMIT
177
272
  });
273
+ assertForwardPage(after, result.messages);
178
274
  if (!reported) {
179
275
  // `result.oldest` is where the hub's retention begins, and only the FIRST page's reply is
180
276
  // asked: every later page reports the same floor, and a gap is one gap.
@@ -183,19 +279,27 @@ const APP_FETCH_LIMIT = 100;
183
279
  }
184
280
  for (const message of result.messages){
185
281
  const position = asLogPosition(message.sequenceID);
282
+ const restored = pendingRecords.find((record)=>record.frame.protocol === name && record.frame.topicID === topicID && record.frame.position === position);
186
283
  takeAppFrame(frames, {
187
284
  position,
188
- sealed: message.payload
189
- });
285
+ sealed: restored == null ? {
286
+ state: 'sealed',
287
+ bytes: message.payload
288
+ } : {
289
+ state: 'pending',
290
+ id: restored.frame.id
291
+ }
292
+ }, crypto.pending != null);
190
293
  after = position;
191
294
  }
192
295
  cursor.fetched = after;
193
296
  if (result.messages.length < APP_FETCH_LIMIT) break;
194
297
  }
195
298
  };
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));
299
+ // Keep the app-lane mutex until every fetch has stopped mutating its buffer.
300
+ const results = await Promise.allSettled(Object.keys(protocols).map(loadOne));
301
+ const failure = results.find((result)=>result.status === 'rejected');
302
+ if (failure?.status === 'rejected') throw failure.reason;
199
303
  };
200
304
  /**
201
305
  * Move this topic's read position over the frames the drain has finished with, and persist it.
@@ -211,7 +315,7 @@ const APP_FETCH_LIMIT = 100;
211
315
  if (cursor == null) return;
212
316
  let passed = 0;
213
317
  let position = null;
214
- while(passed < frames.length && frames[passed].sealed == null){
318
+ while(passed < frames.length && frames[passed].sealed.state === 'done'){
215
319
  position = frames[passed].position;
216
320
  passed += 1;
217
321
  }
@@ -220,6 +324,126 @@ const APP_FETCH_LIMIT = 100;
220
324
  cursor.position = position;
221
325
  await appCursorStore?.save(cursor.topicID, position);
222
326
  };
327
+ 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));
328
+ const blockedByEarlierSealed = (record)=>{
329
+ const cursor = cursors.get(record.frame.protocol);
330
+ if (cursor?.topicID !== record.frame.topicID) return false;
331
+ return (segment.get(record.frame.protocol) ?? []).some((frame)=>frame.position < record.frame.position && frame.sealed.state === 'sealed');
332
+ };
333
+ const finishRecord = async (record)=>{
334
+ if (disposed) return;
335
+ await crypto.pending?.complete(record.frame.id);
336
+ if (disposed) return;
337
+ await runAppLane(async ()=>{
338
+ const index = pendingRecords.findIndex((item)=>item.frame.id === record.frame.id);
339
+ if (index !== -1) pendingRecords.splice(index, 1);
340
+ resumeBlocked(record.frame.topicID, record.frame.position);
341
+ resumeUnknown(record);
342
+ const cursor = cursors.get(record.frame.protocol);
343
+ if (cursor?.topicID !== record.frame.topicID) return;
344
+ const frames = segment.get(record.frame.protocol);
345
+ if (frames == null) return;
346
+ const buffered = frames.find((frame)=>frame.position === record.frame.position);
347
+ if (buffered?.sealed.state === 'pending' && buffered.sealed.id === record.frame.id) {
348
+ buffered.sealed = {
349
+ state: 'done'
350
+ };
351
+ }
352
+ await advanceCursor(record.frame.protocol, frames);
353
+ });
354
+ };
355
+ const deliverRecord = async (record)=>{
356
+ if (disposed) return;
357
+ if (protocols[record.frame.protocol] == null) return;
358
+ let message;
359
+ try {
360
+ message = JSON.parse(toUTF(record.payload));
361
+ } catch {
362
+ // A malformed durable frame is acknowledged without reaching the host.
363
+ }
364
+ const prc = message?.payload?.prc;
365
+ const protocol = protocols[record.frame.protocol];
366
+ const events = appEventHandlers.get(record.frame.protocol);
367
+ if (normalizeDID(record.senderDID) !== localDID && message?.payload?.typ === 'event' && typeof prc === 'string' && protocol != null && retentionOf(protocol, prc) === 'log' && events != null) {
368
+ const event = {
369
+ data: message.payload.data ?? {},
370
+ senderDID: normalizeDID(record.senderDID),
371
+ frame: record.frame
372
+ };
373
+ await events.emit(prc, event);
374
+ }
375
+ if (!disposed) await finishRecord(record);
376
+ };
377
+ const scheduleWorker = (name, delay = 0)=>{
378
+ if (disposed || crypto.pending == null) return;
379
+ let worker = workers.get(name);
380
+ if (worker == null) {
381
+ worker = {
382
+ running: false,
383
+ requested: false,
384
+ retryNow: false,
385
+ backoff: 1000
386
+ };
387
+ workers.set(name, worker);
388
+ }
389
+ worker.requested = true;
390
+ if (worker.running || worker.timer != null) return;
391
+ worker.timer = setTimeout(()=>{
392
+ if (disposed) return;
393
+ worker.timer = undefined;
394
+ worker.running = true;
395
+ worker.requested = false;
396
+ void (async ()=>{
397
+ let failed = false;
398
+ try {
399
+ while(!disposed){
400
+ const record = orderedRecords(name)[0];
401
+ if (record == null || protocols[record.frame.protocol] == null || await runAppLane(async ()=>blockedByEarlierSealed(record))) break;
402
+ if (disposed) break;
403
+ try {
404
+ await deliverRecord(record);
405
+ worker.backoff = 1000;
406
+ } catch {
407
+ failed = true;
408
+ break;
409
+ }
410
+ }
411
+ } finally{
412
+ worker.running = false;
413
+ if (worker.retryNow) {
414
+ worker.retryNow = false;
415
+ scheduleWorker(name);
416
+ } else if (failed) {
417
+ const retry = worker.backoff;
418
+ worker.backoff = Math.min(worker.backoff * 2, 60_000);
419
+ scheduleWorker(name, retry);
420
+ } else if (worker.requested) {
421
+ scheduleWorker(name);
422
+ }
423
+ }
424
+ })();
425
+ }, delay);
426
+ };
427
+ const retryDelivery = (topicID)=>{
428
+ if (disposed) return;
429
+ const names = new Set([
430
+ ...workers.keys(),
431
+ ...pendingRecords.map((record)=>record.frame.protocol)
432
+ ]);
433
+ for (const name of names){
434
+ if (topicID != null && cursors.get(name)?.topicID !== topicID && !pendingRecords.some((record)=>record.frame.protocol === name && record.frame.topicID === topicID)) continue;
435
+ const worker = workers.get(name);
436
+ if (worker != null) {
437
+ worker.backoff = 1000;
438
+ worker.retryNow = worker.running;
439
+ if (worker.timer != null) {
440
+ clearTimeout(worker.timer);
441
+ worker.timer = undefined;
442
+ }
443
+ }
444
+ scheduleWorker(name);
445
+ }
446
+ };
223
447
  /**
224
448
  * Take the staged pushes into the buffer and move the durable cursor over them, off the back of
225
449
  * live traffic alone — a peer that is online and walks no commit still has to keep its position,
@@ -248,34 +472,33 @@ const APP_FETCH_LIMIT = 100;
248
472
  });
249
473
  };
250
474
  /**
251
- * Record a log-class frame the LIVE lane was pushed, at the moment it arrives.
475
+ * Record a log-class frame the LIVE lane was pushed, once the live open of it settles.
252
476
  *
253
477
  * THE OTHER DELIVERER TAKING THE SAME READ POSITION: before the push carried its own log
254
478
  * position there was nothing for the live path to write down, so the cursor sat behind every
255
479
  * frame an online peer had already been given and every re-pull read them all back.
256
480
  *
257
481
  * 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:
482
+ * carries this frame to the host unwraps with the same handle. The open's own outcome decides,
483
+ * never the epoch hint:
259
484
  *
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.
485
+ * - OPENED, or refused at the handle's epoch: the live lane's one chance, taken — DONE.
486
+ * - Refused as AHEAD ({@link FrameEpochError}): its bytes are kept for the drain to deliver
487
+ * once the walk reaches that epoch.
488
+ * - Refused as past, or unreadable: dead. MLS ratchets forward.
270
489
  *
271
490
  * A MAILBOX frame is skipped outright — nothing to advance over. The class travels with the push
272
491
  * because ephemeral and logged app traffic share one topic, and guessing from the topic would
273
492
  * move the cursor over frames the log does not contain.
274
- */ const note = (name, topicID, message)=>{
493
+ */ const note = (name, topicID, message, failure)=>{
275
494
  const position = message.logPosition;
276
495
  if (position == null) return;
277
- const sealedAt = crypto.frameEpoch(message.payload);
278
- const ahead = sealedAt != null && sealedAt > crypto.epoch();
496
+ if (crypto.pending != null) {
497
+ // Pushed positions are unauthenticated metadata. Only fetches may populate this buffer.
498
+ scheduleSync();
499
+ return;
500
+ }
501
+ const ahead = isFrameAhead(failure);
279
502
  let pushes = staged.get(name);
280
503
  if (pushes == null) {
281
504
  pushes = [];
@@ -285,56 +508,108 @@ const APP_FETCH_LIMIT = 100;
285
508
  topicID,
286
509
  frame: {
287
510
  position: asLogPosition(position),
288
- sealed: ahead ? message.payload : null
511
+ sealed: ahead ? {
512
+ state: 'sealed',
513
+ bytes: message.payload
514
+ } : {
515
+ state: 'done'
516
+ }
289
517
  }
290
518
  });
291
519
  scheduleSync();
292
520
  };
293
521
  const drain = async ()=>{
294
522
  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
523
  for (const [name, frames] of segment){
304
524
  const events = appEventHandlers.get(name);
305
525
  const cursor = cursors.get(name);
306
- if (events == null || cursor == null || frames.length === 0) continue;
526
+ if (cursor == null || frames.length === 0 || events == null && crypto.pending == null) {
527
+ continue;
528
+ }
307
529
  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;
530
+ if (frame.sealed.state !== 'sealed') continue;
531
+ const sealed = frame.sealed.bytes;
532
+ // Unreadable bytes are dead. Past and future are the open's locked answer, below.
533
+ if (crypto.frameEpoch(sealed) == null) {
534
+ frame.sealed = {
535
+ state: 'done'
536
+ };
537
+ resumeBlocked(cursor.topicID, frame.position);
317
538
  continue;
318
539
  }
540
+ if (crypto.pending != null) {
541
+ const decoded = decodeAppAAD(crypto.frameAAD(sealed) ?? new Uint8Array());
542
+ if (decoded?.topicID !== cursor.topicID || decoded.intent !== 'log') {
543
+ frame.sealed = {
544
+ state: 'done'
545
+ };
546
+ resumeBlocked(cursor.topicID, frame.position);
547
+ continue;
548
+ }
549
+ }
550
+ const ref = crypto.pending == null ? undefined : {
551
+ id: frameID(cursor.topicID, sealed),
552
+ topicID: cursor.topicID,
553
+ protocol: name,
554
+ segment: anchor().epoch,
555
+ position: frame.position
556
+ };
319
557
  let opened;
320
558
  try {
321
559
  // `crypto.unwrap` always returns the full result — `senderDID` is REQUIRED — so there is
322
560
  // no bare-`Uint8Array` shortcut left to normalize away here. `expectedAAD` is bound to
323
561
  // the cursor's own topic, the authoritative answer to "what lane is this drain reading".
324
562
  opened = await crypto.unwrap(sealed, {
325
- expectedAAD: fromUTF(cursor.topicID)
563
+ expectedAAD: encodeAppAAD({
564
+ topicID: cursor.topicID,
565
+ intent: 'log'
566
+ }),
567
+ ...ref == null ? {} : {
568
+ frame: ref
569
+ }
326
570
  });
327
- } catch {
571
+ } catch (error) {
572
+ if (isFrameAhead(error)) {
573
+ // A future claim keeps its bytes and position even when the hub omits its commit.
574
+ if (crypto.pending != null) {
575
+ reportBlocked(name, cursor.topicID, frame.position, new Error(`frame claims future epoch ${error.frameEpoch}`), 'future-epoch');
576
+ }
577
+ continue;
578
+ }
579
+ if (crypto.pending != null && isAppFrameStorageError(error)) {
580
+ reportBlocked(name, cursor.topicID, frame.position, error);
581
+ throw error;
582
+ }
328
583
  // Claimed this epoch and the handle refused it — OR its AAD did not match this topic (a
329
584
  // wrong-topic frame, or a pre-upgrade empty-AAD frame). Either way, dead: the handle
330
585
  // never returns to this epoch and the topic binding never changes. Retained history from
331
586
  // before this bind existed is DELIBERATELY invalidated, not silently re-offered.
332
- frame.sealed = null;
587
+ frame.sealed = {
588
+ state: 'done'
589
+ };
590
+ resumeBlocked(cursor.topicID, frame.position);
591
+ continue;
592
+ }
593
+ if (ref != null) {
594
+ const record = {
595
+ frame: ref,
596
+ payload: opened.payload,
597
+ senderDID: opened.senderDID
598
+ };
599
+ frame.sealed = {
600
+ state: 'pending',
601
+ id: record.frame.id
602
+ };
603
+ pendingRecords.push(record);
333
604
  continue;
334
605
  }
335
606
  // Opened, so it is done whatever the payload turns out to be — every path below either
336
607
  // delivers it or drops it exactly as the live transport would.
337
- frame.sealed = null;
608
+ frame.sealed = {
609
+ state: 'done'
610
+ };
611
+ resumeBlocked(cursor.topicID, frame.position);
612
+ if (events == null) continue;
338
613
  // This `unwrap` is its own ingress — not fed by `peer.ts`'s normalized inbound path — so
339
614
  // the recovered sender is normalized HERE, once, before either use below: `localDID` (the
340
615
  // param above) is already normalized at peer construction, and the two must compare on
@@ -351,7 +626,9 @@ const APP_FETCH_LIMIT = 100;
351
626
  if (message.payload?.typ !== 'event' || typeof prc !== 'string') continue;
352
627
  // A retained frame naming an EPHEMERAL procedure was published `retain: 'log'` by a member
353
628
  // whose dispatch would never do that. Retention is the protocol's word, not the frame's.
354
- if (retentionOf(protocols[name], prc) !== 'log') continue;
629
+ const protocol = protocols[name];
630
+ if (protocol === undefined) continue;
631
+ if (retentionOf(protocol, prc) !== 'log') continue;
355
632
  try {
356
633
  // Same door as the live push: emit the retained frame's plaintext into the
357
634
  // per-protocol emitter the live bus is also built from. No listener → no-op.
@@ -368,16 +645,43 @@ const APP_FETCH_LIMIT = 100;
368
645
  }
369
646
  };
370
647
  return {
648
+ dropFrame: (topicID, position)=>runAppLane(async ()=>{
649
+ if (crypto.pending == null) throw new Error('durable app delivery is disabled');
650
+ const unknown = pendingRecords.find((record)=>protocols[record.frame.protocol] == null && record.frame.topicID === topicID && record.frame.position === position);
651
+ if (unknown != null) {
652
+ await crypto.pending.complete(unknown.frame.id);
653
+ pendingRecords.splice(pendingRecords.indexOf(unknown), 1);
654
+ resumeUnknown(unknown);
655
+ return;
656
+ }
657
+ const entry = [
658
+ ...cursors.entries()
659
+ ].find(([, cursor])=>cursor.topicID === topicID);
660
+ if (entry == null) throw new Error('app frame is not buffered');
661
+ const [name] = entry;
662
+ const frames = segment.get(name);
663
+ const frame = frames?.find((item)=>item.position === position);
664
+ if (frames == null || frame == null) throw new Error('app frame is not buffered');
665
+ if (frame.sealed.state === 'pending') throw new Error('app frame is pending');
666
+ if (frame.sealed.state !== 'sealed') throw new Error('app frame is already done');
667
+ if (frames.some((item)=>item.position < position && item.sealed.state !== 'done')) {
668
+ throw new Error('an earlier pending or sealed frame blocks the durable cursor');
669
+ }
670
+ frame.sealed = {
671
+ state: 'done'
672
+ };
673
+ resumeBlocked(topicID, position);
674
+ await advanceCursor(name, frames);
675
+ }),
676
+ retryDelivery,
371
677
  /**
372
678
  * MUST run BEFORE the apply, never after: once the commit applies the handle holds different
373
679
  * key material, and those bytes are ciphertext forever. Per-FRAME-EPOCH, not per-rotation:
374
680
  * every epoch inside a segment is dispensed as the walk passes through it.
375
681
  *
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.
682
+ * Which frames are this epoch's is the open's own answer: `unwrap` refuses another epoch with
683
+ * `FrameEpochError` before decrypting, and only its "ahead" answer keeps a frame. A forged
684
+ * future-epoch claim can hold the cursor until an operator drops it.
381
685
  *
382
686
  * The buffer is walked whole, not stopped at the first frame that is not this epoch's, since
383
687
  * the front can still hold a frame from an epoch the handle already passed (a journal replay
@@ -398,13 +702,46 @@ const APP_FETCH_LIMIT = 100;
398
702
  * the ordered buffer mid-walk re-reads or steps over a frame, and a sync landing between
399
703
  * {@link advanceCursor}'s read of a done run and its splice silently drops frames.
400
704
  *
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),
705
+ * The peer starts workers after its commit operation releases; direct lanes start them here.
706
+ */ deliver: async ()=>{
707
+ try {
708
+ await runAppLane(drain);
709
+ } finally{
710
+ if (crypto.pending != null && !disposed) {
711
+ for (const record of pendingRecords)reportUnknown(record);
712
+ for (const name of new Set(pendingRecords.map((record)=>record.frame.protocol))){
713
+ scheduleDelivery(()=>scheduleWorker(name));
714
+ }
715
+ }
716
+ }
717
+ },
406
718
  note,
719
+ pendingRecords: ()=>[
720
+ ...pendingRecords
721
+ ],
722
+ restore: async (records)=>{
723
+ await runAppLane(async ()=>{
724
+ for (const record of records){
725
+ reportUnknown(record);
726
+ if (!pendingRecords.some((item)=>item.frame.id === record.frame.id)) {
727
+ pendingRecords.push(record);
728
+ }
729
+ }
730
+ pendingRecords.sort((a, b)=>a.frame.segment - b.frame.segment || a.frame.position.localeCompare(b.frame.position));
731
+ });
732
+ },
733
+ dispose: ()=>{
734
+ disposed = true;
735
+ for (const worker of workers.values()){
736
+ if (worker.timer != null) clearTimeout(worker.timer);
737
+ }
738
+ },
407
739
  reset: ()=>{
740
+ const cleared = [
741
+ ...blockingFrames.values()
742
+ ];
743
+ blockingFrames.clear();
744
+ if (!disposed) for (const event of cleared)notifyAppHost(onAppDeliveryResumed, event);
408
745
  segment = new Map();
409
746
  cursors = new Map();
410
747
  // Staged pushes go with the buffer for the same reason: a rotation mid-push carries its own
@@ -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
  }