@serfab/cadre-core 1.21.0 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +294 -294
  2. package/dist/cadre-node.d.ts +329 -53
  3. package/dist/cadre-node.js +767 -85
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-authorization.d.ts +32 -2
  6. package/dist/control-authorization.js +19 -0
  7. package/dist/control-authorization.js.map +1 -1
  8. package/dist/control-database.d.ts +236 -23
  9. package/dist/control-database.js +587 -173
  10. package/dist/control-database.js.map +1 -1
  11. package/dist/control-schema.d.ts +3 -3
  12. package/dist/control-schema.js +71 -7
  13. package/dist/control-schema.js.map +1 -1
  14. package/dist/ed25519-key.d.ts +8 -0
  15. package/dist/ed25519-key.js +11 -1
  16. package/dist/ed25519-key.js.map +1 -1
  17. package/dist/index.d.ts +5 -1
  18. package/dist/index.js +13 -1
  19. package/dist/index.js.map +1 -1
  20. package/dist/machine-removal.d.ts +51 -1
  21. package/dist/machine-removal.js +42 -1
  22. package/dist/machine-removal.js.map +1 -1
  23. package/dist/membership-connection-gater.d.ts +8 -0
  24. package/dist/membership-connection-gater.js +13 -1
  25. package/dist/membership-connection-gater.js.map +1 -1
  26. package/dist/owner-keys.js +2 -1
  27. package/dist/owner-keys.js.map +1 -1
  28. package/dist/owner-signer.js +3 -4
  29. package/dist/owner-signer.js.map +1 -1
  30. package/dist/peer-authorization.d.ts +14 -2
  31. package/dist/peer-authorization.js +24 -1
  32. package/dist/peer-authorization.js.map +1 -1
  33. package/dist/sealed-party-key.d.ts +32 -0
  34. package/dist/sealed-party-key.js +162 -0
  35. package/dist/sealed-party-key.js.map +1 -0
  36. package/dist/seed-bootstrap.d.ts +10 -3
  37. package/dist/seed-bootstrap.js +12 -0
  38. package/dist/seed-bootstrap.js.map +1 -1
  39. package/dist/strand-addr-protocol.d.ts +56 -6
  40. package/dist/strand-addr-protocol.js +57 -5
  41. package/dist/strand-addr-protocol.js.map +1 -1
  42. package/dist/strand-commit-durability.d.ts +33 -2
  43. package/dist/strand-commit-durability.js +44 -4
  44. package/dist/strand-commit-durability.js.map +1 -1
  45. package/dist/strand-database.d.ts +35 -5
  46. package/dist/strand-database.js +34 -10
  47. package/dist/strand-database.js.map +1 -1
  48. package/dist/strand-instance-manager.d.ts +133 -9
  49. package/dist/strand-instance-manager.js +266 -42
  50. package/dist/strand-instance-manager.js.map +1 -1
  51. package/dist/strand-membership-reconciler.d.ts +250 -51
  52. package/dist/strand-membership-reconciler.js +410 -66
  53. package/dist/strand-membership-reconciler.js.map +1 -1
  54. package/dist/strand-membership-writer.d.ts +7 -0
  55. package/dist/strand-membership-writer.js +9 -0
  56. package/dist/strand-membership-writer.js.map +1 -1
  57. package/dist/strand-party-key-rotation.d.ts +177 -0
  58. package/dist/strand-party-key-rotation.js +340 -0
  59. package/dist/strand-party-key-rotation.js.map +1 -0
  60. package/dist/strand-party-machines.d.ts +111 -0
  61. package/dist/strand-party-machines.js +258 -0
  62. package/dist/strand-party-machines.js.map +1 -0
  63. package/dist/strand-party-peers.d.ts +101 -0
  64. package/dist/strand-party-peers.js +49 -0
  65. package/dist/strand-party-peers.js.map +1 -0
  66. package/dist/strand-peer-redial.d.ts +34 -7
  67. package/dist/strand-peer-redial.js +46 -13
  68. package/dist/strand-peer-redial.js.map +1 -1
  69. package/dist/strand-revocation-enforcer.d.ts +15 -1
  70. package/dist/strand-revocation-enforcer.js +16 -9
  71. package/dist/strand-revocation-enforcer.js.map +1 -1
  72. package/dist/strand-transport-key.js +3 -0
  73. package/dist/strand-transport-key.js.map +1 -1
  74. package/dist/strand-watcher.d.ts +7 -4
  75. package/dist/strand-watcher.js +12 -7
  76. package/dist/strand-watcher.js.map +1 -1
  77. package/dist/types.d.ts +160 -13
  78. package/dist/types.js.map +1 -1
  79. package/package.json +9 -8
  80. package/src/cadre-node.ts +12252 -11528
  81. package/src/control-authorization.ts +41 -1
  82. package/src/control-database.ts +6123 -5603
  83. package/src/control-schema.ts +71 -7
  84. package/src/ed25519-key.ts +12 -1
  85. package/src/index.ts +957 -924
  86. package/src/machine-removal.ts +80 -1
  87. package/src/membership-connection-gater.ts +13 -1
  88. package/src/owner-keys.ts +2 -1
  89. package/src/owner-signer.ts +92 -94
  90. package/src/peer-authorization.ts +27 -3
  91. package/src/sealed-party-key.ts +190 -0
  92. package/src/seed-bootstrap.ts +17 -3
  93. package/src/strand-addr-protocol.ts +67 -6
  94. package/src/strand-commit-durability.ts +54 -5
  95. package/src/strand-database.ts +47 -11
  96. package/src/strand-instance-manager.ts +330 -42
  97. package/src/strand-membership-reconciler.ts +1310 -942
  98. package/src/strand-membership-writer.ts +10 -0
  99. package/src/strand-party-key-rotation.ts +436 -0
  100. package/src/strand-party-machines.ts +293 -0
  101. package/src/strand-party-peers.ts +129 -0
  102. package/src/strand-peer-redial.ts +61 -14
  103. package/src/strand-revocation-enforcer.ts +27 -9
  104. package/src/strand-transport-key.ts +3 -0
  105. package/src/strand-watcher.ts +12 -7
  106. package/src/types.ts +3112 -2963
