@serfab/cadre-core 1.19.1 → 1.20.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 (103) hide show
  1. package/dist/cadre-node.d.ts +53 -14
  2. package/dist/cadre-node.js +97 -30
  3. package/dist/cadre-node.js.map +1 -1
  4. package/dist/control-database.d.ts +2 -1
  5. package/dist/control-database.js +128 -126
  6. package/dist/control-database.js.map +1 -1
  7. package/dist/control-protocol-guard.js +3 -2
  8. package/dist/control-protocol-guard.js.map +1 -1
  9. package/dist/control-stream.js +2 -1
  10. package/dist/control-stream.js.map +1 -1
  11. package/dist/describe-thrown.d.ts +12 -0
  12. package/dist/describe-thrown.js +59 -0
  13. package/dist/describe-thrown.js.map +1 -0
  14. package/dist/edge-node/dissolve.d.ts +1 -1
  15. package/dist/edge-node/dissolve.js +1 -1
  16. package/dist/edge-node/dissolve.js.map +1 -1
  17. package/dist/edge-node/edge-join.js +2 -1
  18. package/dist/edge-node/edge-join.js.map +1 -1
  19. package/dist/edge-node/edge-node.js +2 -1
  20. package/dist/edge-node/edge-node.js.map +1 -1
  21. package/dist/edge-node/strand-move.d.ts +0 -2
  22. package/dist/edge-node/strand-move.js +1 -4
  23. package/dist/edge-node/strand-move.js.map +1 -1
  24. package/dist/edge-node/strands.js +2 -1
  25. package/dist/edge-node/strands.js.map +1 -1
  26. package/dist/enrollment.js +2 -1
  27. package/dist/enrollment.js.map +1 -1
  28. package/dist/index.d.ts +3 -1
  29. package/dist/index.js +3 -0
  30. package/dist/index.js.map +1 -1
  31. package/dist/member-redemption.js +3 -9
  32. package/dist/member-redemption.js.map +1 -1
  33. package/dist/node-local-snapshot.js +2 -1
  34. package/dist/node-local-snapshot.js.map +1 -1
  35. package/dist/peer-dial.js +3 -2
  36. package/dist/peer-dial.js.map +1 -1
  37. package/dist/pending-join-runner.d.ts +29 -2
  38. package/dist/pending-join-runner.js +60 -20
  39. package/dist/pending-join-runner.js.map +1 -1
  40. package/dist/push-notifier-apns.js +8 -7
  41. package/dist/push-notifier-apns.js.map +1 -1
  42. package/dist/push-notifier-fcm.js +6 -5
  43. package/dist/push-notifier-fcm.js.map +1 -1
  44. package/dist/push-notifier-shared.d.ts +0 -2
  45. package/dist/push-notifier-shared.js +4 -4
  46. package/dist/push-notifier-shared.js.map +1 -1
  47. package/dist/relay-reservation.js +4 -3
  48. package/dist/relay-reservation.js.map +1 -1
  49. package/dist/strand-addr-protocol.js +2 -1
  50. package/dist/strand-addr-protocol.js.map +1 -1
  51. package/dist/strand-app-schema-report.d.ts +53 -0
  52. package/dist/strand-app-schema-report.js +77 -0
  53. package/dist/strand-app-schema-report.js.map +1 -0
  54. package/dist/strand-database.d.ts +9 -5
  55. package/dist/strand-database.js +12 -6
  56. package/dist/strand-database.js.map +1 -1
  57. package/dist/strand-first-sync-gate.js +4 -3
  58. package/dist/strand-first-sync-gate.js.map +1 -1
  59. package/dist/strand-formation-protocol.js +4 -3
  60. package/dist/strand-formation-protocol.js.map +1 -1
  61. package/dist/strand-instance-manager.d.ts +8 -2
  62. package/dist/strand-instance-manager.js +8 -6
  63. package/dist/strand-instance-manager.js.map +1 -1
  64. package/dist/strand-membership-reconciler.js +9 -11
  65. package/dist/strand-membership-reconciler.js.map +1 -1
  66. package/dist/strand-move.js +4 -6
  67. package/dist/strand-move.js.map +1 -1
  68. package/dist/strand-offline.d.ts +10 -39
  69. package/dist/strand-offline.js +9 -54
  70. package/dist/strand-offline.js.map +1 -1
  71. package/dist/types.d.ts +7 -5
  72. package/dist/types.js.map +1 -1
  73. package/package.json +8 -8
  74. package/src/cadre-node.ts +11528 -11456
  75. package/src/control-database.ts +5594 -5592
  76. package/src/control-protocol-guard.ts +3 -2
  77. package/src/control-stream.ts +2 -1
  78. package/src/describe-thrown.ts +60 -0
  79. package/src/edge-node/dissolve.ts +2 -1
  80. package/src/edge-node/edge-join.ts +1 -1
  81. package/src/edge-node/edge-node.ts +2 -1
  82. package/src/edge-node/strand-move.ts +1 -5
  83. package/src/edge-node/strands.ts +74 -73
  84. package/src/enrollment.ts +2 -1
  85. package/src/index.ts +924 -917
  86. package/src/member-redemption.ts +3 -9
  87. package/src/node-local-snapshot.ts +2 -1
  88. package/src/peer-dial.ts +605 -604
  89. package/src/pending-join-runner.ts +68 -22
  90. package/src/push-notifier-apns.ts +8 -7
  91. package/src/push-notifier-fcm.ts +6 -5
  92. package/src/push-notifier-shared.ts +5 -5
  93. package/src/relay-reservation.ts +1212 -1211
  94. package/src/strand-addr-protocol.ts +2 -1
  95. package/src/strand-app-schema-report.ts +115 -0
  96. package/src/strand-database.ts +474 -466
  97. package/src/strand-first-sync-gate.ts +600 -599
  98. package/src/strand-formation-protocol.ts +4 -3
  99. package/src/strand-instance-manager.ts +2219 -2210
  100. package/src/strand-membership-reconciler.ts +942 -945
  101. package/src/strand-move.ts +594 -597
  102. package/src/strand-offline.ts +11 -80
  103. package/src/types.ts +2962 -2960