@@ -1,10 +1,12 @@
1
1
  /**
2
2
  * Strand membership reconciliation: the per-instance background loop that finishes a
3
- * party's join at strand bring-up. Every machine of a party that runs a closed strand
4
- * ends up with (1) the party's `Strand.Member` row seated — redeeming the
5
- * formation-staged invitation if one is pending — and (2) its own durable
6
- * machine→party binding (`Strand.MemberPeer`) written, which is what revocation
7
- * enforcement and future admission control key on.
3
+ * party's join at strand bring-up and keeps the party's machine bindings whole. Every
4
+ * machine of a party that runs a closed strand ends up with (1) the party's `Strand.Member`
5
+ * row seated — redeeming the formation-staged invitation if one is pending — (2) its own
6
+ * durable machine→party binding (`Strand.MemberPeer`) written, which is what revocation
7
+ * enforcement and future admission control key on, and (3) every live sibling machine's
8
+ * binding written under the party's current key, with a removed machine's binding cleared —
9
+ * see "Binding the party's other machines" below.
8
10
  *
9
11
  * ## Contract
10
12
  *
@@ -26,10 +28,12 @@
26
28
  * for someone to admit this party — nothing this machine can do faster — so it re-arms on
27
29
  * the flat poll interval and resets the ladder. The loop stops on the done state.
28
30
  * - **Done state**: the party's member row is visible locally, this machine's own binding
29
- * is in place, AND no invitation is still staged — the loop stops. A LATER revocation is
30
- * the enforcer's business, not this loop's; a resume rebuilds the reconciler and
31
- * re-verifies from scratch (every write is idempotent, so re-running is free), and a
32
- * fresh invitation staged on a done loop re-arms it in place ({@link rearm}).
31
+ * is in place, every live sibling with a `StrandPeer` row is bound under the party's key
32
+ * (a pass that wrote a binding is not done; the next pass has to find nothing left), AND no
33
+ * invitation is still staged — the loop stops. A LATER revocation is the enforcer's
34
+ * business, not this loop's; a resume rebuilds the reconciler and re-verifies from scratch
35
+ * (every write is idempotent, so re-running is free), and a fresh invitation staged on a
36
+ * done loop, or a change to the party's machines, re-arms it in place ({@link rearm}).
33
37
  *
34
38
  * ## One pass
35
39
  *
@@ -38,28 +42,112 @@
38
42
  * a fresh formation, which re-arms the loop. With an invitation staged the loop reports
39
43
  * the dead end (below) and carries on: the redemption is attempted like any other, and a
40
44
  * manager's re-admission lets a later pass finish it.
41
- * 2. **Ensure membership.** Member row visible → done with this step; if a staged
42
- * invitation is still unspent, BURN it ({@link burnInvite} — the `ConsumedInvite` row
43
- * alone) so the bearer credential cannot be spent by anyone else. A burn refused by the
44
- * cohort keeps the invitation staged for the next pass (it is the same write gate a
45
- * redemption faces, and the local member row may be stale — see "Re-arming"); a dead
46
- * invitation is dropped. Member row absent + staged invitation → {@link consumeInvite}
47
- * under the party's own key, retried across passes until the `Invite` row has
48
- * replicated here and the write commits. Absent with no invitation (founder rows not
45
+ * 2. **Ensure membership.** Read first whether the party is moving to another key in this
46
+ * strand ({@link PartyStrandPeerSource.pendingKey}, one control read per pass); while it
47
+ * is, the step runs under that key instead — see "Redeeming under the pending key". Otherwise:
48
+ * member row visible → done with this step; if a staged invitation is still unspent, BURN it
49
+ * ({@link burnInvite} — the `ConsumedInvite` row alone) so the bearer credential cannot be
50
+ * spent by anyone else. A burn refused by the cohort keeps the invitation staged for the next
51
+ * pass (it is the same write gate a redemption faces, and the local member row may be stale —
52
+ * see "Re-arming"); a dead invitation is dropped. Member row absent + staged invitation →
53
+ * {@link consumeInvite} under the party's own key, retried across passes until the `Invite`
54
+ * row has replicated here and the write commits. Absent with no invitation (founder rows not
49
55
  * yet synced, or a machine whose party never joined) → keep waiting, escalating to one
50
56
  * visible warning after {@link IDLE_PASSES_BEFORE_ESCALATION} passes, never throwing.
51
57
  * 3. **Ensure the binding.** {@link registerMemberPeer} (insert-if-absent, restart-safe)
52
58
  * with this node's own strand transport peer id — only after step 2 sees the member
53
- * row locally (its deferred `MemberExists` reads the live local table). Done only once
54
- * the binding is in place AND nothing is staged; a binding written while a burn keeps
55
- * being refused leaves the loop live to settle the invitation later.
59
+ * row locally (its deferred `MemberExists` reads the live local table). A binding
60
+ * written while a burn keeps being refused leaves the loop live to settle the
61
+ * invitation later.
62
+ * 4. **Bind live siblings.** Every strand peer id the control database records for a live
63
+ * machine of this party ({@link PartyStrandPeerSource.read}) that has no binding under the
64
+ * party's key gets one, written here with the party key. See "Binding the party's other
65
+ * machines".
66
+ * 5. **Clear removed machines.** A binding under the party's key for a machine removed from
67
+ * the cadre is cleared through the self branch of {@link removeMemberPeer} — unless the
68
+ * pending-key read at step 2 found a party key rotation pending for the strand, or failed.
69
+ * 6. **Re-attempt this machine's own `StrandPeer` row** ({@link PartyStrandPeerSource.publishOwn}),
70
+ * the control-side statement step 4 on the siblings reads: a background write at bring-up
71
+ * that is deferred while alone or refused until this machine's own `CadrePeer` row arrives.
72
+ *
73
+ * ## Binding the party's other machines
74
+ *
75
+ * A `MemberPeer` binding is signed by the member key, which every machine of the party holds,
76
+ * so any machine can bind any peer id under the party's key: the party vouching for its own
77
+ * machine. Which peer ids are the party's machines comes from `CadreControl.StrandPeer`, each
78
+ * machine's own signed statement of its peer id in the strand, joined to the party's live
79
+ * machines and its `CadrePeer` tombstones (`strand-party-peers.ts`). The point is a party
80
+ * member key that changes (a machine removal rotates it: `strand-party-key-rotation.ts`):
81
+ * a sibling offline through the change returns to find itself bound under the new key by the
82
+ * machines that were there, and a machine bound by a sibling that had not yet heard of its
83
+ * removal is cleared once the tombstone arrives.
84
+ *
85
+ * Step 5 is gated on no rotation pending (the pending-key state step 2 read). While one is, the
86
+ * removed machine's binding under the current key is exactly the orphan the rotation is about to
87
+ * leave behind, and clearing it would hand the removed machine a clean slate the deny-list gate
88
+ * admits. A failed pending read clears nothing for the same reason. After the swap the pending row is gone, and the step
89
+ * clears a binding a lagging sibling wrote under the new key. The gate holds only because a
90
+ * removal writes the machine's tombstone and the pending row in ONE transaction
91
+ * (`ControlDatabase.removeMachine`): a tombstone that reaches this node without
92
+ * its pending row reads as "no rotation", and this step clears the binding the rotation
93
+ * meant to orphan, which leaves the removed machine admitted as a stranger rather than denied.
94
+ *
95
+ * The step reads the party's bindings once per pass (`listMemberPeers`) and compares in
96
+ * JavaScript, the scan-not-seek idiom. Two machines binding one sibling at once collide on the
97
+ * `MemberPeer` primary key; the loser's write is refused and its next pass finds the row. A
98
+ * sibling's row that cannot be read keeps the loop live on the flat poll interval, and a write
99
+ * that fails is retried on the ladder.
100
+ *
101
+ * ## Redeeming under the pending key
102
+ *
103
+ * A machine removal replaces the party's member key K in each closed strand with a fresh key K'
104
+ * (`strand-party-key-rotation.ts`), and in a strand the party does not manage K cannot seat K'
105
+ * itself: the strand's host has to re-invite the party, or its manager admit K' by hand
106
+ * (docs/strands.md → Replacing the party's key). The host's fresh invitation is staged here like
107
+ * any other and lands in step 2, which is why one rule governs that step: **while a
108
+ * `PendingStrandPartyKey` row exists for the strand, this loop never writes a `Strand.Member`
109
+ * row under K.** The removed machine holds K, and a seat written under K is a seat it keeps.
110
+ * Three cases, decided by what {@link PartyStrandPeerSource.pendingKey} answers at the head of
111
+ * the pass (a rejected read counts as pending with the key unreadable):
112
+ *
113
+ * - **No rotation pending**: the ordinary step 2 above.
114
+ * - **Pending, the key not readable here** (the row is sealed to other machines: this machine
115
+ * was admitted after the removal, or runs on an ephemeral identity; or the read failed): the
116
+ * step neither consumes nor burns. A staged invitation stays staged, with one debug line, for
117
+ * a machine that can read the key to redeem; the pass is idle, and it does not count toward
118
+ * the probable blocked re-join report below — it left the invitation staged on purpose.
119
+ * - **Pending, the key opened**: with K' already a member (admitted by hand, or seated by a
120
+ * sibling's redemption), a staged invitation is burned against K' and the rotation driver is
121
+ * kicked ({@link StrandMembershipReconcilerDeps.onPendingKeySeated}); with K' not yet a member
122
+ * and an invitation staged, it is redeemed under K' and the driver kicked; a refused
123
+ * redemption is classified as under K, except that a sealed strand is not terminal here (the
124
+ * party may still be a member under K) and only drops the dead invitation. With nothing staged
125
+ * the pass is idle: the driver has reported `needs-another-party`, and nothing happens until
126
+ * the host acts.
127
+ *
128
+ * Step 2 still answers whether K's member row is visible, which the binding steps that follow
129
+ * are under: K is the party's current key until the control swap, and a binding written under K
130
+ * after K has left (step 5 of the rotation, before the swap replicates here) is refused by
131
+ * `MemberPeer.MemberExists` and polled, until the swap re-keys this loop. The loop does not
132
+ * latch done while a rotation is pending, whatever else is in place, so a by-hand admission or a
133
+ * sibling's redemption is noticed on the next pass and the driver kicked; a pass that wrote
134
+ * nothing is idle, so the cadence is the flat poll interval. The pending state ends with the
135
+ * swap: `StrandInstanceManager.rekeyParty` rebuilds this loop under K', whose next pass finds no
136
+ * pending row, clears the removed machine's stale binding (step 5) and latches done as before.
137
+ * Whoever redeems the host's invitation seats a key of its choosing, so the invitation must reach
138
+ * the party's owner and not the removed machine, as with every invitation today.
56
139
  *
57
140
  * ## Stops, and re-arming
58
141
  *
59
- * Two kinds of stop. A RE-ARMABLE stop is one a fresh invitation should reopen:
142
+ * Two kinds of stop. A RE-ARMABLE stop is one a fresh invitation, or a change to the
143
+ * party's machines, should reopen:
60
144
  *
61
145
  * - **Done** (above).
62
- * - **Self-revoked with nothing staged** (step 1 above).
146
+ * - **Self-revoked with nothing staged** (step 1 above). A machine whose only binding is
147
+ * orphaned — its sibling rotated the key before this machine's `StrandPeer` row reached it —
148
+ * is denied by every other machine, so its own loop cannot write and stops here. The heal is
149
+ * a sibling binding it (step 4 there); its enforcer then drops its peer id from the deny set
150
+ * and reports `onSelfRestored`, which re-arms this loop.
63
151
  *
64
152
  * A PERMANENT stop is one a fresh invitation changes nothing about — {@link rearm} is a
65
153
  * no-op after it:
@@ -76,7 +164,10 @@
76
164
  * the instance manager, which calls {@link rearm}: a done loop reopens and runs one pass
77
165
  * at once; a running loop is merely kicked. This is what lets a party that was REMOVED
78
166
  * from the strand, and then handed a new invitation, actually attempt it — the loop
79
- * finished during its first join, long before the removal.
167
+ * finished during its first join, long before the removal. `CadreNode` also re-arms every
168
+ * strand's loop when `CadreControl.StrandPeer`, `CadrePeer` or `Revocation` changes
169
+ * (`StrandInstanceManager.notifyPartyPeersChanged`), so a sibling's row arriving binds it
170
+ * within the watch's coalescing window rather than at the next resume.
80
171
  *
81
172
  * On a removed party the local replica is usually stale: the cohort cut this machine off
82
173
  * at about the moment the removal was written, so `isStrandMember` still answers true and
@@ -148,7 +239,7 @@ import { CoordinatorPartialCommitError } from '@optimystic/db-core';
148
239
  import { PartialCommitError } from '@optimystic/quereus-plugin-optimystic';
149
240
  import { causeChain } from './control-retry.js';
150
241
  import { strandMemberKeyPair } from './strand-member-key.js';
151
- import { StrandOfflineQueueBusyError, StrandTransactionBusyError, burnInvite, consumeInvite, isStrandMember, registerMemberPeer, } from './strand-membership-writer.js';
242
+ import { StrandOfflineQueueBusyError, StrandTransactionBusyError, burnInvite, consumeInvite, isStrandMember, listMemberPeers, registerMemberPeer, removeMemberPeer, } from './strand-membership-writer.js';
152
243
  import { defaultTimeoutScheduler } from './timeout-scheduler.js';
153
244
  import { describeThrown } from './describe-thrown.js';
154
245
  const log = debug('sereus:cadre:strand-membership-reconciler');
@@ -290,15 +381,24 @@ export class StrandMembershipReconciler {
290
381
  /** Whether the blocked re-join was already reported this re-arm cycle (one report, either trigger). */