@@ -1,945 +1,942 @@
1
- /**
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.
8
- *
9
- * ## Contract
10
- *
11
- * - **Never blocks or fails bring-up.** Armed by `StrandInstanceManager.buildStrandRuntime`
12
- * right after the strand database initializes (launch AND hibernation resume — the one
13
- * seam where a transport peer id and a live `Database` both exist), and every pass is
14
- * fully contained: a joiner at that instant has typically not synced the founder's rows
15
- * and may lack write quorum, so failure means "retry next tick", never a throw.
16
- * - **Kicked the moment its database appears.** A joining machine's first pass runs while
17
- * the first-sync write gate still withholds `instance.database`, so it finds no database
18
- * and returns at once. `StrandInstanceManager.publishDatabase` calls `reconcile()` as it
19
- * hands the database to the app, which is what makes the join finish about a second after
20
- * the strand becomes writable rather than on the next timer.
21
- * - **Retries fast while the join is unfinished, slowly while it is only waiting.** A pass
22
- * that leaves the join unfinished re-arms on a ladder starting at
23
- * {@link INITIAL_JOIN_RETRY_INTERVAL_MS} and doubling, capped at the configured poll
24
- * interval (default {@link DEFAULT_MEMBERSHIP_RECONCILE_INTERVAL_MS}). A pass
25
- * that finds no member row AND no staged invitation is not an unfinished join but a wait
26
- * for someone to admit this party — nothing this machine can do faster — so it re-arms on
27
- * the flat poll interval and resets the ladder. The loop stops on the done state.
28
- * - **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}).
33
- *
34
- * ## One pass
35
- *
36
- * 1. **Self-revocation check.** If the enforcer flags this node's own party as revoked and
37
- * no invitation is staged, stop rather than fight — re-admission arrives (if ever) via
38
- * a fresh formation, which re-arms the loop. With an invitation staged the loop reports
39
- * the dead end (below) and carries on: the redemption is attempted like any other, and a
40
- * 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
49
- * yet synced, or a machine whose party never joined) → keep waiting, escalating to one
50
- * visible warning after {@link IDLE_PASSES_BEFORE_ESCALATION} passes, never throwing.
51
- * 3. **Ensure the binding.** {@link registerMemberPeer} (insert-if-absent, restart-safe)
52
- * 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.
56
- *
57
- * ## Stops, and re-arming
58
- *
59
- * Two kinds of stop. A RE-ARMABLE stop is one a fresh invitation should reopen:
60
- *
61
- * - **Done** (above).
62
- * - **Self-revoked with nothing staged** (step 1 above).
63
- *
64
- * A PERMANENT stop is one a fresh invitation changes nothing about — {@link rearm} is a
65
- * no-op after it:
66
- *
67
- * - **Sealed strand**: `consumeInvite` rejected by `ConsumedInvite.NotSealed` — nobody
68
- * can ever be admitted, so retrying forever is noise. Terminal-with-log.
69
- * - **Undecodable party key**: nothing can be signed; loud log, stop.
70
- * - **The public {@link stop}**: `StrandInstanceManager.releaseRuntime` and
71
- * `clearOwnMemberPeerBinding` both call it and mean it — the latter stops the loop and
72
- * awaits {@link settle} precisely so no pass can re-register the binding it is about to
73
- * delete, and a re-arm that restarted the loop would undo that.
74
- *
75
- * `CadreNode.adoptFormationMembershipInvite` stages every fresh invitation and notifies
76
- * the instance manager, which calls {@link rearm}: a done loop reopens and runs one pass
77
- * at once; a running loop is merely kicked. This is what lets a party that was REMOVED
78
- * from the strand, and then handed a new invitation, actually attempt it — the loop
79
- * finished during its first join, long before the removal.
80
- *
81
- * On a removed party the local replica is usually stale: the cohort cut this machine off
82
- * at about the moment the removal was written, so `isStrandMember` still answers true and
83
- * a re-armed pass lands in the already-member arm. That is why the burn arm keeps a
84
- * refused invitation staged and why the done state requires nothing staged — otherwise
85
- * the fresh credential would be dropped on the first refused burn and the loop would latch
86
- * done again, with the only trace a debug line.
87
- *
88
- * A DEAD invitation that is not terminal for the loop — expired, cancelled, or already
89
- * consumed by someone else (`ConsumedInvite`'s primary key) — is dropped with a log and
90
- * the loop keeps idling: a fresh formation stages a new invitation, and a manager-side
91
- * admission (`addMemberByManager`) seats the member row without one.
92
- *
93
- * ## Reporting a blocked re-join
94
- *
95
- * Redeeming (or burning) writes into the strand, and the machines that would carry that
96
- * write are exactly the ones the remaining members refuse once this party is removed. So
97
- * the attempt is expected to fail, and the failure is REPORTED rather than left to the
98
- * ladder: one `console.warn` plus the {@link StrandMembershipReconcilerDeps.onRejoinBlocked}
99
- * callback (`CadreNode`'s `strand:rejoin-blocked` event), at most once per re-arm cycle.
100
- * Two triggers:
101
- *
102
- * - **Confirmed** — a pass finds this party self-revoked AND an invitation staged. The node
103
- * knows it was removed and is holding a credential it cannot spend.
104
- * - **Probable** — {@link UNFINISHED_PASSES_BEFORE_ESCALATION} consecutive attempted passes
105
- * left the invitation staged. The case that matters most in the field: a removed party
106
- * that never learned it was removed (the removal did not replicate here before the cut).
107
- * It is a suspicion, not a verdict — the invitation's `Invite` row may simply not have
108
- * replicated here yet — and the warning names both causes.
109
- *
110
- * The remedy in either case is a remaining manager admitting this party's member key
111
- * directly (`addMemberByManager`): that lifts the refusal, replication resumes, and the
112
- * still-running loop sees the member row, burns the leftover credential and finishes by
113
- * itself.
114
- *
115
- * ## Sharing the database with the app
116
- *
117
- * The strand `Database` this loop writes to is the one the app holds. Every write here
118
- * passes `joinOpenTransaction: false`, so it runs as a transaction of its own and never
119
- * joins one the app has open: the writer refuses with `StrandTransactionBusyError`, having
120
- * written nothing, and the pass retries on the ladder. A busy refusal is never read as a
121
- * dead invitation, and a busy burn leaves the invitation staged for the next pass.
122
- *
123
- * A write refused because the strand's offline queue holds transactions
124
- * (`StrandOfflineQueueBusyError`, docs/strands.md → "Offline mode") is a busy refusal too: it
125
- * wrote nothing, and the ladder retries it until the queue drains. A membership commit queued
126
- * behind an app commit anyway (the race that refusal leaves open) can fail with Optimystic's
127
- * `OfflineCommitTimeoutError`, which is an unclassified failure here: a redemption keeps the
128
- * invitation and retries, and a binding is retried by the next pass. Each pass reads the state
129
- * before it writes (the member row, then the binding, which is insert-if-absent), so a write that
130
- * landed after all (`sent: true`) is found by that pass rather than written twice.
131
- *
132
- * ## Half-committed join
133
- *
134
- * On a networked strand optimystic commits `Member` and `ConsumedInvite` as separate
135
- * collections and can report that only some of them were saved (`CoordinatorPartialCommitError`,
136
- * or the plugin's legacy `PartialCommitError`). When `ConsumedInvite` is saved and `Member` is
137
- * not, the invitation is spent and the schema seats a `Member` through an invitation only in the
138
- * same transaction as a fresh consumption, so this loop can never seat the party from it. Such a
139
- * failure is recognised by TYPE before any message text is read (its message names the
140
- * `ConsumedInvite` collection, which a text match once mistook for a dead invitation), reported
141
- * with ONE `console.warn`, and the invitation is dropped. The loop keeps running like it does
142
- * after a dead invitation: a manager admission, or a `Member` row that did land, is picked up by
143
- * the next pass, which then writes the binding. Whether sereus should repair such a join itself
144
- * is `blocked/strand-half-committed-join-recovery`.
145
- */
146
-
147
- import debug from 'debug';
148
- import type { Database } from '@quereus/quereus';
149
- import { CoordinatorPartialCommitError } from '@optimystic/db-core';
150
- import { PartialCommitError } from '@optimystic/quereus-plugin-optimystic';
151
- import { causeChain } from './control-retry.js';
152
- import type { Ed25519KeyPair } from './ed25519-key.js';
153
- import type { StrandMembershipInvite } from './types.js';
154
- import { strandMemberKeyPair } from './strand-member-key.js';
155
- import {
156
- StrandOfflineQueueBusyError,
157
- StrandTransactionBusyError,
158
- burnInvite,
159
- consumeInvite,
160
- isStrandMember,
161
- registerMemberPeer,
162
- type StrandWriteOptions,
163
- } from './strand-membership-writer.js';
164
- import { defaultTimeoutScheduler, type TimeoutScheduler } from './timeout-scheduler.js';
165
-
166
- const log = debug('sereus:cadre:strand-membership-reconciler');
167
-
168
- /**
169
- * Default poll interval, ms: the loop's idle cadence while nobody has admitted this party, and
170
- * the cap of its unfinished-join retry ladder. The loop stops once joined, so this matters only
171
- * while a machine is joining.
172
- */
173
- export const DEFAULT_MEMBERSHIP_RECONCILE_INTERVAL_MS = 30_000;
174
-
175
- /**
176
- * Idle passes (no member row, no staged invitation) before ONE `console.warn`
177
- * escalation — at the default 30 s cadence, about five minutes of waiting. The loop
178
- * keeps retrying quietly after it; the warning exists so a joiner stuck waiting on
179
- * founder-row replication is visible without the debug namespace enabled.
180
- */
181
- export const IDLE_PASSES_BEFORE_ESCALATION = 10;
182
-
183
- /**
184
- * Consecutive passes that ran against a live database and ended with the staged
185
- * invitation still unsettled — whatever refused it — before the loop reports a probable
186
- * blocked re-join (see "Reporting a blocked re-join" in the module doc). The same order
187
- * as {@link IDLE_PASSES_BEFORE_ESCALATION}: about three minutes at the default cadence
188
- * (the ladder's five doubling rungs, then five passes at the 30 s cap). Counted by outcome
189
- * rather than by classified failure because a cut-off machine can fail before any write is
190
- * classified: its membership READ may already throw.
191
- */
192
- export const UNFINISHED_PASSES_BEFORE_ESCALATION = 10;
193
-
194
- /**
195
- * First retry delay, ms, for a pass that left the join UNFINISHED — a `consumeInvite`
196
- * whose `Strand.Invite` row has not replicated to this machine yet, a cohort briefly
197
- * unwritable, a database not yet published. Doubles per such pass up to the configured
198
- * poll interval. Sized for what it retries: invite-row replication resolves in about a
199
- * second over a direct connection and a few over a relay. The poll interval is NOT sized
200
- * for that — it is sized for the idle case (waiting to be admitted at all), which is why
201
- * this ladder exists instead of a shorter interval.
202
- */
203
- export const INITIAL_JOIN_RETRY_INTERVAL_MS = 1_000;
204
-
205
- /** Every write this loop makes runs in a transaction of its own — see "Sharing the database with the app". */
206
- const OWN_TRANSACTION: StrandWriteOptions = { joinOpenTransaction: false };
207
-
208
- /**
209
- * The `consumeInvite` rejection that means the strand is SEALED — `ConsumedInvite.NotSealed`
210
- * fired, which Quereus renders `CHECK constraint failed: NotSealed (<its expression>)`.
211
- * Terminal for a non-member: nobody can ever be admitted again.
212
- */
213
- const SEALED_REJECTION = /CHECK constraint failed: NotSealed\b/;
214
-
215
- /**
216
- * `consumeInvite` rejections that mean the INVITATION is dead but the loop should keep
217
- * waiting for membership to arrive another way: expired (`CHECK constraint failed: NotExpired`),
218
- * cancelled (`CHECK constraint failed: NotCancelled`), or already consumed by someone else
219
- * (`UNIQUE constraint failed: ConsumedInvite.InviteKey`, the primary key).
220
- *
221
- * Anchored to the engine's full constraint-failure texts, not the bare names: other failures
222
- * embed those names — a half-committed join's message names the `default/strand/ConsumedInvite`
223
- * collection, which the bare `ConsumedInvite` this used to match read as a dead invitation. The
224
- * texts are pinned against the real engine in `strand-membership-reconciler.spec.ts`, so a
225
- * rewording in Quereus fails a spec instead of silently turning a dead invitation into an
226
- * endless retry.
227
- */
228
- const DEAD_INVITE_REJECTION =
229
- /CHECK constraint failed: (?:NotExpired|NotCancelled)\b|UNIQUE constraint failed: ConsumedInvite\.InviteKey\b/;
230
-
231
- /**
232
- * A redemption only part of which was saved: the collections (or, on the plugin's legacy
233
- * path, tree labels) that were saved and those that were not, as the error reports them.
234
- */
235
- export interface HalfCommittedJoin {
236
- kind: 'half-committed';
237
- saved: readonly string[];
238
- unsaved: readonly string[];
239
- }
240
-
241
- /** Where {@link classifyConsumeFailure} routes a failed `consumeInvite` or `burnInvite`. */
242
- export type ConsumeFailure =
243
- | HalfCommittedJoin
244
- /**
245
- * The app had a transaction open, or the strand's offline queue held transactions, so nothing
246
- * was tried — keep the invitation, retry.
247
- */
248
- | { kind: 'busy' }
249
- /** The strand is sealed — terminal for a non-member; a member's leftover invitation is merely dead. */
250
- | { kind: 'sealed' }
251
- /** Expired, cancelled, or consumed by someone else — drop the invitation, keep waiting. */
252
- | { kind: 'dead-invite' }
253
- /**
254
- * Anything else — the `Invite` row has not replicated here yet, or the cohort refused the
255
- * write (a removed party's machines are denied) — keep the invitation, retry.
256
- */
257
- | { kind: 'retry' };
258
-
259
- /**
260
- * Route a `consumeInvite` or `burnInvite` rejection. Both write the `Strand.ConsumedInvite`
261
- * row under the same `NotExpired` / `NotCancelled` / `NotSealed` / primary-key constraints
262
- * (a burn writes that row alone), so one classifier serves both. Typed checks run before any
263
- * text check: a busy refusal (another transaction was open, so nothing ran) and a
264
- * half-committed join are recognised by their error's type anywhere in the `cause` chain.
265
- * The busy refusal carries Quereus's own refusal as its cause, and a half-committed join's
266
- * message embeds collection names and the underlying failure's text, either of which a text
267
- * matcher can misread. The sealed and dead-invitation checks then read the top-level message.
268
- *
269
- * A second loaded copy of `@optimystic/db-core` (or of the plugin) would fail `instanceof`; the
270
- * half-commit then falls through the anchored texts to `retry`, and once the saved `ConsumedInvite`
271
- * row is visible here a later attempt fails on its primary key and drops the invitation quietly —
272
- * the old silent outcome, a few passes later, never a wrong write.
273
- */
274
- export function classifyConsumeFailure(error: unknown): ConsumeFailure {
275
- if (isTransactionBusy(error)) return { kind: 'busy' };
276
- const halfCommitted = halfCommittedJoin(error);
277
- if (halfCommitted) return halfCommitted;
278
- const message = errorMessage(error);
279
- if (SEALED_REJECTION.test(message)) return { kind: 'sealed' };
280
- if (DEAD_INVITE_REJECTION.test(message)) return { kind: 'dead-invite' };
281
- return { kind: 'retry' };
282
- }
283
-
284
- /**
285
- * The first partial-commit error in the `cause` chain, as the lists it reports.
286
- *
287
- * NOTE: `PartialCommitError` is imported from the plugin's root entry while strands register the
288
- * plugin through its `/plugin` entry (`quereus-plugin-sereus`'s `compose-strand.ts`); the two are
289
- * one class only because the plugin's build emits both entries over one shared chunk — the same
290
- * dependency, and the same remedy if upstream ever bundles them apart, as the NOTE on
291
- * `reportsPossiblyStoredWrite` in `control-write-retry.ts`.
292
- */
293
- function halfCommittedJoin(error: unknown): HalfCommittedJoin | undefined {
294
- for (const link of causeChain(error)) {
295
- if (link instanceof CoordinatorPartialCommitError) {
296
- return { kind: 'half-committed', saved: link.committedCollections, unsaved: link.failedCollections };
297
- }
298
- if (link instanceof PartialCommitError) {
299
- return { kind: 'half-committed', saved: link.persisted, unsaved: link.unpersisted };
300
- }
301
- }
302
- return undefined;
303
- }
304
-
305
- /**
306
- * Whether a writer refused having written nothing, because another transaction was open or the
307
- * offline queue held transactions (see "Sharing the database with the app").
308
- */
309
- function isTransactionBusy(error: unknown): boolean {
310
- return causeChain(error).some((link) =>
311
- link instanceof StrandTransactionBusyError || link instanceof StrandOfflineQueueBusyError);
312
- }
313
-
314
- function errorMessage(error: unknown): string {
315
- return error instanceof Error ? error.message : String(error);
316
- }
317
-
318
- /**
319
- * The staged formation invitation seam — `CadreNode`'s in-memory
320
- * `pendingMembershipInvites` cache, scoped to one strand. Read lazily per pass (a
321
- * re-formation may replace the entry between passes) and cleared by the reconciler once
322
- * the invitation is spent, burned, or dead — the invalidation half the cache itself
323
- * deliberately does not own.
324
- */
325
- export interface PendingMembershipInviteSource {
326
- /** The staged invitation, or `undefined` when none is pending for this strand. */
327
- get(): StrandMembershipInvite | undefined;
328
- /**
329
- * Drop `settled` (spent, burned, or dead) — only if it is still the staged one. A
330
- * re-formation can replace the entry between a pass's {@link get} and this call, and
331
- * the fresh invitation it staged must survive the older one being settled.
332
- */
333
- clear(settled: StrandMembershipInvite): void;
334
- }
335
-
336
- export interface StrandMembershipReconcilerDeps {
337
- /** Log tag naming which strand this reconciler serves (the strand id). */
338
- label: string;
339
- /**
340
- * THIS party's own strand membership private key (base64 protobuf, the control-layer
341
- * `StrandPartyKey` row's content). Decoded LAZILY on the first pass, so a malformed
342
- * key stops the loop with a log instead of failing bring-up.
343
- */
344
- partyMemberPrivateKey: string;
345
- /**
346
- * The live strand `Database`, read per pass, never captured — the instance's handle
347
- * is dropped on quiesce, and `undefined` means "no live database this instant" (the
348
- * pass simply waits for the next tick).
349
- */
350
- getDatabase: () => Database | undefined;
351
- /**
352
- * This node's own strand transport peer id — the `MemberPeer.PeerId` to bind. Read
353
- * per pass for the same lifecycle reason as {@link getDatabase}.
354
- */
355
- getOwnPeerId: () => string | undefined;
356
- /** The staged invitation seam. Absent for flows with no invitation (e.g. tests). */
357
- pendingInvite?: PendingMembershipInviteSource;
358
- /**
359
- * Whether the revocation enforcer currently flags THIS node's own party as revoked.
360
- * When it does and nothing is staged, the loop stops rather than fight the enforcer;
361
- * with an invitation staged it reports the blocked re-join and keeps trying — see the
362
- * module doc. Absent (enforcement disarmed) means "not known revoked".
363
- */
364
- isSelfRevoked?: () => boolean;
365
- /**
366
- * Called when the loop reports a blocked re-join (see "Reporting a blocked re-join" in
367
- * the module doc) — at most once per re-arm cycle, after the `console.warn`. `CadreNode`
368
- * wires it to its `strand:rejoin-blocked` event.
369
- */
370
- onRejoinBlocked?: () => void;
371
- /**
372
- * Timer seam for the retry ladder; omit for real (unref'd) timeouts. Timeouts rather
373
- * than the enforcer's repeating interval because the delay changes per pass and the next
374
- * pass is armed only once the previous one settles, so a slow pass never stacks ticks
375
- * behind it — the same seam the first-sync gate's probe loop uses.
376
- */
377
- scheduler?: TimeoutScheduler;
378
- }
379
-
380
- /** Embedder-facing tuning, threaded by `StrandInstanceManager`. */
381
- export interface StrandMembershipReconciliationConfig {
382
- /**
383
- * Default true. False disarms the loop entirely — meant for test fixtures that
384
- * hand-drive the membership writers and assert exact row sets; a production
385
- * node that disarms it never seats a joiner's member row or binds its machines.
386
- */
387
- enabled?: boolean;
388
- /**
389
- * Idle cadence, ms — how often the loop re-checks while nobody has admitted this party
390
- * yet — and the CAP of the unfinished-join retry ladder. Default
391
- * {@link DEFAULT_MEMBERSHIP_RECONCILE_INTERVAL_MS}.
392
- */
393
- pollIntervalMs?: number;
394
- }
395
-
396
- /**
397
- * The per-strand membership reconciliation loop. Created in
398
- * `StrandInstanceManager.buildStrandRuntime` (closed strands with a party key only),
399
- * started right after the strand database initializes, stopped and dropped in
400
- * `releaseRuntime` — so quiesce → resume rebuilds it and re-runs the (idempotent) ladder
401
- * from scratch.
402
- */
403
- export class StrandMembershipReconciler {
404
- private readonly scheduler: TimeoutScheduler;
405
- private readonly pollIntervalMs: number;
406
- /** Tail of the pass chain — serializes passes (no two in flight). */
407
- private tail: Promise<void> = Promise.resolve();
408
- private timer: unknown;
409
- private started = false;
410
- private stoppedFlag = false;
411
- /**
412
- * Whether the last stop was one {@link rearm} may not undo — see "Stops, and re-arming"
413
- * in the module doc. Latched by the public {@link stop} and the permanent terminal
414
- * states, never cleared.
415
- */
416
- private permanentlyStopped = false;
417
- private doneFlag = false;
418
- /** Lazily decoded party keypair — see {@link StrandMembershipReconcilerDeps.partyMemberPrivateKey}. */
419
- private keyPair: Ed25519KeyPair | undefined;
420
- private idlePasses = 0;
421
- private idleEscalated = false;
422
- /** Consecutive attempted passes that left the invitation staged — see {@link UNFINISHED_PASSES_BEFORE_ESCALATION}. */
423
- private unfinishedPasses = 0;
424
- /** Whether the blocked re-join was already reported this re-arm cycle (one report, either trigger). */
425
- private rejoinBlockedReported = false;
426
- /**
427
- * Whether the pass that just ran found nothing to act on — no member row and no staged
428
- * invitation. That is a wait to be admitted, not an unfinished join, so it re-arms on the
429
- * flat poll interval; every other unfinished outcome climbs the ladder.
430
- *
431
- * NOTE: the ladder is therefore the DEFAULT for any outcome nobody classified — a new
432
- * early return added to {@link doPass} inherits the fast retry unless it calls
433
- * {@link noteIdlePass}. Right for every outcome that exists today (each is an unfinished
434
- * join this machine can make progress on). If an early return is ever added for a
435
- * condition retrying cannot resolve, classify it idle.
436
- */
437
- private lastPassIdle = false;
438
- /** Current rung of the unfinished-join retry ladder, ms; unset before the first retry. */
439
- private retryDelayMs: number | undefined;
440
-
441
- constructor(
442
- private readonly deps: StrandMembershipReconcilerDeps,
443
- config?: StrandMembershipReconciliationConfig
444
- ) {
445
- this.scheduler = deps.scheduler ?? defaultTimeoutScheduler;
446
- this.pollIntervalMs = config?.pollIntervalMs ?? DEFAULT_MEMBERSHIP_RECONCILE_INTERVAL_MS;
447
- }
448
-
449
- /**
450
- * True once member row + own binding were both confirmed with nothing staged and the
451
- * loop stopped. Cleared again by {@link rearm}.
452
- */
453
- get done(): boolean {
454
- return this.doneFlag;
455
- }
456
-
457
- /** True while the loop is stopped — done, terminal, or externally stopped. */
458
- get stopped(): boolean {
459
- return this.stoppedFlag;
460
- }
461
-
462
- /**
463
- * Kick an immediate pass (not awaited — bring-up never blocks on it). Every later pass
464
- * is armed only once the previous one settles — see the retry ladder in the module doc —
465
- * so there is no repeating interval to arm here.
466
- */
467
- start(): void {
468
- if (this.started || this.stoppedFlag) return;
469
- this.started = true;
470
- void this.reconcile();
471
- log('[%s] membership reconciler started (retry from %dms, idle poll %dms)',
472
- this.deps.label, Math.min(INITIAL_JOIN_RETRY_INTERVAL_MS, this.pollIntervalMs), this.pollIntervalMs);
473
- }
474
-
475
- /**
476
- * Resolve once no pass is in flight. {@link stop} only disarms the retry TIMER — a pass
477
- * already past its stopped check runs to completion, so a caller that must know the
478
- * loop can no longer write (`StrandInstanceManager.clearOwnMemberPeerBinding`, which
479
- * would otherwise have its removal undone by a racing `registerMemberPeer`) awaits
480
- * this after stopping. Never rejects: the pass chain contains every failure.
481
- */
482
- async settle(): Promise<void> {
483
- await this.tail;
484
- }
485
-
486
- /**
487
- * Disarm the retry timer, for good: a later {@link rearm} is refused. A pass already in
488
- * flight completes but writes idempotently — {@link settle} is what waits it out.
489
- */
490
- stop(): void {
491
- this.halt('stopped by the runtime', true);
492
- }
493
-
494
- /**
495
- * A fresh invitation was staged: reopen a loop that stopped on a re-armable state (done,
496
- * or self-revoked with nothing staged) and run one pass at once; merely kick a loop that
497
- * is still running; do nothing after a permanent stop. Never rejects, and serialized
498
- * like {@link reconcile}: the reopen happens when the queued pass STARTS, after any pass
499
- * in flight has settled, so a `done` that pass latches cannot swallow the re-arm — and a
500
- * public {@link stop} that lands first still wins, because the queued pass re-checks it.
501
- */
502
- rearm(): Promise<void> {
503
- return this.enqueue(() => this.reopen() ? this.doPass() : Promise.resolve());
504
- }
505
-
506
- /**
507
- * Run one pass now. Never rejects. Serialized: concurrent calls chain, so no two
508
- * passes overlap and each explicit call gets a pass that STARTS after the call. On a
509
- * started loop the pass re-arms the retry timer where it settles, so an explicit call —
510
- * `StrandInstanceManager.publishDatabase`'s kick when a joiner's database is finally
511
- * published — REPLACES the pending timer rather than running alongside it.
512
- */
513
- reconcile(): Promise<void> {
514
- return this.enqueue(() => this.doPass());
515
- }
516
-
517
- /** Chain `pass` after every pass already queued; the tail never rejects. */
518
- private enqueue(pass: () => Promise<void>): Promise<void> {
519
- // The catch is what keeps the chain alive. `doPass` contains its own failures, but its
520
- // `finally` calls into the injected scheduler, and a throw from there would leave `tail`
521
- // REJECTED — after which every later `reconcile()` short-circuits on it and the join
522
- // stalls for good, silently. Swallowing it here makes the "never rejects" contract
523
- // {@link reconcile}, {@link rearm}, {@link settle} and the `void`-ed call sites all rely
524
- // on structural rather than incidental.
525
- const run = this.tail.then(pass).catch((error) => {
526
- log('[%s] reconcile pass threw outside its own handler — the chain continues: %o',
527
- this.deps.label, error);
528
- });
529
- this.tail = run;
530
- return run;
531
- }
532
-
533
- /**
534
- * The re-arm itself, run at the head of the queued pass: `false` refuses the pass (a
535
- * permanent stop), a running loop is left as it is, and a re-armable stop is reopened
536
- * with the idle and unfinished counters, both escalation latches and the retry ladder
537
- * reset — a fresh invitation is a fresh cycle.
538
- */
539
- private reopen(): boolean {
540
- if (this.permanentlyStopped) {
541
- log('[%s] re-arm refused — the loop is stopped for good', this.deps.label);
542
- return false;
543
- }
544
- if (!this.stoppedFlag) {
545
- // NOTE: a running loop keeps its counters and its once-per-cycle report latch, so a
546
- // party whose loop already reported and is then re-formed AGAIN gets no second report
547
- // for the replacement invitation. If that second report is ever wanted, key the latch
548
- // on the staged invitation's key rather than on the re-arm.
549
- log('[%s] fresh invitation staged on a running loop — kicking a pass', this.deps.label);
550
- return true;
551
- }
552
- this.stoppedFlag = false;
553
- this.doneFlag = false;
554
- this.idlePasses = 0;
555
- this.idleEscalated = false;
556
- this.unfinishedPasses = 0;
557
- this.rejoinBlockedReported = false;
558
- this.retryDelayMs = undefined;
559
- log('[%s] membership reconciler re-armed by a fresh invitation', this.deps.label);
560
- return true;
561
- }
562
-
563
- /** One serialized pass; contains every failure (contract: never rejects). */
564
- private async doPass(): Promise<void> {
565
- if (this.stoppedFlag || this.doneFlag) return;
566
- this.lastPassIdle = false;
567
- try {
568
- if (this.deps.isSelfRevoked?.() === true && !this.stagedInviteBlockedBySelfRevocation()) {
569
- // NOTE: the enforcer's flag lags a re-admission by up to one of its polls. If the
570
- // pass that settled the last staged invitation then failed to write the binding, this
571
- // stop lands with the binding missing until the next resume rebuilds the loop. A
572
- // missing binding only mis-credits diversity today; if it ever gates admission, make
573
- // this stop also require the binding to be in place.
574
- this.finish('this party is revoked from the strand — re-admission arrives (if ever) via a fresh formation', false);
575
- return;
576
- }
577
- const keyPair = this.resolveKeyPair();
578
- if (!keyPair) return; // undecodable key already stopped the loop
579
- const db = this.deps.getDatabase();
580
- if (!db) return; // no live database this instant (quiesce race) — next tick decides
581
- await this.attempt(db, keyPair);
582
- } catch (error) {
583
- log('[%s] reconcile pass failed — retrying next tick: %o', this.deps.label, error);
584
- } finally {
585
- this.scheduleNext();
586
- }
587
- }
588
-
589
- /**
590
- * Steps 2 and 3 against a live database, with the outcome counted toward the probable
591
- * blocked re-join report whether the attempt returned or threw.
592
- */
593
- private async attempt(db: Database, keyPair: Ed25519KeyPair): Promise<void> {
594
- try {
595
- if (!(await this.ensureMembership(db, keyPair))) return;
596
- // NOTE: accepted tradeoff — the redemption (`Member` + `ConsumedInvite`) and the binding
597
- // below stay two SEPARATE commits on purpose. Merging them would save one commit: its
598
- // serial latency and, since Optimystic 1.19.0 pends and commits a transaction's collections
599
- // together, its `/cluster` requests (the two commits cost 6 on a two-member strand in
600
- // `message-cost-accounting` on 2026-10-25, 20 before). It would also let a torn commit
601
- // (Optimystic can report a multi-collection commit partly saved) or the cohort applying
602
- // the collections out of order show this machine's `MemberPeer` without its `Member`,
603
- // which the revocation enforcer reads as a removed member and hangs up on — fail closed,
604
- // undone only by a manager clearing the binding (module doc of
605
- // `strand-revocation-enforcer.ts`). And it would add a half-committed shape (`MemberPeer`
606
- // saved, the invitation still live) that {@link reportHalfCommittedJoin}'s dropping of the
607
- // invitation gets wrong. Revisit when Optimystic offers an all-or-nothing multi-collection
608
- // commit, or when the enforcer can tell a not-yet-seated binding from a removed member's.
609
- await this.ensureBinding(db, keyPair);
610
- } finally {
611
- this.noteAttemptOutcome();
612
- }
613
- }
614
-
615
- /**
616
- * Arm the next pass, now that this one has settled — so a slow pass never stacks ticks
617
- * behind it. Only a STARTED loop schedules: a caller driving {@link reconcile} by hand
618
- * (the unit tests, and the publish kick on a launch whose `start()` has not run yet) gets
619
- * exactly the passes it asks for and no background timer.
620
- */
621
- private scheduleNext(): void {
622
- if (!this.started || this.stoppedFlag || this.doneFlag) return;
623
- this.clearTimer();
624
- const delayMs = this.nextDelayMs();
625
- this.timer = this.scheduler.setTimeout(() => {
626
- this.timer = undefined;
627
- void this.reconcile();
628
- }, delayMs);
629
- }
630
-
631
- /**
632
- * The delay before the next pass: the flat poll interval while the loop is merely idling
633
- * (no member row, no staged invitation — {@link noteIdlePass}), otherwise the next rung
634
- * of the doubling ladder from {@link INITIAL_JOIN_RETRY_INTERVAL_MS}, capped at the poll
635
- * interval. A pass that lands idle resets the ladder, so a later unfinished join starts
636
- * over at the bottom rung.
637
- */
638
- private nextDelayMs(): number {
639
- if (this.lastPassIdle) {
640
- this.retryDelayMs = undefined;
641
- return this.pollIntervalMs;
642
- }
643
- this.retryDelayMs = Math.min(
644
- this.retryDelayMs === undefined ? INITIAL_JOIN_RETRY_INTERVAL_MS : this.retryDelayMs * 2,
645
- this.pollIntervalMs
646
- );
647
- return this.retryDelayMs;
648
- }
649
-
650
- private clearTimer(): void {
651
- if (this.timer !== undefined) {
652
- this.scheduler.clearTimeout(this.timer);
653
- this.timer = undefined;
654
- }
655
- }
656
-
657
- /**
658
- * Step 2 of the pass: `true` iff the party's member row is visible locally by the
659
- * time this returns (already present, or seated by redeeming the staged invitation).
660
- */
661
- private async ensureMembership(db: Database, keyPair: Ed25519KeyPair): Promise<boolean> {
662
- if (await isStrandMember(db, keyPair.publicKeyB64)) {
663
- await this.burnLeftoverInvite(db, keyPair);
664
- return true;
665
- }
666
- const invite = this.deps.pendingInvite?.get();
667
- if (!invite) {
668
- this.noteIdlePass();
669
- return false;
670
- }
671
- try {
672
- await consumeInvite(db, {
673
- inviteKey: invite.inviteKey,
674
- invitePrivateKey: invite.invitePrivateKey,
675
- memberKey: keyPair.publicKeyB64,
676
- }, OWN_TRANSACTION);
677
- } catch (error) {
678
- this.handleConsumeFailure(error, invite);
679
- return false;
680
- }
681
- this.deps.pendingInvite?.clear(invite);
682
- log('[%s] redeemed the staged membership invitation — Member row seated under this party\'s key', this.deps.label);
683
- return true;
684
- }
685
-
686
- /**
687
- * The already-member arm: spend a still-staged invitation so nobody else can. The stage
688
- * is cleared once the burn lands or the invitation is known dead (already spent,
689
- * cancelled, expired, or the strand sealed around a party that is still a member) — with
690
- * the member row present a dead credential has no further local use, and keeping it
691
- * staged would leave `getPendingMembershipInvite` lying. A refused burn keeps it staged:
692
- * a busy refusal tried nothing, and a write the cohort refused is the removed-party shape
693
- * ("Stops, and re-arming" in the module doc), where the local member row is stale and the
694
- * credential is the one thing a later manager admission lets this loop settle.
695
- *
696
- * NOTE: this REPLACES an earlier accepted tradeoff that never retried a burn which failed
697
- * for a transient reason and dropped the invitation instead. That decision was made when
698
- * this arm could only ever see an invitation staged before the first join finished, so a
699
- * dropped credential cost nothing but a spendable bearer token. {@link rearm} makes the
700
- * arm reachable with a freshly issued invitation the app wants redeemed, and dropping
701
- * that one on the first refused write is the silent failure this loop exists to avoid.
702
- */
703
- private async burnLeftoverInvite(db: Database, keyPair: Ed25519KeyPair): Promise<void> {
704
- const invite = this.deps.pendingInvite?.get();
705
- if (!invite) return;
706
- try {
707
- await burnInvite(db, {
708
- inviteKey: invite.inviteKey,
709
- invitePrivateKey: invite.invitePrivateKey,
710
- memberKey: keyPair.publicKeyB64,
711
- }, OWN_TRANSACTION);
712
- } catch (error) {
713
- this.handleBurnFailure(error, invite);
714
- return;
715
- }
716
- this.deps.pendingInvite?.clear(invite);
717
- log('[%s] burned the leftover invitation (member row already present)', this.deps.label);
718
- }
719
-
720
- /**
721
- * Act on a `burnInvite` rejection as {@link classifyConsumeFailure} routes it. Unlike a
722
- * redemption, a sealed strand is not terminal here — the member row is present, so this
723
- * party is a member of the sealed strand and only its leftover credential is dead — and a
724
- * half-committed burn (one collection, so a report of it means the commit's durability
725
- * was in doubt) is retried: the next pass either lands it or fails on the row's primary
726
- * key, which drops it as dead.
727
- */
728
- private handleBurnFailure(error: unknown, invite: StrandMembershipInvite): void {
729
- const failure = classifyConsumeFailure(error);
730
- switch (failure.kind) {
731
- case 'busy':
732
- log('[%s] burning the leftover invitation deferred — nothing was tried; it stays staged for the next '
733
- + 'pass: %s', this.deps.label, errorMessage(error));
734
- return;
735
- case 'sealed':
736
- case 'dead-invite':
737
- log('[%s] the leftover invitation is dead (already spent, cancelled, expired, or the strand sealed) — '
738
- + 'dropping it: %s', this.deps.label, errorMessage(error));
739
- this.deps.pendingInvite?.clear(invite);
740
- return;
741
- case 'half-committed':
742
- case 'retry':
743
- log('[%s] burning the leftover invitation was refused — it stays staged and is retried next tick '
744
- + '(the cohort refusing this machine, or a transient write failure): %s', this.deps.label, errorMessage(error));
745
- return;
746
- }
747
- }
748
-
749
- /**
750
- * Step 3 of the pass: write this machine's own `MemberPeer` binding (insert-if-absent)
751
- * and, once it is in place with nothing staged, latch the done state and stop the loop.
752
- * A missing transport peer id (a quiesce racing the pass) defers to the next tick; a
753
- * write failure — a busy refusal included — is contained by the pass's outer catch and
754
- * retried. A binding written while an invitation is still staged (its burn keeps being
755
- * refused) is not done: the loop stays live so a later pass can settle the credential.
756
- */
757
- private async ensureBinding(db: Database, keyPair: Ed25519KeyPair): Promise<void> {
758
- const peerId = this.deps.getOwnPeerId();
759
- if (!peerId) {
760
- log('[%s] no live transport peer id this pass — binding deferred', this.deps.label);
761
- return;
762
- }
763
- await registerMemberPeer(db, { memberKeyPair: keyPair, peerId }, OWN_TRANSACTION);
764
- if (this.deps.pendingInvite?.get()) {
765
- log('[%s] own MemberPeer binding is in place but an invitation is still staged — not done yet', this.deps.label);
766
- return;
767
- }
768
- this.doneFlag = true;
769
- this.finish('member row and own MemberPeer binding are both in place', false);
770
- }
771
-
772
- /**
773
- * Act on a `consumeInvite` rejection as {@link classifyConsumeFailure} routes it: busy → keep
774
- * the invitation and retry; half-committed → warn and drop; sealed → terminal; dead
775
- * invitation → drop; anything else → retry.
776
- */
777
- private handleConsumeFailure(error: unknown, invite: StrandMembershipInvite): void {
778
- const failure = classifyConsumeFailure(error);
779
- switch (failure.kind) {
780
- case 'busy':
781
- log('[%s] redeeming the staged invitation deferred — nothing was tried; retrying next tick: %s',
782
- this.deps.label, errorMessage(error));
783
- return;
784
- case 'half-committed':
785
- this.reportHalfCommittedJoin(failure, error, invite);
786
- return;
787
- case 'sealed':
788
- // The staged credential is dead with the seal; drop it so the cache stays honest.
789
- this.deps.pendingInvite?.clear(invite);
790
- this.finish('the strand is sealed — nobody can ever be admitted, so the staged invitation is dead', true);
791
- return;
792
- case 'dead-invite':
793
- // NOTE: accepted tradeoff — dropping a dead invitation does not mark the pass idle,
794
- // so the next attempt is one ladder rung away rather than a full poll interval. Kept:
795
- // the pass AFTER it finds no member row and no invitation, marks itself idle, and
796
- // re-arms flat, so the cost is one extra read per dead credential. Revisit if a
797
- // source of dead invitations ever repeats per pass.
798
- log('[%s] the staged invitation is dead (expired, cancelled, or consumed elsewhere) — dropping it; '
799
- + 'a fresh formation stages a new one: %s', this.deps.label, errorMessage(error));
800
- this.deps.pendingInvite?.clear(invite);
801
- return;
802
- case 'retry':
803
- log('[%s] consumeInvite failed — retrying next tick (Invite row not yet replicated here, the cohort '
804
- + 'refusing this machine, or a transient write failure): %s', this.deps.label, errorMessage(error));
805
- return;
806
- }
807
- }
808
-
809
- /**
810
- * Count an attempted pass that left the invitation staged (whatever stopped it — a
811
- * refused or busy write, or a read that threw on a cut-off machine); one that settled
812
- * it, or finished, ends the streak. At {@link UNFINISHED_PASSES_BEFORE_ESCALATION}
813
- * report the PROBABLE blocked re-join.
814
- */
815
- private noteAttemptOutcome(): void {
816
- if (this.doneFlag || !this.deps.pendingInvite?.get()) {
817
- this.unfinishedPasses = 0;
818
- return;
819
- }
820
- this.unfinishedPasses += 1;
821
- if (this.unfinishedPasses >= UNFINISHED_PASSES_BEFORE_ESCALATION) {
822
- this.reportRejoinBlocked(
823
- `${this.unfinishedPasses} membership reconcile passes have left the staged membership invitation `
824
- + 'unsettled. Either this party was removed from the strand and the remaining members are refusing its '
825
- + 'machines, or the invitation\'s Strand.Invite row has not replicated here yet.'
826
- );
827
- }
828
- }
829
-
830
- /**
831
- * Step 1's CONFIRMED trigger: self-revoked with an invitation staged. Reports (once per
832
- * re-arm cycle) and answers `true` so the pass carries on — the redemption is attempted
833
- * and refused like any other write, and a manager's re-admission lets a later pass finish.
834
- * `false` (nothing staged) means step 1 stops the loop as before.
835
- */
836
- private stagedInviteBlockedBySelfRevocation(): boolean {
837
- if (!this.deps.pendingInvite?.get()) return false;
838
- this.reportRejoinBlocked(
839
- 'this party is revoked from the strand and holds a staged membership invitation it cannot spend: the '
840
- + 'remaining members refuse this machine\'s strand writes, so the redemption cannot land.'
841
- );
842
- return true;
843
- }
844
-
845
- /**
846
- * ONE `console.warn` and one callback per re-arm cycle, whichever trigger fires first —
847
- * see "Reporting a blocked re-join" in the module doc. `cause` is the trigger's own
848
- * sentence; the remedy and the loop's posture are the same for both.
849
- */
850
- private reportRejoinBlocked(cause: string): void {
851
- if (this.rejoinBlockedReported) return;
852
- this.rejoinBlockedReported = true;
853
- console.warn(
854
- `[sereus] strand ${this.deps.label}: ${cause} A fresh invitation cannot re-admit a removed party by itself — `
855
- + 'a remaining manager must admit this party\'s member key directly (addMemberByManager). The membership '
856
- + 'loop keeps retrying quietly and completes the join once a Member row for this party appears.'
857
- );
858
- this.deps.onRejoinBlocked?.();
859
- }
860
-
861
- /**
862
- * A redemption only part of which was saved (see "Half-committed join" in the module doc):
863
- * ONE visible warning naming both halves, and the staged invitation dropped. The pass is not
864
- * marked idle, so the next one runs a ladder rung later and either finds a `Member` row (a
865
- * saved one, or a manager's admission) and writes the binding, or idles flat.
866
- *
867
- * NOTE: the invitation is dropped whichever half was saved. In the observed shape
868
- * (`ConsumedInvite` saved, `Member` not) it is spent and a retry could only fail on
869
- * `ConsumedInvite`'s primary key. In the opposite shape (`Member` saved, `ConsumedInvite` not)
870
- * keeping it would let the already-member arm burn it; dropping it leaves that bearer
871
- * credential spendable until it expires — the state the burn arm's accepted tradeoff already
872
- * lands in. Not branched on, because telling the shapes apart means parsing the lists, which
873
- * are collection ids on the coordinator path but free-form tree labels on the plugin's legacy
874
- * path. Revisit if a `Member`-saved half-commit is ever observed, or when
875
- * `blocked/strand-half-committed-join-recovery` is decided.
876
- */
877
- private reportHalfCommittedJoin(failure: HalfCommittedJoin, error: unknown, invite: StrandMembershipInvite): void {
878
- console.warn(
879
- `[sereus] strand ${this.deps.label}: redeeming the staged membership invitation was only partly saved. `
880
- + `Saved: [${failure.saved.join(', ')}]. Not saved: [${failure.unsaved.join(', ')}]. `
881
- + 'The invitation is dropped: a saved ConsumedInvite row spends it, so it cannot be redeemed again. '
882
- + 'If this party\'s Member row is not among the saved, the party is not a member of the strand and '
883
- + 'cannot become one from this invitation — a manager must admit it directly (addMemberByManager). '
884
- + 'The membership loop keeps checking and completes the join once a Member row for this party appears.'
885
- );
886
- log('[%s] half-committed redemption, full error: %o', this.deps.label, error);
887
- this.deps.pendingInvite?.clear(invite);
888
- // The idle passes that follow are the wait this warning already explained; the escalation's
889
- // "waiting on the founder rows to replicate" would be a second, misleading warning.
890
- this.idleEscalated = true;
891
- }
892
-
893
- /** Decode the party key once; an undecodable key is terminal (nothing can be signed). */
894
- private resolveKeyPair(): Ed25519KeyPair | undefined {
895
- if (this.keyPair) return this.keyPair;
896
- try {
897
- this.keyPair = strandMemberKeyPair(this.deps.partyMemberPrivateKey);
898
- } catch (error) {
899
- this.finish(`the party membership key does not decode — nothing can be signed (${errorMessage(error)})`, true);
900
- return undefined;
901
- }
902
- return this.keyPair;
903
- }
904
-
905
- /**
906
- * Count a no-member/no-invitation pass; escalate to ONE visible warning at the bound.
907
- *
908
- * NOTE: an idling loop never gives up — a machine whose party is never admitted keeps
909
- * polling for the life of the process, one `Strand.Member` scan per strand per
910
- * interval (30 s by default). Negligible at the handful of strands a device runs and
911
- * the handful of members a strand has; if a node ever runs strands by the hundred, or
912
- * a strand's member set grows large, bound the idle phase (give up after N passes and
913
- * surface it) rather than shortening the interval.
914
- */
915
- private noteIdlePass(): void {
916
- this.lastPassIdle = true;
917
- this.idlePasses += 1;
918
- if (this.idlePasses >= IDLE_PASSES_BEFORE_ESCALATION && !this.idleEscalated) {
919
- this.idleEscalated = true;
920
- console.warn(
921
- `[sereus] strand ${this.deps.label}: ${this.idlePasses} membership reconcile passes and still no `
922
- + 'Member row for this party and no staged invitation — a joiner is waiting on the founder rows to '
923
- + 'replicate (or on a manager admission). The loop keeps retrying quietly.'
924
- );
925
- }
926
- }
927
-
928
- /**
929
- * Stop with a reason — the terminal and done paths' shared exit. `permanent` says whether
930
- * a fresh invitation may reopen the loop ("Stops, and re-arming" in the module doc).
931
- */
932
- private finish(reason: string, permanent: boolean): void {
933
- this.halt(`membership reconciliation stopping: ${reason}`, permanent);
934
- }
935
-
936
- /** Latch the stop and disarm the timer; a permanent latch sticks even on an already-stopped loop. */
937
- private halt(reason: string, permanent: boolean): void {
938
- if (permanent) this.permanentlyStopped = true;
939
- if (this.stoppedFlag) return;
940
- this.stoppedFlag = true;
941
- this.clearTimer();
942
- log('[%s] membership reconciler stopped%s: %s%s', this.deps.label, this.doneFlag ? ' (done)' : '', reason,
943
- permanent ? '' : ' — a fresh invitation re-arms it');
944
- }
945
- }
1
+ /**
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.
8
+ *
9
+ * ## Contract
10
+ *
11
+ * - **Never blocks or fails bring-up.** Armed by `StrandInstanceManager.buildStrandRuntime`
12
+ * right after the strand database initializes (launch AND hibernation resume — the one
13
+ * seam where a transport peer id and a live `Database` both exist), and every pass is
14
+ * fully contained: a joiner at that instant has typically not synced the founder's rows
15
+ * and may lack write quorum, so failure means "retry next tick", never a throw.
16
+ * - **Kicked the moment its database appears.** A joining machine's first pass runs while
17
+ * the first-sync write gate still withholds `instance.database`, so it finds no database
18
+ * and returns at once. `StrandInstanceManager.publishDatabase` calls `reconcile()` as it
19
+ * hands the database to the app, which is what makes the join finish about a second after
20
+ * the strand becomes writable rather than on the next timer.
21
+ * - **Retries fast while the join is unfinished, slowly while it is only waiting.** A pass
22
+ * that leaves the join unfinished re-arms on a ladder starting at
23
+ * {@link INITIAL_JOIN_RETRY_INTERVAL_MS} and doubling, capped at the configured poll
24
+ * interval (default {@link DEFAULT_MEMBERSHIP_RECONCILE_INTERVAL_MS}). A pass
25
+ * that finds no member row AND no staged invitation is not an unfinished join but a wait
26
+ * for someone to admit this party — nothing this machine can do faster — so it re-arms on
27
+ * the flat poll interval and resets the ladder. The loop stops on the done state.
28
+ * - **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}).
33
+ *
34
+ * ## One pass
35
+ *
36
+ * 1. **Self-revocation check.** If the enforcer flags this node's own party as revoked and
37
+ * no invitation is staged, stop rather than fight — re-admission arrives (if ever) via
38
+ * a fresh formation, which re-arms the loop. With an invitation staged the loop reports
39
+ * the dead end (below) and carries on: the redemption is attempted like any other, and a
40
+ * 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
49
+ * yet synced, or a machine whose party never joined) → keep waiting, escalating to one
50
+ * visible warning after {@link IDLE_PASSES_BEFORE_ESCALATION} passes, never throwing.
51
+ * 3. **Ensure the binding.** {@link registerMemberPeer} (insert-if-absent, restart-safe)
52
+ * 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.
56
+ *
57
+ * ## Stops, and re-arming
58
+ *
59
+ * Two kinds of stop. A RE-ARMABLE stop is one a fresh invitation should reopen:
60
+ *
61
+ * - **Done** (above).
62
+ * - **Self-revoked with nothing staged** (step 1 above).
63
+ *
64
+ * A PERMANENT stop is one a fresh invitation changes nothing about — {@link rearm} is a
65
+ * no-op after it:
66
+ *
67
+ * - **Sealed strand**: `consumeInvite` rejected by `ConsumedInvite.NotSealed` — nobody
68
+ * can ever be admitted, so retrying forever is noise. Terminal-with-log.
69
+ * - **Undecodable party key**: nothing can be signed; loud log, stop.
70
+ * - **The public {@link stop}**: `StrandInstanceManager.releaseRuntime` and
71
+ * `clearOwnMemberPeerBinding` both call it and mean it — the latter stops the loop and
72
+ * awaits {@link settle} precisely so no pass can re-register the binding it is about to
73
+ * delete, and a re-arm that restarted the loop would undo that.
74
+ *
75
+ * `CadreNode.adoptFormationMembershipInvite` stages every fresh invitation and notifies
76
+ * the instance manager, which calls {@link rearm}: a done loop reopens and runs one pass
77
+ * at once; a running loop is merely kicked. This is what lets a party that was REMOVED
78
+ * from the strand, and then handed a new invitation, actually attempt it — the loop
79
+ * finished during its first join, long before the removal.
80
+ *
81
+ * On a removed party the local replica is usually stale: the cohort cut this machine off
82
+ * at about the moment the removal was written, so `isStrandMember` still answers true and
83
+ * a re-armed pass lands in the already-member arm. That is why the burn arm keeps a
84
+ * refused invitation staged and why the done state requires nothing staged — otherwise
85
+ * the fresh credential would be dropped on the first refused burn and the loop would latch
86
+ * done again, with the only trace a debug line.
87
+ *
88
+ * A DEAD invitation that is not terminal for the loop — expired, cancelled, or already
89
+ * consumed by someone else (`ConsumedInvite`'s primary key) — is dropped with a log and
90
+ * the loop keeps idling: a fresh formation stages a new invitation, and a manager-side
91
+ * admission (`addMemberByManager`) seats the member row without one.
92
+ *
93
+ * ## Reporting a blocked re-join
94
+ *
95
+ * Redeeming (or burning) writes into the strand, and the machines that would carry that
96
+ * write are exactly the ones the remaining members refuse once this party is removed. So
97
+ * the attempt is expected to fail, and the failure is REPORTED rather than left to the
98
+ * ladder: one `console.warn` plus the {@link StrandMembershipReconcilerDeps.onRejoinBlocked}
99
+ * callback (`CadreNode`'s `strand:rejoin-blocked` event), at most once per re-arm cycle.
100
+ * Two triggers:
101
+ *
102
+ * - **Confirmed** — a pass finds this party self-revoked AND an invitation staged. The node
103
+ * knows it was removed and is holding a credential it cannot spend.
104
+ * - **Probable** — {@link UNFINISHED_PASSES_BEFORE_ESCALATION} consecutive attempted passes
105
+ * left the invitation staged. The case that matters most in the field: a removed party
106
+ * that never learned it was removed (the removal did not replicate here before the cut).
107
+ * It is a suspicion, not a verdict — the invitation's `Invite` row may simply not have
108
+ * replicated here yet — and the warning names both causes.
109
+ *
110
+ * The remedy in either case is a remaining manager admitting this party's member key
111
+ * directly (`addMemberByManager`): that lifts the refusal, replication resumes, and the
112
+ * still-running loop sees the member row, burns the leftover credential and finishes by
113
+ * itself.
114
+ *
115
+ * ## Sharing the database with the app
116
+ *
117
+ * The strand `Database` this loop writes to is the one the app holds. Every write here
118
+ * passes `joinOpenTransaction: false`, so it runs as a transaction of its own and never
119
+ * joins one the app has open: the writer refuses with `StrandTransactionBusyError`, having
120
+ * written nothing, and the pass retries on the ladder. A busy refusal is never read as a
121
+ * dead invitation, and a busy burn leaves the invitation staged for the next pass.
122
+ *
123
+ * A write refused because the strand's offline queue holds transactions
124
+ * (`StrandOfflineQueueBusyError`, docs/strands.md → "Offline mode") is a busy refusal too: it
125
+ * wrote nothing, and the ladder retries it until the queue drains. A membership commit queued
126
+ * behind an app commit anyway (the race that refusal leaves open) can fail with Optimystic's
127
+ * `OfflineCommitTimeoutError`, which is an unclassified failure here: a redemption keeps the
128
+ * invitation and retries, and a binding is retried by the next pass. Each pass reads the state
129
+ * before it writes (the member row, then the binding, which is insert-if-absent), so a write that
130
+ * landed after all (`sent: true`) is found by that pass rather than written twice.
131
+ *
132
+ * ## Half-committed join
133
+ *
134
+ * On a networked strand optimystic commits `Member` and `ConsumedInvite` as separate
135
+ * collections and can report that only some of them were saved (`CoordinatorPartialCommitError`,
136
+ * or the plugin's legacy `PartialCommitError`). When `ConsumedInvite` is saved and `Member` is
137
+ * not, the invitation is spent and the schema seats a `Member` through an invitation only in the
138
+ * same transaction as a fresh consumption, so this loop can never seat the party from it. Such a
139
+ * failure is recognised by TYPE before any message text is read (its message names the
140
+ * `ConsumedInvite` collection, which a text match once mistook for a dead invitation), reported
141
+ * with ONE `console.warn`, and the invitation is dropped. The loop keeps running like it does
142
+ * after a dead invitation: a manager admission, or a `Member` row that did land, is picked up by
143
+ * the next pass, which then writes the binding. Whether sereus should repair such a join itself
144
+ * is `blocked/strand-half-committed-join-recovery`.
145
+ */
146
+
147
+ import debug from 'debug';
148
+ import type { Database } from '@quereus/quereus';
149
+ import { CoordinatorPartialCommitError } from '@optimystic/db-core';
150
+ import { PartialCommitError } from '@optimystic/quereus-plugin-optimystic';
151
+ import { causeChain } from './control-retry.js';
152
+ import type { Ed25519KeyPair } from './ed25519-key.js';
153
+ import type { StrandMembershipInvite } from './types.js';
154
+ import { strandMemberKeyPair } from './strand-member-key.js';
155
+ import {
156
+ StrandOfflineQueueBusyError,
157
+ StrandTransactionBusyError,
158
+ burnInvite,
159
+ consumeInvite,
160
+ isStrandMember,
161
+ registerMemberPeer,
162
+ type StrandWriteOptions,
163
+ } from './strand-membership-writer.js';
164
+ import { defaultTimeoutScheduler, type TimeoutScheduler } from './timeout-scheduler.js';
165
+ import { describeThrown } from './describe-thrown.js';
166
+
167
+ const log = debug('sereus:cadre:strand-membership-reconciler');
168
+
169
+ /**
170
+ * Default poll interval, ms: the loop's idle cadence while nobody has admitted this party, and
171
+ * the cap of its unfinished-join retry ladder. The loop stops once joined, so this matters only
172
+ * while a machine is joining.
173
+ */
174
+ export const DEFAULT_MEMBERSHIP_RECONCILE_INTERVAL_MS = 30_000;
175
+
176
+ /**
177
+ * Idle passes (no member row, no staged invitation) before ONE `console.warn`
178
+ * escalation — at the default 30 s cadence, about five minutes of waiting. The loop
179
+ * keeps retrying quietly after it; the warning exists so a joiner stuck waiting on
180
+ * founder-row replication is visible without the debug namespace enabled.
181
+ */
182
+ export const IDLE_PASSES_BEFORE_ESCALATION = 10;
183
+
184
+ /**
185
+ * Consecutive passes that ran against a live database and ended with the staged
186
+ * invitation still unsettled — whatever refused it — before the loop reports a probable
187
+ * blocked re-join (see "Reporting a blocked re-join" in the module doc). The same order
188
+ * as {@link IDLE_PASSES_BEFORE_ESCALATION}: about three minutes at the default cadence
189
+ * (the ladder's five doubling rungs, then five passes at the 30 s cap). Counted by outcome
190
+ * rather than by classified failure because a cut-off machine can fail before any write is
191
+ * classified: its membership READ may already throw.
192
+ */
193
+ export const UNFINISHED_PASSES_BEFORE_ESCALATION = 10;
194
+
195
+ /**
196
+ * First retry delay, ms, for a pass that left the join UNFINISHED — a `consumeInvite`
197
+ * whose `Strand.Invite` row has not replicated to this machine yet, a cohort briefly
198
+ * unwritable, a database not yet published. Doubles per such pass up to the configured
199
+ * poll interval. Sized for what it retries: invite-row replication resolves in about a
200
+ * second over a direct connection and a few over a relay. The poll interval is NOT sized
201
+ * for that — it is sized for the idle case (waiting to be admitted at all), which is why
202
+ * this ladder exists instead of a shorter interval.
203
+ */
204
+ export const INITIAL_JOIN_RETRY_INTERVAL_MS = 1_000;
205
+
206
+ /** Every write this loop makes runs in a transaction of its own — see "Sharing the database with the app". */
207
+ const OWN_TRANSACTION: StrandWriteOptions = { joinOpenTransaction: false };
208
+
209
+ /**
210
+ * The `consumeInvite` rejection that means the strand is SEALED — `ConsumedInvite.NotSealed`
211
+ * fired, which Quereus renders `CHECK constraint failed: NotSealed (<its expression>)`.
212
+ * Terminal for a non-member: nobody can ever be admitted again.
213
+ */
214
+ const SEALED_REJECTION = /CHECK constraint failed: NotSealed\b/;
215
+
216
+ /**
217
+ * `consumeInvite` rejections that mean the INVITATION is dead but the loop should keep
218
+ * waiting for membership to arrive another way: expired (`CHECK constraint failed: NotExpired`),
219
+ * cancelled (`CHECK constraint failed: NotCancelled`), or already consumed by someone else
220
+ * (`UNIQUE constraint failed: ConsumedInvite.InviteKey`, the primary key).
221
+ *
222
+ * Anchored to the engine's full constraint-failure texts, not the bare names: other failures
223
+ * embed those names — a half-committed join's message names the `default/strand/ConsumedInvite`
224
+ * collection, which the bare `ConsumedInvite` this used to match read as a dead invitation. The
225
+ * texts are pinned against the real engine in `strand-membership-reconciler.spec.ts`, so a
226
+ * rewording in Quereus fails a spec instead of silently turning a dead invitation into an
227
+ * endless retry.
228
+ */
229
+ const DEAD_INVITE_REJECTION =
230
+ /CHECK constraint failed: (?:NotExpired|NotCancelled)\b|UNIQUE constraint failed: ConsumedInvite\.InviteKey\b/;
231
+
232
+ /**
233
+ * A redemption only part of which was saved: the collections (or, on the plugin's legacy
234
+ * path, tree labels) that were saved and those that were not, as the error reports them.
235
+ */
236
+ export interface HalfCommittedJoin {
237
+ kind: 'half-committed';
238
+ saved: readonly string[];
239
+ unsaved: readonly string[];
240
+ }
241
+
242
+ /** Where {@link classifyConsumeFailure} routes a failed `consumeInvite` or `burnInvite`. */
243
+ export type ConsumeFailure =
244
+ | HalfCommittedJoin
245
+ /**
246
+ * The app had a transaction open, or the strand's offline queue held transactions, so nothing
247
+ * was tried — keep the invitation, retry.
248
+ */
249
+ | { kind: 'busy' }
250
+ /** The strand is sealed — terminal for a non-member; a member's leftover invitation is merely dead. */
251
+ | { kind: 'sealed' }
252
+ /** Expired, cancelled, or consumed by someone else — drop the invitation, keep waiting. */
253
+ | { kind: 'dead-invite' }
254
+ /**
255
+ * Anything else — the `Invite` row has not replicated here yet, or the cohort refused the
256
+ * write (a removed party's machines are denied) — keep the invitation, retry.
257
+ */
258
+ | { kind: 'retry' };
259
+
260
+ /**
261
+ * Route a `consumeInvite` or `burnInvite` rejection. Both write the `Strand.ConsumedInvite`
262
+ * row under the same `NotExpired` / `NotCancelled` / `NotSealed` / primary-key constraints
263
+ * (a burn writes that row alone), so one classifier serves both. Typed checks run before any
264
+ * text check: a busy refusal (another transaction was open, so nothing ran) and a
265
+ * half-committed join are recognised by their error's type anywhere in the `cause` chain.
266
+ * The busy refusal carries Quereus's own refusal as its cause, and a half-committed join's
267
+ * message embeds collection names and the underlying failure's text, either of which a text
268
+ * matcher can misread. The sealed and dead-invitation checks then read the top-level message.
269
+ *
270
+ * A second loaded copy of `@optimystic/db-core` (or of the plugin) would fail `instanceof`; the
271
+ * half-commit then falls through the anchored texts to `retry`, and once the saved `ConsumedInvite`
272
+ * row is visible here a later attempt fails on its primary key and drops the invitation quietly —
273
+ * the old silent outcome, a few passes later, never a wrong write.
274
+ */
275
+ export function classifyConsumeFailure(error: unknown): ConsumeFailure {
276
+ if (isTransactionBusy(error)) return { kind: 'busy' };
277
+ const halfCommitted = halfCommittedJoin(error);
278
+ if (halfCommitted) return halfCommitted;
279
+ const message = describeThrown(error);
280
+ if (SEALED_REJECTION.test(message)) return { kind: 'sealed' };
281
+ if (DEAD_INVITE_REJECTION.test(message)) return { kind: 'dead-invite' };
282
+ return { kind: 'retry' };
283
+ }
284
+
285
+ /**
286
+ * The first partial-commit error in the `cause` chain, as the lists it reports.
287
+ *
288
+ * NOTE: `PartialCommitError` is imported from the plugin's root entry while strands register the
289
+ * plugin through its `/plugin` entry (`quereus-plugin-sereus`'s `compose-strand.ts`); the two are
290
+ * one class only because the plugin's build emits both entries over one shared chunk — the same
291
+ * dependency, and the same remedy if upstream ever bundles them apart, as the NOTE on
292
+ * `reportsPossiblyStoredWrite` in `control-write-retry.ts`.
293
+ */
294
+ function halfCommittedJoin(error: unknown): HalfCommittedJoin | undefined {
295
+ for (const link of causeChain(error)) {
296
+ if (link instanceof CoordinatorPartialCommitError) {
297
+ return { kind: 'half-committed', saved: link.committedCollections, unsaved: link.failedCollections };
298
+ }
299
+ if (link instanceof PartialCommitError) {
300
+ return { kind: 'half-committed', saved: link.persisted, unsaved: link.unpersisted };
301
+ }
302
+ }
303
+ return undefined;
304
+ }
305
+
306
+ /**
307
+ * Whether a writer refused having written nothing, because another transaction was open or the
308
+ * offline queue held transactions (see "Sharing the database with the app").
309
+ */
310
+ function isTransactionBusy(error: unknown): boolean {
311
+ return causeChain(error).some((link) =>
312
+ link instanceof StrandTransactionBusyError || link instanceof StrandOfflineQueueBusyError);
313
+ }
314
+
315
+ /**
316
+ * The staged formation invitation seam — `CadreNode`'s in-memory
317
+ * `pendingMembershipInvites` cache, scoped to one strand. Read lazily per pass (a
318
+ * re-formation may replace the entry between passes) and cleared by the reconciler once
319
+ * the invitation is spent, burned, or dead — the invalidation half the cache itself
320
+ * deliberately does not own.
321
+ */
322
+ export interface PendingMembershipInviteSource {
323
+ /** The staged invitation, or `undefined` when none is pending for this strand. */
324
+ get(): StrandMembershipInvite | undefined;
325
+ /**
326
+ * Drop `settled` (spent, burned, or dead) — only if it is still the staged one. A
327
+ * re-formation can replace the entry between a pass's {@link get} and this call, and
328
+ * the fresh invitation it staged must survive the older one being settled.
329
+ */
330
+ clear(settled: StrandMembershipInvite): void;
331
+ }
332
+
333
+ export interface StrandMembershipReconcilerDeps {
334
+ /** Log tag naming which strand this reconciler serves (the strand id). */
335
+ label: string;
336
+ /**
337
+ * THIS party's own strand membership private key (base64 protobuf, the control-layer
338
+ * `StrandPartyKey` row's content). Decoded LAZILY on the first pass, so a malformed
339
+ * key stops the loop with a log instead of failing bring-up.
340
+ */
341
+ partyMemberPrivateKey: string;
342
+ /**
343
+ * The live strand `Database`, read per pass, never captured — the instance's handle
344
+ * is dropped on quiesce, and `undefined` means "no live database this instant" (the
345
+ * pass simply waits for the next tick).
346
+ */
347
+ getDatabase: () => Database | undefined;
348
+ /**
349
+ * This node's own strand transport peer id — the `MemberPeer.PeerId` to bind. Read
350
+ * per pass for the same lifecycle reason as {@link getDatabase}.
351
+ */
352
+ getOwnPeerId: () => string | undefined;
353
+ /** The staged invitation seam. Absent for flows with no invitation (e.g. tests). */
354
+ pendingInvite?: PendingMembershipInviteSource;
355
+ /**
356
+ * Whether the revocation enforcer currently flags THIS node's own party as revoked.
357
+ * When it does and nothing is staged, the loop stops rather than fight the enforcer;
358
+ * with an invitation staged it reports the blocked re-join and keeps trying — see the
359
+ * module doc. Absent (enforcement disarmed) means "not known revoked".
360
+ */
361
+ isSelfRevoked?: () => boolean;
362
+ /**
363
+ * Called when the loop reports a blocked re-join (see "Reporting a blocked re-join" in
364
+ * the module doc) — at most once per re-arm cycle, after the `console.warn`. `CadreNode`
365
+ * wires it to its `strand:rejoin-blocked` event.
366
+ */
367
+ onRejoinBlocked?: () => void;
368
+ /**
369
+ * Timer seam for the retry ladder; omit for real (unref'd) timeouts. Timeouts rather
370
+ * than the enforcer's repeating interval because the delay changes per pass and the next
371
+ * pass is armed only once the previous one settles, so a slow pass never stacks ticks
372
+ * behind it — the same seam the first-sync gate's probe loop uses.
373
+ */
374
+ scheduler?: TimeoutScheduler;
375
+ }
376
+
377
+ /** Embedder-facing tuning, threaded by `StrandInstanceManager`. */
378
+ export interface StrandMembershipReconciliationConfig {
379
+ /**
380
+ * Default true. False disarms the loop entirely — meant for test fixtures that
381
+ * hand-drive the membership writers and assert exact row sets; a production
382
+ * node that disarms it never seats a joiner's member row or binds its machines.
383
+ */
384
+ enabled?: boolean;
385
+ /**
386
+ * Idle cadence, ms — how often the loop re-checks while nobody has admitted this party
387
+ * yet — and the CAP of the unfinished-join retry ladder. Default
388
+ * {@link DEFAULT_MEMBERSHIP_RECONCILE_INTERVAL_MS}.
389
+ */
390
+ pollIntervalMs?: number;
391
+ }
392
+
393
+ /**
394
+ * The per-strand membership reconciliation loop. Created in
395
+ * `StrandInstanceManager.buildStrandRuntime` (closed strands with a party key only),
396
+ * started right after the strand database initializes, stopped and dropped in
397
+ * `releaseRuntime` — so quiesce → resume rebuilds it and re-runs the (idempotent) ladder
398
+ * from scratch.
399
+ */
400
+ export class StrandMembershipReconciler {
401
+ private readonly scheduler: TimeoutScheduler;
402
+ private readonly pollIntervalMs: number;
403
+ /** Tail of the pass chain — serializes passes (no two in flight). */
404
+ private tail: Promise<void> = Promise.resolve();
405
+ private timer: unknown;
406
+ private started = false;
407
+ private stoppedFlag = false;
408
+ /**
409
+ * Whether the last stop was one {@link rearm} may not undo — see "Stops, and re-arming"
410
+ * in the module doc. Latched by the public {@link stop} and the permanent terminal
411
+ * states, never cleared.
412
+ */
413
+ private permanentlyStopped = false;
414
+ private doneFlag = false;
415
+ /** Lazily decoded party keypair — see {@link StrandMembershipReconcilerDeps.partyMemberPrivateKey}. */
416
+ private keyPair: Ed25519KeyPair | undefined;
417
+ private idlePasses = 0;
418
+ private idleEscalated = false;
419
+ /** Consecutive attempted passes that left the invitation staged — see {@link UNFINISHED_PASSES_BEFORE_ESCALATION}. */
420
+ private unfinishedPasses = 0;
421
+ /** Whether the blocked re-join was already reported this re-arm cycle (one report, either trigger). */
422
+ private rejoinBlockedReported = false;
423
+ /**
424
+ * Whether the pass that just ran found nothing to act on — no member row and no staged
425
+ * invitation. That is a wait to be admitted, not an unfinished join, so it re-arms on the
426
+ * flat poll interval; every other unfinished outcome climbs the ladder.
427
+ *
428
+ * NOTE: the ladder is therefore the DEFAULT for any outcome nobody classified — a new
429
+ * early return added to {@link doPass} inherits the fast retry unless it calls
430
+ * {@link noteIdlePass}. Right for every outcome that exists today (each is an unfinished
431
+ * join this machine can make progress on). If an early return is ever added for a
432
+ * condition retrying cannot resolve, classify it idle.
433
+ */
434
+ private lastPassIdle = false;
435
+ /** Current rung of the unfinished-join retry ladder, ms; unset before the first retry. */
436
+ private retryDelayMs: number | undefined;
437
+
438
+ constructor(
439
+ private readonly deps: StrandMembershipReconcilerDeps,
440
+ config?: StrandMembershipReconciliationConfig
441
+ ) {
442
+ this.scheduler = deps.scheduler ?? defaultTimeoutScheduler;
443
+ this.pollIntervalMs = config?.pollIntervalMs ?? DEFAULT_MEMBERSHIP_RECONCILE_INTERVAL_MS;
444
+ }
445
+
446
+ /**
447
+ * True once member row + own binding were both confirmed with nothing staged and the
448
+ * loop stopped. Cleared again by {@link rearm}.
449
+ */
450
+ get done(): boolean {
451
+ return this.doneFlag;
452
+ }
453
+
454
+ /** True while the loop is stopped — done, terminal, or externally stopped. */
455
+ get stopped(): boolean {
456
+ return this.stoppedFlag;
457
+ }
458
+
459
+ /**
460
+ * Kick an immediate pass (not awaited — bring-up never blocks on it). Every later pass
461
+ * is armed only once the previous one settles — see the retry ladder in the module doc —
462
+ * so there is no repeating interval to arm here.
463
+ */
464
+ start(): void {
465
+ if (this.started || this.stoppedFlag) return;
466
+ this.started = true;
467
+ void this.reconcile();
468
+ log('[%s] membership reconciler started (retry from %dms, idle poll %dms)',
469
+ this.deps.label, Math.min(INITIAL_JOIN_RETRY_INTERVAL_MS, this.pollIntervalMs), this.pollIntervalMs);
470
+ }
471
+
472
+ /**
473
+ * Resolve once no pass is in flight. {@link stop} only disarms the retry TIMER — a pass
474
+ * already past its stopped check runs to completion, so a caller that must know the
475
+ * loop can no longer write (`StrandInstanceManager.clearOwnMemberPeerBinding`, which
476
+ * would otherwise have its removal undone by a racing `registerMemberPeer`) awaits
477
+ * this after stopping. Never rejects: the pass chain contains every failure.
478
+ */
479
+ async settle(): Promise<void> {
480
+ await this.tail;
481
+ }
482
+
483
+ /**
484
+ * Disarm the retry timer, for good: a later {@link rearm} is refused. A pass already in
485
+ * flight completes but writes idempotently — {@link settle} is what waits it out.
486
+ */
487
+ stop(): void {
488
+ this.halt('stopped by the runtime', true);
489
+ }
490
+
491
+ /**
492
+ * A fresh invitation was staged: reopen a loop that stopped on a re-armable state (done,
493
+ * or self-revoked with nothing staged) and run one pass at once; merely kick a loop that
494
+ * is still running; do nothing after a permanent stop. Never rejects, and serialized
495
+ * like {@link reconcile}: the reopen happens when the queued pass STARTS, after any pass
496
+ * in flight has settled, so a `done` that pass latches cannot swallow the re-arm — and a
497
+ * public {@link stop} that lands first still wins, because the queued pass re-checks it.
498
+ */
499
+ rearm(): Promise<void> {
500
+ return this.enqueue(() => this.reopen() ? this.doPass() : Promise.resolve());
501
+ }
502
+
503
+ /**
504
+ * Run one pass now. Never rejects. Serialized: concurrent calls chain, so no two
505
+ * passes overlap and each explicit call gets a pass that STARTS after the call. On a
506
+ * started loop the pass re-arms the retry timer where it settles, so an explicit call —
507
+ * `StrandInstanceManager.publishDatabase`'s kick when a joiner's database is finally
508
+ * published — REPLACES the pending timer rather than running alongside it.
509
+ */
510
+ reconcile(): Promise<void> {
511
+ return this.enqueue(() => this.doPass());
512
+ }
513
+
514
+ /** Chain `pass` after every pass already queued; the tail never rejects. */
515
+ private enqueue(pass: () => Promise<void>): Promise<void> {
516
+ // The catch is what keeps the chain alive. `doPass` contains its own failures, but its
517
+ // `finally` calls into the injected scheduler, and a throw from there would leave `tail`
518
+ // REJECTED — after which every later `reconcile()` short-circuits on it and the join
519
+ // stalls for good, silently. Swallowing it here makes the "never rejects" contract
520
+ // {@link reconcile}, {@link rearm}, {@link settle} and the `void`-ed call sites all rely
521
+ // on structural rather than incidental.
522
+ const run = this.tail.then(pass).catch((error) => {
523
+ log('[%s] reconcile pass threw outside its own handler — the chain continues: %o',
524
+ this.deps.label, error);
525
+ });
526
+ this.tail = run;
527
+ return run;
528
+ }
529
+
530
+ /**
531
+ * The re-arm itself, run at the head of the queued pass: `false` refuses the pass (a
532
+ * permanent stop), a running loop is left as it is, and a re-armable stop is reopened
533
+ * with the idle and unfinished counters, both escalation latches and the retry ladder
534
+ * reset — a fresh invitation is a fresh cycle.
535
+ */
536
+ private reopen(): boolean {
537
+ if (this.permanentlyStopped) {
538
+ log('[%s] re-arm refused — the loop is stopped for good', this.deps.label);
539
+ return false;
540
+ }
541
+ if (!this.stoppedFlag) {
542
+ // NOTE: a running loop keeps its counters and its once-per-cycle report latch, so a
543
+ // party whose loop already reported and is then re-formed AGAIN gets no second report
544
+ // for the replacement invitation. If that second report is ever wanted, key the latch
545
+ // on the staged invitation's key rather than on the re-arm.
546
+ log('[%s] fresh invitation staged on a running loop — kicking a pass', this.deps.label);
547
+ return true;
548
+ }
549
+ this.stoppedFlag = false;
550
+ this.doneFlag = false;
551
+ this.idlePasses = 0;
552
+ this.idleEscalated = false;
553
+ this.unfinishedPasses = 0;
554
+ this.rejoinBlockedReported = false;
555
+ this.retryDelayMs = undefined;
556
+ log('[%s] membership reconciler re-armed by a fresh invitation', this.deps.label);
557
+ return true;
558
+ }
559
+
560
+ /** One serialized pass; contains every failure (contract: never rejects). */
561
+ private async doPass(): Promise<void> {
562
+ if (this.stoppedFlag || this.doneFlag) return;
563
+ this.lastPassIdle = false;
564
+ try {
565
+ if (this.deps.isSelfRevoked?.() === true && !this.stagedInviteBlockedBySelfRevocation()) {
566
+ // NOTE: the enforcer's flag lags a re-admission by up to one of its polls. If the
567
+ // pass that settled the last staged invitation then failed to write the binding, this
568
+ // stop lands with the binding missing until the next resume rebuilds the loop. A
569
+ // missing binding only mis-credits diversity today; if it ever gates admission, make
570
+ // this stop also require the binding to be in place.
571
+ this.finish('this party is revoked from the strand — re-admission arrives (if ever) via a fresh formation', false);
572
+ return;
573
+ }
574
+ const keyPair = this.resolveKeyPair();
575
+ if (!keyPair) return; // undecodable key already stopped the loop
576
+ const db = this.deps.getDatabase();
577
+ if (!db) return; // no live database this instant (quiesce race) — next tick decides
578
+ await this.attempt(db, keyPair);
579
+ } catch (error) {
580
+ log('[%s] reconcile pass failed — retrying next tick: %o', this.deps.label, error);
581
+ } finally {
582
+ this.scheduleNext();
583
+ }
584
+ }
585
+
586
+ /**
587
+ * Steps 2 and 3 against a live database, with the outcome counted toward the probable
588
+ * blocked re-join report whether the attempt returned or threw.
589
+ */
590
+ private async attempt(db: Database, keyPair: Ed25519KeyPair): Promise<void> {
591
+ try {
592
+ if (!(await this.ensureMembership(db, keyPair))) return;
593
+ // NOTE: accepted tradeoff — the redemption (`Member` + `ConsumedInvite`) and the binding
594
+ // below stay two SEPARATE commits on purpose. Merging them would save one commit: its
595
+ // serial latency and, since Optimystic 1.19.0 pends and commits a transaction's collections
596
+ // together, its `/cluster` requests (the two commits cost 6 on a two-member strand in
597
+ // `message-cost-accounting` on 2026-10-25, 20 before). It would also let a torn commit
598
+ // (Optimystic can report a multi-collection commit partly saved) or the cohort applying
599
+ // the collections out of order show this machine's `MemberPeer` without its `Member`,
600
+ // which the revocation enforcer reads as a removed member and hangs up on — fail closed,
601
+ // undone only by a manager clearing the binding (module doc of
602
+ // `strand-revocation-enforcer.ts`). And it would add a half-committed shape (`MemberPeer`
603
+ // saved, the invitation still live) that {@link reportHalfCommittedJoin}'s dropping of the
604
+ // invitation gets wrong. Revisit when Optimystic offers an all-or-nothing multi-collection
605
+ // commit, or when the enforcer can tell a not-yet-seated binding from a removed member's.
606
+ await this.ensureBinding(db, keyPair);
607
+ } finally {
608
+ this.noteAttemptOutcome();
609
+ }
610
+ }
611
+
612
+ /**
613
+ * Arm the next pass, now that this one has settled — so a slow pass never stacks ticks
614
+ * behind it. Only a STARTED loop schedules: a caller driving {@link reconcile} by hand
615
+ * (the unit tests, and the publish kick on a launch whose `start()` has not run yet) gets
616
+ * exactly the passes it asks for and no background timer.
617
+ */
618
+ private scheduleNext(): void {
619
+ if (!this.started || this.stoppedFlag || this.doneFlag) return;
620
+ this.clearTimer();
621
+ const delayMs = this.nextDelayMs();
622
+ this.timer = this.scheduler.setTimeout(() => {
623
+ this.timer = undefined;
624
+ void this.reconcile();
625
+ }, delayMs);
626
+ }
627
+
628
+ /**
629
+ * The delay before the next pass: the flat poll interval while the loop is merely idling
630
+ * (no member row, no staged invitation — {@link noteIdlePass}), otherwise the next rung
631
+ * of the doubling ladder from {@link INITIAL_JOIN_RETRY_INTERVAL_MS}, capped at the poll
632
+ * interval. A pass that lands idle resets the ladder, so a later unfinished join starts
633
+ * over at the bottom rung.
634
+ */
635
+ private nextDelayMs(): number {
636
+ if (this.lastPassIdle) {
637
+ this.retryDelayMs = undefined;
638
+ return this.pollIntervalMs;
639
+ }
640
+ this.retryDelayMs = Math.min(
641
+ this.retryDelayMs === undefined ? INITIAL_JOIN_RETRY_INTERVAL_MS : this.retryDelayMs * 2,
642
+ this.pollIntervalMs
643
+ );
644
+ return this.retryDelayMs;
645
+ }
646
+
647
+ private clearTimer(): void {
648
+ if (this.timer !== undefined) {
649
+ this.scheduler.clearTimeout(this.timer);
650
+ this.timer = undefined;
651
+ }
652
+ }
653
+
654
+ /**
655
+ * Step 2 of the pass: `true` iff the party's member row is visible locally by the
656
+ * time this returns (already present, or seated by redeeming the staged invitation).
657
+ */
658
+ private async ensureMembership(db: Database, keyPair: Ed25519KeyPair): Promise<boolean> {
659
+ if (await isStrandMember(db, keyPair.publicKeyB64)) {
660
+ await this.burnLeftoverInvite(db, keyPair);
661
+ return true;
662
+ }
663
+ const invite = this.deps.pendingInvite?.get();
664
+ if (!invite) {
665
+ this.noteIdlePass();
666
+ return false;
667
+ }
668
+ try {
669
+ await consumeInvite(db, {
670
+ inviteKey: invite.inviteKey,
671
+ invitePrivateKey: invite.invitePrivateKey,
672
+ memberKey: keyPair.publicKeyB64,
673
+ }, OWN_TRANSACTION);
674
+ } catch (error) {
675
+ this.handleConsumeFailure(error, invite);
676
+ return false;
677
+ }
678
+ this.deps.pendingInvite?.clear(invite);
679
+ log('[%s] redeemed the staged membership invitation — Member row seated under this party\'s key', this.deps.label);
680
+ return true;
681
+ }
682
+
683
+ /**
684
+ * The already-member arm: spend a still-staged invitation so nobody else can. The stage
685
+ * is cleared once the burn lands or the invitation is known dead (already spent,
686
+ * cancelled, expired, or the strand sealed around a party that is still a member) — with
687
+ * the member row present a dead credential has no further local use, and keeping it
688
+ * staged would leave `getPendingMembershipInvite` lying. A refused burn keeps it staged:
689
+ * a busy refusal tried nothing, and a write the cohort refused is the removed-party shape
690
+ * ("Stops, and re-arming" in the module doc), where the local member row is stale and the
691
+ * credential is the one thing a later manager admission lets this loop settle.
692
+ *
693
+ * NOTE: this REPLACES an earlier accepted tradeoff that never retried a burn which failed
694
+ * for a transient reason and dropped the invitation instead. That decision was made when
695
+ * this arm could only ever see an invitation staged before the first join finished, so a
696
+ * dropped credential cost nothing but a spendable bearer token. {@link rearm} makes the
697
+ * arm reachable with a freshly issued invitation the app wants redeemed, and dropping
698
+ * that one on the first refused write is the silent failure this loop exists to avoid.
699
+ */
700
+ private async burnLeftoverInvite(db: Database, keyPair: Ed25519KeyPair): Promise<void> {
701
+ const invite = this.deps.pendingInvite?.get();
702
+ if (!invite) return;
703
+ try {
704
+ await burnInvite(db, {
705
+ inviteKey: invite.inviteKey,
706
+ invitePrivateKey: invite.invitePrivateKey,
707
+ memberKey: keyPair.publicKeyB64,
708
+ }, OWN_TRANSACTION);
709
+ } catch (error) {
710
+ this.handleBurnFailure(error, invite);
711
+ return;
712
+ }
713
+ this.deps.pendingInvite?.clear(invite);
714
+ log('[%s] burned the leftover invitation (member row already present)', this.deps.label);
715
+ }
716
+
717
+ /**
718
+ * Act on a `burnInvite` rejection as {@link classifyConsumeFailure} routes it. Unlike a
719
+ * redemption, a sealed strand is not terminal here — the member row is present, so this
720
+ * party is a member of the sealed strand and only its leftover credential is dead — and a
721
+ * half-committed burn (one collection, so a report of it means the commit's durability
722
+ * was in doubt) is retried: the next pass either lands it or fails on the row's primary
723
+ * key, which drops it as dead.
724
+ */
725
+ private handleBurnFailure(error: unknown, invite: StrandMembershipInvite): void {
726
+ const failure = classifyConsumeFailure(error);
727
+ switch (failure.kind) {
728
+ case 'busy':
729
+ log('[%s] burning the leftover invitation deferred — nothing was tried; it stays staged for the next '
730
+ + 'pass: %s', this.deps.label, describeThrown(error));
731
+ return;
732
+ case 'sealed':
733
+ case 'dead-invite':
734
+ log('[%s] the leftover invitation is dead (already spent, cancelled, expired, or the strand sealed) — '
735
+ + 'dropping it: %s', this.deps.label, describeThrown(error));
736
+ this.deps.pendingInvite?.clear(invite);
737
+ return;
738
+ case 'half-committed':
739
+ case 'retry':
740
+ log('[%s] burning the leftover invitation was refused — it stays staged and is retried next tick '
741
+ + '(the cohort refusing this machine, or a transient write failure): %s', this.deps.label, describeThrown(error));
742
+ return;
743
+ }
744
+ }
745
+
746
+ /**
747
+ * Step 3 of the pass: write this machine's own `MemberPeer` binding (insert-if-absent)
748
+ * and, once it is in place with nothing staged, latch the done state and stop the loop.
749
+ * A missing transport peer id (a quiesce racing the pass) defers to the next tick; a
750
+ * write failure — a busy refusal included — is contained by the pass's outer catch and
751
+ * retried. A binding written while an invitation is still staged (its burn keeps being
752
+ * refused) is not done: the loop stays live so a later pass can settle the credential.
753
+ */
754
+ private async ensureBinding(db: Database, keyPair: Ed25519KeyPair): Promise<void> {
755
+ const peerId = this.deps.getOwnPeerId();
756
+ if (!peerId) {
757
+ log('[%s] no live transport peer id this pass — binding deferred', this.deps.label);
758
+ return;
759
+ }
760
+ await registerMemberPeer(db, { memberKeyPair: keyPair, peerId }, OWN_TRANSACTION);
761
+ if (this.deps.pendingInvite?.get()) {
762
+ log('[%s] own MemberPeer binding is in place but an invitation is still staged — not done yet', this.deps.label);
763
+ return;
764
+ }
765
+ this.doneFlag = true;
766
+ this.finish('member row and own MemberPeer binding are both in place', false);
767
+ }
768
+
769
+ /**
770
+ * Act on a `consumeInvite` rejection as {@link classifyConsumeFailure} routes it: busy → keep
771
+ * the invitation and retry; half-committed → warn and drop; sealed → terminal; dead
772
+ * invitation → drop; anything else → retry.
773
+ */
774
+ private handleConsumeFailure(error: unknown, invite: StrandMembershipInvite): void {
775
+ const failure = classifyConsumeFailure(error);
776
+ switch (failure.kind) {
777
+ case 'busy':
778
+ log('[%s] redeeming the staged invitation deferred — nothing was tried; retrying next tick: %s',
779
+ this.deps.label, describeThrown(error));
780
+ return;
781
+ case 'half-committed':
782
+ this.reportHalfCommittedJoin(failure, error, invite);
783
+ return;
784
+ case 'sealed':
785
+ // The staged credential is dead with the seal; drop it so the cache stays honest.
786
+ this.deps.pendingInvite?.clear(invite);
787
+ this.finish('the strand is sealed — nobody can ever be admitted, so the staged invitation is dead', true);
788
+ return;
789
+ case 'dead-invite':
790
+ // NOTE: accepted tradeoff — dropping a dead invitation does not mark the pass idle,
791
+ // so the next attempt is one ladder rung away rather than a full poll interval. Kept:
792
+ // the pass AFTER it finds no member row and no invitation, marks itself idle, and
793
+ // re-arms flat, so the cost is one extra read per dead credential. Revisit if a
794
+ // source of dead invitations ever repeats per pass.
795
+ log('[%s] the staged invitation is dead (expired, cancelled, or consumed elsewhere) — dropping it; '
796
+ + 'a fresh formation stages a new one: %s', this.deps.label, describeThrown(error));
797
+ this.deps.pendingInvite?.clear(invite);
798
+ return;
799
+ case 'retry':
800
+ log('[%s] consumeInvite failed — retrying next tick (Invite row not yet replicated here, the cohort '
801
+ + 'refusing this machine, or a transient write failure): %s', this.deps.label, describeThrown(error));
802
+ return;
803
+ }
804
+ }
805
+
806
+ /**
807
+ * Count an attempted pass that left the invitation staged (whatever stopped it — a
808
+ * refused or busy write, or a read that threw on a cut-off machine); one that settled
809
+ * it, or finished, ends the streak. At {@link UNFINISHED_PASSES_BEFORE_ESCALATION}
810
+ * report the PROBABLE blocked re-join.
811
+ */
812
+ private noteAttemptOutcome(): void {
813
+ if (this.doneFlag || !this.deps.pendingInvite?.get()) {
814
+ this.unfinishedPasses = 0;
815
+ return;
816
+ }
817
+ this.unfinishedPasses += 1;
818
+ if (this.unfinishedPasses >= UNFINISHED_PASSES_BEFORE_ESCALATION) {
819
+ this.reportRejoinBlocked(
820
+ `${this.unfinishedPasses} membership reconcile passes have left the staged membership invitation `
821
+ + 'unsettled. Either this party was removed from the strand and the remaining members are refusing its '
822
+ + 'machines, or the invitation\'s Strand.Invite row has not replicated here yet.'
823
+ );
824
+ }
825
+ }
826
+
827
+ /**
828
+ * Step 1's CONFIRMED trigger: self-revoked with an invitation staged. Reports (once per
829
+ * re-arm cycle) and answers `true` so the pass carries on — the redemption is attempted
830
+ * and refused like any other write, and a manager's re-admission lets a later pass finish.
831
+ * `false` (nothing staged) means step 1 stops the loop as before.
832
+ */
833
+ private stagedInviteBlockedBySelfRevocation(): boolean {
834
+ if (!this.deps.pendingInvite?.get()) return false;
835
+ this.reportRejoinBlocked(
836
+ 'this party is revoked from the strand and holds a staged membership invitation it cannot spend: the '
837
+ + 'remaining members refuse this machine\'s strand writes, so the redemption cannot land.'
838
+ );
839
+ return true;
840
+ }
841
+
842
+ /**
843
+ * ONE `console.warn` and one callback per re-arm cycle, whichever trigger fires first —
844
+ * see "Reporting a blocked re-join" in the module doc. `cause` is the trigger's own
845
+ * sentence; the remedy and the loop's posture are the same for both.
846
+ */
847
+ private reportRejoinBlocked(cause: string): void {
848
+ if (this.rejoinBlockedReported) return;
849
+ this.rejoinBlockedReported = true;
850
+ console.warn(
851
+ `[sereus] strand ${this.deps.label}: ${cause} A fresh invitation cannot re-admit a removed party by itself — `
852
+ + 'a remaining manager must admit this party\'s member key directly (addMemberByManager). The membership '
853
+ + 'loop keeps retrying quietly and completes the join once a Member row for this party appears.'
854
+ );
855
+ this.deps.onRejoinBlocked?.();
856
+ }
857
+
858
+ /**
859
+ * A redemption only part of which was saved (see "Half-committed join" in the module doc):
860
+ * ONE visible warning naming both halves, and the staged invitation dropped. The pass is not
861
+ * marked idle, so the next one runs a ladder rung later and either finds a `Member` row (a
862
+ * saved one, or a manager's admission) and writes the binding, or idles flat.
863
+ *
864
+ * NOTE: the invitation is dropped whichever half was saved. In the observed shape
865
+ * (`ConsumedInvite` saved, `Member` not) it is spent and a retry could only fail on
866
+ * `ConsumedInvite`'s primary key. In the opposite shape (`Member` saved, `ConsumedInvite` not)
867
+ * keeping it would let the already-member arm burn it; dropping it leaves that bearer
868
+ * credential spendable until it expires — the state the burn arm's accepted tradeoff already
869
+ * lands in. Not branched on, because telling the shapes apart means parsing the lists, which
870
+ * are collection ids on the coordinator path but free-form tree labels on the plugin's legacy
871
+ * path. Revisit if a `Member`-saved half-commit is ever observed, or when
872
+ * `blocked/strand-half-committed-join-recovery` is decided.
873
+ */
874
+ private reportHalfCommittedJoin(failure: HalfCommittedJoin, error: unknown, invite: StrandMembershipInvite): void {
875
+ console.warn(
876
+ `[sereus] strand ${this.deps.label}: redeeming the staged membership invitation was only partly saved. `
877
+ + `Saved: [${failure.saved.join(', ')}]. Not saved: [${failure.unsaved.join(', ')}]. `
878
+ + 'The invitation is dropped: a saved ConsumedInvite row spends it, so it cannot be redeemed again. '
879
+ + 'If this party\'s Member row is not among the saved, the party is not a member of the strand and '
880
+ + 'cannot become one from this invitation — a manager must admit it directly (addMemberByManager). '
881
+ + 'The membership loop keeps checking and completes the join once a Member row for this party appears.'
882
+ );
883
+ log('[%s] half-committed redemption, full error: %o', this.deps.label, error);
884
+ this.deps.pendingInvite?.clear(invite);
885
+ // The idle passes that follow are the wait this warning already explained; the escalation's
886
+ // "waiting on the founder rows to replicate" would be a second, misleading warning.
887
+ this.idleEscalated = true;
888
+ }
889
+
890
+ /** Decode the party key once; an undecodable key is terminal (nothing can be signed). */
891
+ private resolveKeyPair(): Ed25519KeyPair | undefined {
892
+ if (this.keyPair) return this.keyPair;
893
+ try {
894
+ this.keyPair = strandMemberKeyPair(this.deps.partyMemberPrivateKey);
895
+ } catch (error) {
896
+ this.finish(`the party membership key does not decode — nothing can be signed (${describeThrown(error)})`, true);
897
+ return undefined;
898
+ }
899
+ return this.keyPair;
900
+ }
901
+
902
+ /**
903
+ * Count a no-member/no-invitation pass; escalate to ONE visible warning at the bound.
904
+ *
905
+ * NOTE: an idling loop never gives up — a machine whose party is never admitted keeps
906
+ * polling for the life of the process, one `Strand.Member` scan per strand per
907
+ * interval (30 s by default). Negligible at the handful of strands a device runs and
908
+ * the handful of members a strand has; if a node ever runs strands by the hundred, or
909
+ * a strand's member set grows large, bound the idle phase (give up after N passes and
910
+ * surface it) rather than shortening the interval.
911
+ */
912
+ private noteIdlePass(): void {
913
+ this.lastPassIdle = true;
914
+ this.idlePasses += 1;
915
+ if (this.idlePasses >= IDLE_PASSES_BEFORE_ESCALATION && !this.idleEscalated) {
916
+ this.idleEscalated = true;
917
+ console.warn(
918
+ `[sereus] strand ${this.deps.label}: ${this.idlePasses} membership reconcile passes and still no `
919
+ + 'Member row for this party and no staged invitation — a joiner is waiting on the founder rows to '
920
+ + 'replicate (or on a manager admission). The loop keeps retrying quietly.'
921
+ );
922
+ }
923
+ }
924
+
925
+ /**
926
+ * Stop with a reason — the terminal and done paths' shared exit. `permanent` says whether
927
+ * a fresh invitation may reopen the loop ("Stops, and re-arming" in the module doc).
928
+ */
929
+ private finish(reason: string, permanent: boolean): void {
930
+ this.halt(`membership reconciliation stopping: ${reason}`, permanent);
931
+ }
932
+
933
+ /** Latch the stop and disarm the timer; a permanent latch sticks even on an already-stopped loop. */
934
+ private halt(reason: string, permanent: boolean): void {
935
+ if (permanent) this.permanentlyStopped = true;
936
+ if (this.stoppedFlag) return;
937
+ this.stoppedFlag = true;
938
+ this.clearTimer();
939
+ log('[%s] membership reconciler stopped%s: %s%s', this.deps.label, this.doneFlag ? ' (done)' : '', reason,
940
+ permanent ? '' : ' — a fresh invitation re-arms it');
941
+ }
942
+ }