291
382
  this.rejoinBlockedReported = false;
292
383
  /**
293
- * Whether the pass that just ran found nothing to act on — no member row and no staged
294
- * invitation. That is a wait to be admitted, not an unfinished join, so it re-arms on the
295
- * flat poll interval; every other unfinished outcome climbs the ladder.
384
+ * Whether the pass in flight left the staged invitation alone ON PURPOSE (a rotation is pending
385
+ * and this machine cannot read the key), which is not an attempt that failed and so does not
386
+ * count toward the probable blocked re-join report. Reset at the head of every pass.
387
+ */
388
+ this.inviteLeftStagedDeliberately = false;
389
+ /** Whether this cycle has logged that the loop stays live for a pending rotation (one line per re-arm cycle). */
390
+ this.pendingRotationLogged = false;
391
+ /**
392
+ * Whether the pass that just ran is waiting on something no faster retry can shorten — no
393
+ * member row and no staged invitation (a wait to be admitted, {@link noteIdlePass}), or the
394
+ * party's machines unreadable ({@link waitForPoll}). Such a pass re-arms on the flat poll
395
+ * interval; every other unfinished outcome climbs the ladder.
296
396
  *
297
397
  * NOTE: the ladder is therefore the DEFAULT for any outcome nobody classified — a new
298
398
  * early return added to {@link doPass} inherits the fast retry unless it calls
299
- * {@link noteIdlePass}. Right for every outcome that exists today (each is an unfinished
300
- * join this machine can make progress on). If an early return is ever added for a
301
- * condition retrying cannot resolve, classify it idle.
399
+ * {@link noteIdlePass} or {@link waitForPoll}. Right for every outcome that exists today
400
+ * (each is an unfinished join this machine can make progress on). If an early return is
401
+ * ever added for a condition retrying cannot resolve, classify it so.
302
402
  */
303
403
  this.lastPassIdle = false;
304
404
  this.scheduler = deps.scheduler ?? defaultTimeoutScheduler;
@@ -345,15 +445,17 @@ export class StrandMembershipReconciler {
345
445
  this.halt('stopped by the runtime', true);
346
446
  }
347
447
  /**
348
- * A fresh invitation was staged: reopen a loop that stopped on a re-armable state (done,
349
- * or self-revoked with nothing staged) and run one pass at once; merely kick a loop that
350
- * is still running; do nothing after a permanent stop. Never rejects, and serialized
351
- * like {@link reconcile}: the reopen happens when the queued pass STARTS, after any pass
352
- * in flight has settled, so a `done` that pass latches cannot swallow the re-arm — and a
353
- * public {@link stop} that lands first still wins, because the queued pass re-checks it.
448
+ * Something changed that a stopped loop should look at — `cause` names it for the log: a
449
+ * fresh invitation was staged, the party's machines changed, or this machine is no longer
450
+ * revoked. Reopen a loop that stopped on a re-armable state (done, or self-revoked with
451
+ * nothing staged) and run one pass at once; merely kick a loop that is still running; do
452
+ * nothing after a permanent stop. Never rejects, and serialized like {@link reconcile}: the
453
+ * reopen happens when the queued pass STARTS, after any pass in flight has settled, so a
454
+ * `done` that pass latches cannot swallow the re-arm — and a public {@link stop} that lands
455
+ * first still wins, because the queued pass re-checks it.
354
456
  */
355
- rearm() {
356
- return this.enqueue(() => this.reopen() ? this.doPass() : Promise.resolve());
457
+ rearm(cause = 'a fresh invitation') {
458
+ return this.enqueue(() => this.reopen(cause) ? this.doPass() : Promise.resolve());
357
459
  }
358
460
  /**
359
461
  * Run one pass now. Never rejects. Serialized: concurrent calls chain, so no two
@@ -385,9 +487,9 @@ export class StrandMembershipReconciler {
385
487
  * with the idle and unfinished counters, both escalation latches and the retry ladder
386
488
  * reset — a fresh invitation is a fresh cycle.
387
489
  */
388
- reopen() {
490
+ reopen(cause) {
389
491
  if (this.permanentlyStopped) {
390
- log('[%s] re-arm refused — the loop is stopped for good', this.deps.label);
492
+ log('[%s] re-arm (%s) refused — the loop is stopped for good', this.deps.label, cause);
391
493
  return false;
392
494
  }
393
495
  if (!this.stoppedFlag) {
@@ -395,7 +497,7 @@ export class StrandMembershipReconciler {
395
497
  // party whose loop already reported and is then re-formed AGAIN gets no second report
396
498
  // for the replacement invitation. If that second report is ever wanted, key the latch
397
499
  // on the staged invitation's key rather than on the re-arm.
398
- log('[%s] fresh invitation staged on a running loop — kicking a pass', this.deps.label);
500
+ log('[%s] %s on a running loop — kicking a pass', this.deps.label, cause);
399
501
  return true;
400
502
  }
401
503
  this.stoppedFlag = false;
@@ -404,8 +506,9 @@ export class StrandMembershipReconciler {
404
506
  this.idleEscalated = false;
405
507
  this.unfinishedPasses = 0;
406
508
  this.rejoinBlockedReported = false;
509
+ this.pendingRotationLogged = false;
407
510
  this.retryDelayMs = undefined;
408
- log('[%s] membership reconciler re-armed by a fresh invitation', this.deps.label);
511
+ log('[%s] membership reconciler re-armed by %s', this.deps.label, cause);
409
512
  return true;
410
513
  }
411
514
  /** One serialized pass; contains every failure (contract: never rejects). */
@@ -420,7 +523,8 @@ export class StrandMembershipReconciler {
420
523
  // stop lands with the binding missing until the next resume rebuilds the loop. A
421
524
  // missing binding only mis-credits diversity today; if it ever gates admission, make
422
525
  // this stop also require the binding to be in place.
423
- this.finish('this party is revoked from the strand — re-admission arrives (if ever) via a fresh formation', false);
526
+ this.finish('this party is revoked from the strand — re-admission arrives (if ever) via a fresh formation, '
527
+ + 'or a sibling binds this machine under the party\'s current key', false);
424
528
  return;
425
529
  }
426
530
  const keyPair = this.resolveKeyPair();
@@ -439,12 +543,20 @@ export class StrandMembershipReconciler {
439
543
  }
440
544
  }
441
545
  /**
442
- * Steps 2 and 3 against a live database, with the outcome counted toward the probable
546
+ * Steps 2 to 6 against a live database, with the outcome counted toward the probable
443
547
  * blocked re-join report whether the attempt returned or threw.
548
+ *
549
+ * NOTE: steps 4 to 6 cost one `StrandPeer` read, one fresh membership read and one
550
+ * `MemberPeer` scan per pass, per closed strand, and `CadreNode` re-arms every strand's loop
551
+ * on each change to the party's machines, their records included. Fine at party scale; if a
552
+ * party ever runs many strands on many machines, read `StrandPeer` once per control change
553
+ * rather than per pass.
444
554
  */
445
555
  async attempt(db, keyPair) {
556
+ this.inviteLeftStagedDeliberately = false;
446
557
  try {
447
- if (!(await this.ensureMembership(db, keyPair)))
558
+ const pending = await this.readPendingKeyState();
559
+ if (!(await this.ensureMembership(db, keyPair, pending)))
448
560
  return;
449
561
  // NOTE: accepted tradeoff — the redemption (`Member` + `ConsumedInvite`) and the binding
450
562
  // below stay two SEPARATE commits on purpose. Merging them would save one commit: its
@@ -459,12 +571,33 @@ export class StrandMembershipReconciler {
459
571
  // saved, the invitation still live) that {@link reportHalfCommittedJoin}'s dropping of the
460
572
  // invitation gets wrong. Revisit when Optimystic offers an all-or-nothing multi-collection
461
573
  // commit, or when the enforcer can tell a not-yet-seated binding from a removed member's.
462
- await this.ensureBinding(db, keyPair);
574
+ if (!(await this.ensureBinding(db, keyPair)))
575
+ return;
576
+ const siblingsSettled = await this.reconcileSiblings(db, keyPair, pending.pending);
577
+ await this.publishOwnStrandPeer();
578
+ this.latchDone(siblingsSettled, pending.pending);
463
579
  }
464
580
  finally {
465
581
  this.noteAttemptOutcome();
466
582
  }
467
583
  }
584
+ /**
585
+ * The party's pending key in this strand, read once per pass. No seam means no rotation is
586
+ * ever pending; a rejected read is "pending, key unreadable", the posture under which nothing
587
+ * is seated under the current key and no removed machine's binding is cleared (module doc).
588
+ */
589
+ async readPendingKeyState() {
590
+ const source = this.deps.partyPeers;
591
+ if (!source)
592
+ return { pending: false };
593
+ try {
594
+ return await source.pendingKey();
595
+ }
596
+ catch (error) {
597
+ log('[%s] whether a party key rotation is pending could not be read — treated as pending with the key unreadable: %s', this.deps.label, describeThrown(error));
598
+ return { pending: true, key: null };
599
+ }
600
+ }
468
601
  /**
469
602
  * Arm the next pass, now that this one has settled — so a slow pass never stacks ticks
470
603
  * behind it. Only a STARTED loop schedules: a caller driving {@link reconcile} by hand
@@ -482,8 +615,8 @@ export class StrandMembershipReconciler {
482
615
  }, delayMs);
483
616
  }
484
617
  /**
485
- * The delay before the next pass: the flat poll interval while the loop is merely idling
486
- * (no member row, no staged invitation — {@link noteIdlePass}), otherwise the next rung
618
+ * The delay before the next pass: the flat poll interval while the loop is merely waiting
619
+ * ({@link lastPassIdle}), otherwise the next rung
487
620
  * of the doubling ladder from {@link INITIAL_JOIN_RETRY_INTERVAL_MS}, capped at the poll
488
621
  * interval. A pass that lands idle resets the ladder, so a later unfinished join starts
489
622
  * over at the bottom rung.
@@ -503,10 +636,27 @@ export class StrandMembershipReconciler {
503
636
  }
504
637
  }
505
638
  /**
506
- * Step 2 of the pass: `true` iff the party's member row is visible locally by the
507
- * time this returns (already present, or seated by redeeming the staged invitation).
639
+ * Step 2 of the pass: `true` iff the party's member row under its CURRENT key is visible
640
+ * locally by the time this returns (already present, or seated by redeeming the staged
641
+ * invitation). While a rotation is pending the staged invitation is spent under the pending
642
+ * key instead, or left alone ("Redeeming under the pending key" in the module doc), and the
643
+ * answer is only whether the current key is still a member.
508
644
  */
509
- async ensureMembership(db, keyPair) {
645
+ async ensureMembership(db, keyPair, pending) {
646
+ if (!pending.pending) {
647
+ return this.ensureMembershipUnderOwnKey(db, keyPair);
648
+ }
649
+ const isMember = await isStrandMember(db, keyPair.publicKeyB64);
650
+ if (pending.key === null) {
651
+ this.leaveInviteStaged();
652
+ }
653
+ else {
654
+ await this.seatPendingKey(db, pending.key);
655
+ }
656
+ return isMember;
657
+ }
658
+ /** Step 2 with no rotation pending: the member row under the party's own key, seated from the staged invitation if need be. */
659
+ async ensureMembershipUnderOwnKey(db, keyPair) {
510
660
  if (await isStrandMember(db, keyPair.publicKeyB64)) {
511
661
  await this.burnLeftoverInvite(db, keyPair);
512
662
  return true;
@@ -524,13 +674,83 @@ export class StrandMembershipReconciler {
524
674
  }, OWN_TRANSACTION);
525
675
  }
526
676
  catch (error) {
527
- this.handleConsumeFailure(error, invite);
677
+ this.handleConsumeFailure(error, invite, 'own-key');
528
678
  return false;
529
679
  }
530
680
  this.deps.pendingInvite?.clear(invite);
531
681
  log('[%s] redeemed the staged membership invitation — Member row seated under this party\'s key', this.deps.label);
532
682
  return true;
533
683
  }
684
+ /**
685
+ * Step 2 while a rotation is pending whose key this machine cannot read: nothing is seated or
686
+ * burned, since the only key this machine could sign with is the one being retired. A staged
687
+ * invitation is left for a machine that can read the key, and the pass is idle.
688
+ */
689
+ leaveInviteStaged() {
690
+ this.waitForPoll();
691
+ if (this.deps.pendingInvite?.get()) {
692
+ this.inviteLeftStagedDeliberately = true;
693
+ log('[%s] the staged invitation is left staged: the party is moving to a key this machine cannot read', this.deps.label);
694
+ }
695
+ }
696
+ /**
697
+ * Step 2 while a rotation is pending and this machine can read the pending key: see the
698
+ * pending-and-opened case of "Redeeming under the pending key" in the module doc. A pending
699
+ * key that does not decode throws to the pass's catch, which retries it.
700
+ */
701
+ async seatPendingKey(db, opened) {
702
+ const newKey = strandMemberKeyPair(opened.privateKey);
703
+ const invite = this.deps.pendingInvite?.get();
704
+ if (await isStrandMember(db, newKey.publicKeyB64)) {
705
+ if (invite) {
706
+ await this.burnLeftoverInvite(db, newKey);
707
+ }
708
+ else {
709
+ this.waitForPoll();
710
+ }
711
+ this.kickRotationDriver('the pending key is a member');
712
+ return;
713
+ }
714
+ if (!invite) {
715
+ this.waitForPoll();
716
+ return;
717
+ }
718
+ try {
719
+ await consumeInvite(db, {
720
+ inviteKey: invite.inviteKey,
721
+ invitePrivateKey: invite.invitePrivateKey,
722
+ memberKey: newKey.publicKeyB64,
723
+ }, OWN_TRANSACTION);
724
+ }
725
+ catch (error) {
726
+ this.handleConsumeFailure(error, invite, 'pending-key');
727
+ return;
728
+ }
729
+ this.deps.pendingInvite?.clear(invite);
730
+ log('[%s] redeemed the staged membership invitation under the party\'s PENDING key — the rotation can finish', this.deps.label);
731
+ this.kickRotationDriver('the pending key was just seated');
732
+ }
733
+ /**
734
+ * Tell the rotation driver the pending key is seated. Once per pass that sees the seat, so a
735
+ * machine that cannot drive (no owner key here, or the swap deferred) hears it again on its
736
+ * next pass rather than never.
737
+ *
738
+ * NOTE: a non-owner machine that reads the key kicks on every pass between the seat and the
739
+ * swap, and `CadreNode.driveRotationIfPending` logs its refusal each time; bounded by the
740
+ * seconds the swap takes on the owner machine. The owner machine alone does the same while
741
+ * its swap is deferred (the only sibling offline): every pass kicks, the driver runs its
742
+ * reads and ends "swap deferred", for as long as that sibling stays away. If either log
743
+ * ever matters, kick once per seat (remember the pending stamp kicked for).
744
+ */
745
+ kickRotationDriver(cause) {
746
+ try {
747
+ this.deps.onPendingKeySeated?.();
748
+ log('[%s] rotation driver kicked: %s', this.deps.label, cause);
749
+ }
750
+ catch (error) {
751
+ log('[%s] the pending-key-seated callback threw: %s', this.deps.label, describeThrown(error));
752
+ }
753
+ }
534
754
  /**
535
755
  * The already-member arm: spend a still-staged invitation so nobody else can. The stage
536
756
  * is cleared once the burn lands or the invitation is known dead (already spent,
@@ -595,33 +815,147 @@ export class StrandMembershipReconciler {
595
815
  }
596
816
  }
597
817
  /**
598
- * Step 3 of the pass: write this machine's own `MemberPeer` binding (insert-if-absent)
599
- * and, once it is in place with nothing staged, latch the done state and stop the loop.
600
- * A missing transport peer id (a quiesce racing the pass) defers to the next tick; a
601
- * write failure — a busy refusal included — is contained by the pass's outer catch and
602
- * retried. A binding written while an invitation is still staged (its burn keeps being
603
- * refused) is not done: the loop stays live so a later pass can settle the credential.
818
+ * Step 3 of the pass: write this machine's own `MemberPeer` binding (insert-if-absent);
819
+ * `true` once it is in place. A missing transport peer id (a quiesce racing the pass)
820
+ * defers to the next tick; a write failure — a busy refusal included — is contained by the
821
+ * pass's outer catch and retried.
604
822
  */
605
823
  async ensureBinding(db, keyPair) {
606
824
  const peerId = this.deps.getOwnPeerId();
607
825
  if (!peerId) {
608
826
  log('[%s] no live transport peer id this pass — binding deferred', this.deps.label);
609
- return;
827
+ return false;
610
828
  }
611
829
  await registerMemberPeer(db, { memberKeyPair: keyPair, peerId }, OWN_TRANSACTION);
830
+ return true;
831
+ }
832
+ /**
833
+ * Steps 4 and 5 of the pass, against the party's machines as the control database records
834
+ * them: `true` when nothing was left to write — every live sibling was already bound and no
835
+ * removed machine's binding had to be cleared — so the pass may latch done. A pass that
836
+ * wrote is not settled: the next one re-reads and confirms. Rows that cannot be read settle
837
+ * nothing and move the next pass to the flat poll interval; nothing this machine can do
838
+ * sooner. No seam means no siblings to bind: settled.
839
+ */
840
+ async reconcileSiblings(db, keyPair, rotationPending) {
841
+ const source = this.deps.partyPeers;
842
+ if (!source)
843
+ return true;
844
+ let peers;
845
+ try {
846
+ peers = await source.read();
847
+ }
848
+ catch (error) {
849
+ log('[%s] the party\'s strand peers could not be read — sibling bindings wait for the next poll: %s', this.deps.label, describeThrown(error));
850
+ this.waitForPoll();
851
+ return false;
852
+ }
853
+ const bound = new Set(await listMemberPeers(db, keyPair.publicKeyB64));
854
+ const unbound = peers.live.map((peer) => peer.strandPeerId).filter((peerId) => !bound.has(peerId));
855
+ const stale = peers.removed.filter((peerId) => bound.has(peerId));
856
+ const siblingsBound = await this.bindSiblings(db, keyPair, unbound);
857
+ const removedCleared = await this.clearRemovedMachines(db, keyPair, rotationPending, stale);
858
+ return siblingsBound && removedCleared;
859
+ }
860
+ /**
861
+ * Step 4: bind each of `unbound` under the party's key. Each write is contained on its own,
862
+ * so one sibling's refusal (busy, or a collision with a sibling binding the same id) does
863
+ * not keep the others waiting. `true` iff there was nothing to bind.
864
+ */
865
+ async bindSiblings(db, keyPair, unbound) {
866
+ for (const peerId of unbound) {
867
+ try {
868
+ await registerMemberPeer(db, { memberKeyPair: keyPair, peerId }, OWN_TRANSACTION);
869
+ log('[%s] bound sibling machine %s under the party\'s key', this.deps.label, peerId);
870
+ }
871
+ catch (error) {
872
+ log('[%s] binding sibling machine %s failed — retried next tick: %s', this.deps.label, peerId, describeThrown(error));
873
+ }
874
+ }
875
+ return unbound.length === 0;
876
+ }
877
+ /**
878
+ * Step 5: clear the binding of each of `stale` (removed machines bound under the party's
879
+ * key), through the self branch of {@link removeMemberPeer} — signed by the party key, which
880
+ * is the row's own member key, so any peer id of the party's is reachable this way. Clears
881
+ * nothing while a key rotation is pending for the strand, or while whether one is could not be
882
+ * read, both of which `rotationPending` carries (see the module doc); that is settled, since
883
+ * the loop stays live until the swap re-keys it. `true` iff nothing was left to clear.
884
+ */
885
+ async clearRemovedMachines(db, keyPair, rotationPending, stale) {
886
+ if (stale.length === 0)
887
+ return true;
888
+ if (rotationPending) {
889
+ log('[%s] %d removed machine(s) stay bound: a party key rotation is pending, or whether one is could not be read', this.deps.label, stale.length);
890
+ return true;
891
+ }
892
+ for (const peerId of stale) {
893
+ try {
894
+ await removeMemberPeer(db, { memberKeyPair: keyPair, peerId }, OWN_TRANSACTION);
895
+ log('[%s] cleared the binding of removed machine %s', this.deps.label, peerId);
896
+ }
897
+ catch (error) {
898
+ log('[%s] clearing the binding of removed machine %s failed — retried next tick: %s', this.deps.label, peerId, describeThrown(error));
899
+ }
900
+ }
901
+ return false;
902
+ }
903
+ /** Step 6: re-attempt this machine's own `StrandPeer` row; the seam contains its failures and remembers success. */
904
+ async publishOwnStrandPeer() {
905
+ const peerId = this.deps.getOwnPeerId();
906
+ if (!this.deps.partyPeers || !peerId)
907
+ return;
908
+ try {
909
+ await this.deps.partyPeers.publishOwn(peerId);
910
+ }
911
+ catch (error) {
912
+ log('[%s] publishing this machine\'s StrandPeer row threw — retried next pass: %s', this.deps.label, describeThrown(error));
913
+ }
914
+ }
915
+ /**
916
+ * The done decision, once the member row and the own binding are in place: not while a party
917
+ * key rotation is pending (the loop stays live to notice the pending key seated, and is
918
+ * rebuilt under that key by the swap; logged once per cycle), not while an invitation is still
919
+ * staged (its burn keeps being refused; the loop stays live so a later pass can settle the
920
+ * credential), and not while a sibling step wrote or could not read this pass. Otherwise latch
921
+ * done and stop.
922
+ */
923
+ latchDone(siblingsSettled, rotationPending) {
924
+ if (rotationPending) {
925
+ // NOTE: a rotation the host never finishes (no re-invitation, no by-hand admission) keeps
926
+ // this loop polling flat for good: one control read plus the strand reads of steps 2 to 5
927
+ // per poll interval, per such strand. Fine at party scale; if a party ever carries many
928
+ // strands with rotations pending indefinitely, re-arm on the strand's `Member` table
929
+ // changing instead of polling for the seat.
930
+ if (!this.pendingRotationLogged) {
931
+ this.pendingRotationLogged = true;
932
+ log('[%s] a party key rotation is pending — the loop stays live until the party\'s key is swapped', this.deps.label);
933
+ }
934
+ return;
935
+ }
612
936
  if (this.deps.pendingInvite?.get()) {
613
937
  log('[%s] own MemberPeer binding is in place but an invitation is still staged — not done yet', this.deps.label);
614
938
  return;
615
939
  }
940
+ if (!siblingsSettled) {
941
+ log('[%s] sibling bindings changed or could not be read this pass — confirming next pass', this.deps.label);
942
+ return;
943
+ }
616
944
  this.doneFlag = true;
617
- this.finish('member row and own MemberPeer binding are both in place', false);
945
+ this.finish('member row, own MemberPeer binding and every known sibling binding are in place', false);
946
+ }
947
+ /** Re-arm the next pass on the flat poll interval, for a wait no faster retry can shorten. */
948
+ waitForPoll() {
949
+ this.lastPassIdle = true;
618
950
  }
619
951
  /**
620
952
  * Act on a `consumeInvite` rejection as {@link classifyConsumeFailure} routes it: busy → keep
621
- * the invitation and retry; half-committed → warn and drop; sealed → terminal; dead
622
- * invitation → drop; anything else → retry.
953
+ * the invitation and retry; half-committed → warn and drop; sealed → terminal under the party's
954
+ * own key, but under the pending key only a dead invitation (the party may still be a member
955
+ * under its current key, whose bindings this loop keeps whole, and the rotation stays pending
956
+ * for the life of the row); dead invitation → drop; anything else → retry.
623
957
  */
624
- handleConsumeFailure(error, invite) {
958
+ handleConsumeFailure(error, invite, under) {
625
959
  const failure = classifyConsumeFailure(error);
626
960
  switch (failure.kind) {
627
961
  case 'busy':
@@ -633,6 +967,12 @@ export class StrandMembershipReconciler {
633
967
  case 'sealed':
634
968
  // The staged credential is dead with the seal; drop it so the cache stays honest.
635
969
  this.deps.pendingInvite?.clear(invite);
970
+ if (under === 'pending-key') {
971
+ log('[%s] the strand is sealed, so the party\'s pending key can never be admitted there — the staged '
972
+ + 'invitation is dead and dropped; the rotation stays pending', this.deps.label);
973
+ this.waitForPoll();
974
+ return;
975
+ }
636
976
  this.finish('the strand is sealed — nobody can ever be admitted, so the staged invitation is dead', true);
637
977
  return;
638
978
  case 'dead-invite':
@@ -654,10 +994,14 @@ export class StrandMembershipReconciler {
654
994
  /**
655
995
  * Count an attempted pass that left the invitation staged (whatever stopped it — a
656
996
  * refused or busy write, or a read that threw on a cut-off machine); one that settled
657
- * it, or finished, ends the streak. At {@link UNFINISHED_PASSES_BEFORE_ESCALATION}
658
- * report the PROBABLE blocked re-join.
997
+ * it, or finished, ends the streak. A pass that left it staged on purpose (a rotation
998
+ * pending whose key this machine cannot read) is no attempt: it neither counts nor ends
999
+ * the streak. At {@link UNFINISHED_PASSES_BEFORE_ESCALATION} report the PROBABLE blocked
1000
+ * re-join.
659
1001
  */
660
1002
  noteAttemptOutcome() {
1003
+ if (this.inviteLeftStagedDeliberately)
1004
+ return;
661
1005
  if (this.doneFlag || !this.deps.pendingInvite?.get()) {
662
1006
  this.unfinishedPasses = 0;
663
1007
  return;
@@ -773,7 +1117,7 @@ export class StrandMembershipReconciler {
773
1117
  return;
774
1118
  this.stoppedFlag = true;
775
1119
  this.clearTimer();
776
- log('[%s] membership reconciler stopped%s: %s%s', this.deps.label, this.doneFlag ? ' (done)' : '', reason, permanent ? '' : ' — a fresh invitation re-arms it');
1120
+ log('[%s] membership reconciler stopped%s: %s%s', this.deps.label, this.doneFlag ? ' (done)' : '', reason, permanent ? '' : ' — a fresh invitation or a change to the party\'s machines re-arms it');
777
1121
  }
778
1122
  }
779
1123
  //# sourceMappingURL=strand-membership-reconciler.js.map