@serfab/cadre-core 1.21.0 → 1.23.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 (109) hide show
  1. package/README.md +294 -294
  2. package/dist/cadre-node.d.ts +334 -53
  3. package/dist/cadre-node.js +794 -85
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-authorization.d.ts +32 -2
  6. package/dist/control-authorization.js +19 -0
  7. package/dist/control-authorization.js.map +1 -1
  8. package/dist/control-database.d.ts +236 -23
  9. package/dist/control-database.js +587 -173
  10. package/dist/control-database.js.map +1 -1
  11. package/dist/control-schema.d.ts +3 -3
  12. package/dist/control-schema.js +71 -7
  13. package/dist/control-schema.js.map +1 -1
  14. package/dist/ed25519-key.d.ts +8 -0
  15. package/dist/ed25519-key.js +11 -1
  16. package/dist/ed25519-key.js.map +1 -1
  17. package/dist/index.d.ts +5 -1
  18. package/dist/index.js +13 -1
  19. package/dist/index.js.map +1 -1
  20. package/dist/machine-removal.d.ts +51 -1
  21. package/dist/machine-removal.js +42 -1
  22. package/dist/machine-removal.js.map +1 -1
  23. package/dist/membership-connection-gater.d.ts +8 -0
  24. package/dist/membership-connection-gater.js +13 -1
  25. package/dist/membership-connection-gater.js.map +1 -1
  26. package/dist/membership-view.js +4 -1
  27. package/dist/membership-view.js.map +1 -1
  28. package/dist/owner-keys.js +2 -1
  29. package/dist/owner-keys.js.map +1 -1
  30. package/dist/owner-signer.js +3 -4
  31. package/dist/owner-signer.js.map +1 -1
  32. package/dist/peer-authorization.d.ts +14 -2
  33. package/dist/peer-authorization.js +24 -1
  34. package/dist/peer-authorization.js.map +1 -1
  35. package/dist/sealed-party-key.d.ts +32 -0
  36. package/dist/sealed-party-key.js +162 -0
  37. package/dist/sealed-party-key.js.map +1 -0
  38. package/dist/seed-bootstrap.d.ts +10 -3
  39. package/dist/seed-bootstrap.js +12 -0
  40. package/dist/seed-bootstrap.js.map +1 -1
  41. package/dist/strand-addr-protocol.d.ts +56 -6
  42. package/dist/strand-addr-protocol.js +57 -5
  43. package/dist/strand-addr-protocol.js.map +1 -1
  44. package/dist/strand-commit-durability.d.ts +33 -2
  45. package/dist/strand-commit-durability.js +44 -4
  46. package/dist/strand-commit-durability.js.map +1 -1
  47. package/dist/strand-database.d.ts +35 -5
  48. package/dist/strand-database.js +34 -10
  49. package/dist/strand-database.js.map +1 -1
  50. package/dist/strand-instance-manager.d.ts +200 -18
  51. package/dist/strand-instance-manager.js +434 -64
  52. package/dist/strand-instance-manager.js.map +1 -1
  53. package/dist/strand-membership-reconciler.d.ts +250 -51
  54. package/dist/strand-membership-reconciler.js +410 -66
  55. package/dist/strand-membership-reconciler.js.map +1 -1
  56. package/dist/strand-membership-writer.d.ts +7 -0
  57. package/dist/strand-membership-writer.js +9 -0
  58. package/dist/strand-membership-writer.js.map +1 -1
  59. package/dist/strand-party-key-rotation.d.ts +177 -0
  60. package/dist/strand-party-key-rotation.js +340 -0
  61. package/dist/strand-party-key-rotation.js.map +1 -0
  62. package/dist/strand-party-machines.d.ts +111 -0
  63. package/dist/strand-party-machines.js +258 -0
  64. package/dist/strand-party-machines.js.map +1 -0
  65. package/dist/strand-party-peers.d.ts +101 -0
  66. package/dist/strand-party-peers.js +49 -0
  67. package/dist/strand-party-peers.js.map +1 -0
  68. package/dist/strand-peer-redial.d.ts +34 -7
  69. package/dist/strand-peer-redial.js +46 -13
  70. package/dist/strand-peer-redial.js.map +1 -1
  71. package/dist/strand-revocation-enforcer.d.ts +15 -1
  72. package/dist/strand-revocation-enforcer.js +16 -9
  73. package/dist/strand-revocation-enforcer.js.map +1 -1
  74. package/dist/strand-transport-key.js +3 -0
  75. package/dist/strand-transport-key.js.map +1 -1
  76. package/dist/strand-watcher.d.ts +7 -4
  77. package/dist/strand-watcher.js +12 -7
  78. package/dist/strand-watcher.js.map +1 -1
  79. package/dist/types.d.ts +169 -13
  80. package/dist/types.js.map +1 -1
  81. package/package.json +9 -8
  82. package/src/cadre-node.ts +12280 -11528
  83. package/src/control-authorization.ts +41 -1
  84. package/src/control-database.ts +6123 -5603
  85. package/src/control-schema.ts +71 -7
  86. package/src/ed25519-key.ts +12 -1
  87. package/src/index.ts +957 -924
  88. package/src/machine-removal.ts +80 -1
  89. package/src/membership-connection-gater.ts +13 -1
  90. package/src/membership-view.ts +4 -1
  91. package/src/owner-keys.ts +2 -1
  92. package/src/owner-signer.ts +92 -94
  93. package/src/peer-authorization.ts +27 -3
  94. package/src/sealed-party-key.ts +190 -0
  95. package/src/seed-bootstrap.ts +17 -3
  96. package/src/strand-addr-protocol.ts +67 -6
  97. package/src/strand-commit-durability.ts +54 -5
  98. package/src/strand-database.ts +47 -11
  99. package/src/strand-instance-manager.ts +524 -65
  100. package/src/strand-membership-reconciler.ts +1310 -942
  101. package/src/strand-membership-writer.ts +10 -0
  102. package/src/strand-party-key-rotation.ts +436 -0
  103. package/src/strand-party-machines.ts +293 -0
  104. package/src/strand-party-peers.ts +129 -0
  105. package/src/strand-peer-redial.ts +61 -14
  106. package/src/strand-revocation-enforcer.ts +27 -9
  107. package/src/strand-transport-key.ts +3 -0
  108. package/src/strand-watcher.ts +12 -7
  109. package/src/types.ts +3121 -2963
@@ -1,7 +1,8 @@
1
1
  import debug from 'debug';
2
2
  import type { Libp2p, PrivateKey } from '@libp2p/interface';
3
+ import type { ICohortReachability } from '@optimystic/db-core';
3
4
  import { createLibp2pNode, type IRawStorage } from '@optimystic/db-p2p';
4
- import { wrapStorageWithCache, disposeStorageCache } from '@serfab/quereus-plugin-sereus';
5
+ import { wrapStorageWithCache, disposeStorageCache, checkAppSchema, appSchemaRefusalOf } from '@serfab/quereus-plugin-sereus';
5
6
  import { StrandDatabase, type StrandDatabaseOffline } from './strand-database.js';
6
7
  import type { StrandCommitDurability, StrandCommitHeld } from './strand-commit-durability.js';
7
8
  import type { StrandOfflineConfig, StrandOfflineListeners, StrandOfflineMode } from './strand-offline.js';
@@ -20,6 +21,8 @@ import {
20
21
  type StrandMembershipReconciliationConfig
21
22
  } from './strand-membership-reconciler.js';
22
23
  import { removeMemberPeer } from './strand-membership-writer.js';
24
+ import type { PartyStrandPeer, PartyStrandPeerSource } from './strand-party-peers.js';
25
+ import { StrandPartyMachines, cohortGateWaitingForMachines, watchRemovedMachinesInSeed } from './strand-party-machines.js';
23
26
  import { strandMemberKeyPair } from './strand-member-key.js';
24
27
  import { assertSchemaSignature } from './schema-verification.js';
25
28
  import { assertStrandScopeKey } from './storage-scope.js';
@@ -77,6 +80,17 @@ type StrandDatabaseBuild = 'built' | 'awaiting-seed' | 'released';
77
80
 
78
81
  const timing = debug('sereus:cadre:timing');
79
82
 
83
+ /**
84
+ * An sApp claim of a storage replica ({@link StrandInstanceManager.attachSApp}) that the retained
85
+ * launch config carries and that has not been applied to the strand yet.
86
+ */
87
+ interface UnappliedAttach {
88
+ /** The claiming sApp's config, as the retained launch config holds it. */
89
+ sAppConfig: SAppConfig;
90
+ /** The instance's latency hint before the claim, for a fallback to the replica to put back. */
91
+ latencyHint: LatencyHint;
92
+ }
93
+
80
94
  /** One caller blocked in {@link StrandInstanceManager.whenWritable}. */
81
95
  interface WritableWaiter {
82
96
  resolve: () => void;
@@ -249,6 +263,42 @@ export interface StartStrandConfig {
249
263
  */
250
264
  membershipReconciliation?: StrandMembershipReconciliationConfig;
251
265
 
266
+ /**
267
+ * The party's machines in THIS strand, as the control database records them
268
+ * (`strand-party-peers.ts`): `CadreNode.launchStrand` wires it for every strand, open or
269
+ * closed, party key or not. Bring-up publishes this machine's own `StrandPeer` row through it
270
+ * in the background, once the strand's libp2p node exists (launch and hibernation resume
271
+ * alike, since the row is this machine's statement of a peer id that is the same across
272
+ * both). On a closed strand the membership reconciler reads the party's other machines
273
+ * through it to bind them (`strand-membership-reconciler.ts` → "Binding the party's other
274
+ * machines"); on a node offering offline mode ({@link offline}) the queue's gate reads them
275
+ * as the machines a queued transaction waits for (`strand-party-machines.ts`). An open
276
+ * strand's row serves only that wait. Retained with the launch config.
277
+ */
278
+ partyPeers?: PartyStrandPeerSource;
279
+
280
+ /**
281
+ * Called when the membership reconciler finds the party's PENDING membership key seated as a
282
+ * `Strand.Member` in this strand (`strand-membership-reconciler.ts` → "Redeeming under the
283
+ * pending key"): it redeemed the host's fresh invitation under that key, or another party's
284
+ * manager admitted the key by hand. `CadreNode` wires it to its party key rotation driver,
285
+ * which then finishes the move on an owner machine the key is sealed to
286
+ * (`strand-party-key-rotation.ts`). Called on every pass that sees the seat until the control
287
+ * record is swapped, so the receiver refuses cheaply when it cannot drive. Retained with the
288
+ * launch config.
289
+ */
290
+ onPartyKeySeated?: (strandId: string) => void;
291
+
292
+ /**
293
+ * Called when a read of the party's machines finds one removed from the cadre in
294
+ * {@link bootstrapNodes}, on a node tracking them ({@link offline} with {@link partyPeers}), and
295
+ * once per such machine ({@link watchRemovedMachinesInSeed}). The node refuses that peer but
296
+ * cannot drop it from its frozen seed, so its queue stays held until a new node is built from a
297
+ * fresh seed: `CadreNode` quiesces and resumes the runtime. May be called during a build or a
298
+ * rebuild, so the receiver serializes. Retained with the launch config.
299
+ */
300
+ onRemovedMachineInSeed?: (strandId: string) => void;
301
+
252
302
  /**
253
303
  * Called when THIS node's own peer id turns up in the strand's revoked set —
254
304
  * this node's party was removed from the closed strand, or left it. Fires once
@@ -369,6 +419,12 @@ export interface ResumeStrandOverrides {
369
419
  * {@link StartStrandConfig} does — it retains the last value; see `resumeStrand`.
370
420
  */
371
421
  servingMachines?: number;
422
+ /**
423
+ * The party's membership key for a closed strand as the control record names it now
424
+ * (`StrandPartyKey.PrivateKey`), re-read by `CadreNode.resumeStrandRuntime` because a party
425
+ * key rotation can finish while the strand hibernates. Omitted, the retained key stands.
426
+ */
427
+ partyMemberPrivateKey?: string;
372
428
  }
373
429
 
374
430
  /** A {@link StrandInstanceManager.resumeStrand} or {@link StrandInstanceManager.quiesceStrand} of one strand. */
@@ -534,6 +590,21 @@ export class StrandInstanceManager {
534
590
  * nobody and a resume redials over the new node.
535
591
  */
536
592
  private peerRedials: Map<string, StrandPeerRedial> = new Map();
593
+ /**
594
+ * The party's other machines known to hold each strand (`strand-party-machines.ts`), keyed
595
+ * by strand id, on a node offering offline mode for a launch with a party-machine seam. Same
596
+ * lifecycle as {@link peerRedials}: built in `buildStrandRuntime` before the libp2p node (the
597
+ * node's redial loop, the database's offline gate and its commit record read it), stopped and dropped in
598
+ * `releaseRuntime`, so a resume reads the control database afresh. Refreshed by
599
+ * {@link notifyPartyPeersChanged}.
600
+ */
601
+ private partyMachines: Map<string, StrandPartyMachines> = new Map();
602
+ /**
603
+ * Per strand, the removed machines' peer ids a rebuild was asked for
604
+ * ({@link watchRemovedMachinesInSeed}). Outlives a runtime, which is its point: it is what stops
605
+ * a rebuilt node whose seed still names one from asking again. Dropped with the launch config.
606
+ */
607
+ private seedRemovalsAnnounced: Map<string, Set<string>> = new Map();
537
608
  /**
538
609
  * The resolved (cache-wrapped) raw storage per strand id — the instance's OWN
539
610
  * store, resolved once in `startStrand` and held until `stopStrand` disposes it.
@@ -578,6 +649,14 @@ export class StrandInstanceManager {
578
649
  * {@link releaseRuntime}, so a stop or a quiesce cancels it.
579
650
  */
580
651
  private unreachableJoinRetries: Map<string, unknown> = new Map();
652
+ /**
653
+ * Per strand id, the sApp claim ({@link attachSApp}) whose schema the retained launch config
654
+ * carries but no apply has landed yet: the claim found no live database, or its live apply failed
655
+ * for a reason that may pass. Lets a build that refuses that schema fall back to the replica
656
+ * ({@link revertRefusedAttach}). Deleted when a database applies the schema, by that fallback,
657
+ * and when {@link stopStrand} begins.
658
+ */
659
+ private unappliedAttaches: Map<string, UnappliedAttach> = new Map();
581
660
  /**
582
661
  * The offline mode set per strand id ({@link setOfflineMode}); a strand absent here runs in its
583
662
  * launch's `initialMode`. Never cleared: the mode belongs to the strand, not to one database, so
@@ -713,6 +792,7 @@ export class StrandInstanceManager {
713
792
  // reads both, and a config without an instance would strand the config.
714
793
  this.instances.delete(strandId);
715
794
  this.launchConfigs.delete(strandId);
795
+ this.seedRemovalsAnnounced.delete(strandId);
716
796
  // The cleanup above remembered the half-built database's queue; an untracked strand keeps none.
717
797
  this.closedQueues.delete(strandId);
718
798
  // The store this launch resolved goes with it: nothing owns it any more, and a
@@ -842,7 +922,11 @@ export class StrandInstanceManager {
842
922
  // therefore means "no transport right now", which the enforcer
843
923
  // treats as "nothing to tear down".
844
924
  getNetwork: () => instance.libp2pNode,
845
- onSelfRevoked: () => config.onSelfRevoked?.(strandId)
925
+ onSelfRevoked: () => config.onSelfRevoked?.(strandId),
926
+ // The membership reconciler below stops on a self-revocation ("stop rather than
927
+ // fight"); a sibling binding this machine back in is what restarts it. Looked up
928
+ // at call time: the reconciler is built after the enforcer, and dropped with it.
929
+ onSelfRestored: () => this.rearmMembershipReconciler(strandId, 'this machine is no longer revoked')
846
930
  }, config.revocationEnforcement)
847
931
  : undefined;
848
932
  if (revocationEnforcer) {
@@ -867,12 +951,37 @@ export class StrandInstanceManager {
867
951
  log('strand %s: change notifications on', strandId);
868
952
  }
869
953
 
954
+ // The party's other machines holding this strand, for the offline queue's gate, each commit's
955
+ // durability record and the redial loop below (`strand-party-machines.ts`). Only a node offering offline mode pays
956
+ // for the control reads, which leaves out the always-on programs. Built BEFORE the libp2p
957
+ // node, and its first read started now, so a queue restored at launch waits on rows that
958
+ // were asked for before the node existed. Registered in the map at once, so the failure
959
+ // rollback (releaseRuntime) stops it like every other runtime component.
960
+ const partyMachines = config.offline && config.partyPeers
961
+ ? new StrandPartyMachines({ label: strandId, source: config.partyPeers })
962
+ : undefined;
963
+ if (partyMachines) {
964
+ this.partyMachines.set(strandId, partyMachines);
965
+ this.watchSeedForRemovedMachines(strandId, config, partyMachines);
966
+ partyMachines.refresh();
967
+ }
968
+
870
969
  try {
871
970
  let t0 = performance.now();
872
971
  const node = await createLibp2pNode({
873
972
  port: 0, // Random port
874
973
  bootstrapNodes: config.bootstrapNodes ?? [],
875
974
  networkName,
975
+ // A machine removed from the party stops counting as a member, ahead of whatever this node
976
+ // remembers of it, so a queue stops waiting for it. Read live, and everyone else takes the
977
+ // path they would with no predicate.
978
+ //
979
+ // NOTE: a machine can state any id in its own `StrandPeer` row before its removal, and that
980
+ // id is then refused here, leaving that peer out of this node's cohorts. One id per
981
+ // (strand, machine), in a row a machine the party trusted then signed, and an id a live
982
+ // sibling recorded is never read as removed. If a peer is ever seen left out of cohorts
983
+ // this way, the row needs a proof that the id it states is the machine's own.
984
+ ...(partyMachines && { isNetworkMember: (peerId: string) => !partyMachines.removed().has(peerId) }),
876
985
  storage: strandStorage,
877
986
  fretProfile: config.profile === 'storage' ? 'core' : 'edge',
878
987
  relay: relayServer.enabled,
@@ -969,6 +1078,17 @@ export class StrandInstanceManager {
969
1078
 
970
1079
  instance.libp2pNode = node;
971
1080
 
1081
+ // This machine's statement of its peer id in the strand, for the party's control
1082
+ // database (`StrandPeer`): a background write that never fails or delays the launch.
1083
+ // The seam defers it while a write could fork the party and retries it on cohort
1084
+ // growth and from every membership reconciler pass, so a refusal here is not final.
1085
+ // Written for open strands too: their row is what a sibling's offline queue waits for.
1086
+ if (config.partyPeers) {
1087
+ void config.partyPeers.publishOwn(node.peerId.toString()).catch((error) => {
1088
+ log('Strand %s: publishing this machine\'s StrandPeer row threw (retried later): %o', strandId, error);
1089
+ });
1090
+ }
1091
+
972
1092
  // One reservation supervisor PER RELAY, started now so the first attempts
973
1093
  // overlap the database bring-up below (the relay is never in a strand's
974
1094
  // Optimystic cohort — its protocol ids are namespaced `/optimystic/strand-<id>/…`
@@ -981,12 +1101,20 @@ export class StrandInstanceManager {
981
1101
  // declared link gives a relayed dial — what reconnects two restarted phones on a slow
982
1102
  // link, where FRET's own redial cannot (`strand-peer-redial.ts`). The relays are
983
1103
  // excluded by peer id: the node is connected to them throughout, and they are no member.
1104
+ // The party's machines holding the strand are dialed too, at the addresses the
1105
+ // strand-addr RPC put in the address book, so a sibling's blocked port that opens is
1106
+ // reached without a connection ever having been made to it.
1107
+ // A machine removed from the party is revoked to this loop on an open strand too: neither a
1108
+ // peer to dial nor a connection that stands in for reaching the party's other machines.
984
1109
  this.peerRedials.set(strandId, superviseStrandPeerRedial({
985
1110
  label: strandId,
986
1111
  node,
987
1112
  seed: config.bootstrapNodes ?? [],
988
1113
  excluded: new Set(groupAddrsByPeerId([...relayDialAddrs]).keys()),
989
- ...(revocationEnforcer && { isRevoked: (peerId: string) => revocationEnforcer.isRevoked(peerId) })
1114
+ ...((revocationEnforcer || partyMachines) && {
1115
+ isRevoked: (peerId: string) => revocationEnforcer?.isRevoked(peerId) === true || partyMachines?.removed().has(peerId) === true
1116
+ }),
1117
+ ...(partyMachines && { partyMachines: () => partyMachines.machines().map((machine) => machine.strandPeerId) })
990
1118
  }, strandRedialTimings(config.network?.linkRoundTripMs)));
991
1119
 
992
1120
  const databaseBuild = await this.buildStrandDatabase(instance, config, node);
@@ -1012,30 +1140,7 @@ export class StrandInstanceManager {
1012
1140
  // (`bindFounderPeer`), so the first pass finds them and stops. Armed AFTER the database
1013
1141
  // phase above, so a gated or deferred launch always has a reconciler registered by the
1014
1142
  // time it can publish.
1015
- if (config.strandRow.Type === 'c' && config.partyMemberPrivateKey
1016
- && config.membershipReconciliation?.enabled !== false) {
1017
- const reconciler = new StrandMembershipReconciler({
1018
- label: strandId,
1019
- partyMemberPrivateKey: config.partyMemberPrivateKey,
1020
- // Read per pass, never captured — same lifecycle argument as the
1021
- // enforcer's getNetwork: quiesce drops both handles.
1022
- getDatabase: () => instance.database?.getDatabase(),
1023
- getOwnPeerId: () => instance.libp2pNode?.peerId.toString(),
1024
- pendingInvite: config.pendingMembershipInvite,
1025
- // The enforcer's CURRENT snapshot view of this node's own peer id — the
1026
- // reconciler stops rather than fight a self-revocation. Absent when the
1027
- // gate is disarmed (fail-open: the loop just runs).
1028
- isSelfRevoked: revocationEnforcer
1029
- ? () => {
1030
- const ownPeerId = instance.libp2pNode?.peerId.toString();
1031
- return ownPeerId !== undefined && revocationEnforcer.isRevoked(ownPeerId);
1032
- }
1033
- : undefined,
1034
- onRejoinBlocked: () => config.onRejoinBlocked?.(strandId)
1035
- }, config.membershipReconciliation);
1036
- this.membershipReconcilers.set(strandId, reconciler);
1037
- reconciler.start();
1038
- }
1143
+ this.armMembershipReconciler(instance, config, revocationEnforcer);
1039
1144
 
1040
1145
  // Peer-join block catch-up: push this strand's own blocks to each newly
1041
1146
  // connected peer, so a machine that joined after blocks were committed
@@ -1142,6 +1247,7 @@ export class StrandInstanceManager {
1142
1247
  // a partially-initialized db), and the app only ever sees `instance.database` once this
1143
1248
  // machine is allowed to write to the strand.
1144
1249
  let t0 = performance.now();
1250
+ const partyMachines = this.partyMachines.get(strandId);
1145
1251
  const strandDb = new StrandDatabase({
1146
1252
  strandId,
1147
1253
  sAppConfig: config.sAppConfig,
@@ -1161,8 +1267,9 @@ export class StrandInstanceManager {
1161
1267
  bindFounderPeer: config.membershipReconciliation?.enabled !== false,
1162
1268
  onCommitDurability: config.onCommitDurability,
1163
1269
  onCommitHeld: config.onCommitHeld,
1164
- offline: this.offlineDatabaseConfig(strandId, config.offline),
1165
- appSchema: config.appSchema
1270
+ offline: this.offlineDatabaseConfig(strandId, config.offline, this.offlineCohortGate(strandId, node)),
1271
+ appSchema: config.appSchema,
1272
+ ...(partyMachines && { partyMachines: () => partyMachines.machines() })
1166
1273
  });
1167
1274
  const storageRepo = node.storageRepo;
1168
1275
  const gate = new StrandFirstSyncGate({
@@ -1200,6 +1307,7 @@ export class StrandInstanceManager {
1200
1307
  await strandDb.close();
1201
1308
  return 'released';
1202
1309
  }
1310
+ this.forgetAppliedAttach(strandId, config.sAppConfig, strandDb);
1203
1311
 
1204
1312
  // The first-sync write gate. A founder just wrote the Header in its bootstrap; any
1205
1313
  // other machine may commit only once it holds the Header — which it can only have
@@ -1238,10 +1346,14 @@ export class StrandInstanceManager {
1238
1346
 
1239
1347
  /**
1240
1348
  * One build's {@link StrandDatabaseOffline}: the strand's journal, which the database resolves as
1241
- * it initializes (a throw or rejection fails the build), and the strand's mode, which it reads each
1242
- * time it applies it.
1349
+ * it initializes (a throw or rejection fails the build), the strand's mode, which it reads each
1350
+ * time it applies it, and the gate its queue asks, when one could be built.
1243
1351
  */
1244
- private offlineDatabaseConfig(strandId: string, offline: StartStrandConfig['offline']): StrandDatabaseOffline | undefined {
1352
+ private offlineDatabaseConfig(
1353
+ strandId: string,
1354
+ offline: StartStrandConfig['offline'],
1355
+ cohortReachability: ICohortReachability | undefined
1356
+ ): StrandDatabaseOffline | undefined {
1245
1357
  if (!offline) {
1246
1358
  return undefined;
1247
1359
  }
@@ -1249,10 +1361,64 @@ export class StrandInstanceManager {
1249
1361
  return {
1250
1362
  ...listeners,
1251
1363
  journal: () => journal(strandId),
1252
- mode: () => this.currentOfflineMode(strandId, offline)
1364
+ mode: () => this.currentOfflineMode(strandId, offline),
1365
+ ...(cohortReachability && { cohortReachability })
1253
1366
  };
1254
1367
  }
1255
1368
 
1369
+ /**
1370
+ * The gate a build's offline queue asks: the node's own, closed also while the party has
1371
+ * machines holding the strand that this node is alone in a cohort without
1372
+ * (`cohortGateWaitingForMachines`). None when the launch tracks no party machines (no offline
1373
+ * mode, or no party-machine seam), or when the node carries no gate or key network to compose
1374
+ * over; the queue then asks the node's own gate, as before.
1375
+ */
1376
+ private offlineCohortGate(strandId: string, node: Libp2pNodeWithRepo): ICohortReachability | undefined {
1377
+ const partyMachines = this.partyMachines.get(strandId);
1378
+ if (!partyMachines) {
1379
+ return undefined;
1380
+ }
1381
+ if (!node.cohortReachability || !node.keyNetwork) {
1382
+ log('Strand %s: its node carries no %s, so its offline queue does not wait for the party\'s machines',
1383
+ strandId, node.cohortReachability ? 'key network' : 'reachability gate');
1384
+ return undefined;
1385
+ }
1386
+ return cohortGateWaitingForMachines(node.cohortReachability, node.keyNetwork, node.peerId.toString(), partyMachines);
1387
+ }
1388
+
1389
+ /** Ask the launcher for a rebuild when a machine removed from the party is in this runtime's seed. */
1390
+ private watchSeedForRemovedMachines(strandId: string, config: StartStrandConfig, machines: StrandPartyMachines): void {
1391
+ const { onRemovedMachineInSeed } = config;
1392
+ if (!onRemovedMachineInSeed) {
1393
+ return;
1394
+ }
1395
+ let announced = this.seedRemovalsAnnounced.get(strandId);
1396
+ if (!announced) {
1397
+ announced = new Set();
1398
+ this.seedRemovalsAnnounced.set(strandId, announced);
1399
+ }
1400
+ const seedPeers = new Set(groupAddrsByPeerId(config.bootstrapNodes ?? []).keys());
1401
+ watchRemovedMachinesInSeed(machines, seedPeers, announced, () => onRemovedMachineInSeed(strandId), strandId);
1402
+ }
1403
+
1404
+ /**
1405
+ * The party's other machines known to hold `strandId` with no open connection from its strand
1406
+ * node: what an offline queue reporting `waitingFor: 'cohort'` may be waiting for
1407
+ * (`docs/strands.md` → "Waiting for the party's own machines"). Empty for a strand not tracked
1408
+ * or not running here, and on a launch that tracks no party machines.
1409
+ */
1410
+ unreachedPartyMachines(strandId: string): readonly PartyStrandPeer[] {
1411
+ const partyMachines = this.partyMachines.get(strandId);
1412
+ const node = this.instances.get(strandId)?.libp2pNode;
1413
+ if (!partyMachines || !node) {
1414
+ return [];
1415
+ }
1416
+ const connected = new Set(node.getConnections()
1417
+ .filter((connection) => connection.status === 'open')
1418
+ .map((connection) => connection.remotePeer.toString()));
1419
+ return partyMachines.machines().filter((machine) => !connected.has(machine.strandPeerId));
1420
+ }
1421
+
1256
1422
  /**
1257
1423
  * Whether this strand's raw store holds no block. False for a store that cannot list its
1258
1424
  * blocks, or whose listing fails, so such a launch probes at once.
@@ -1315,7 +1481,8 @@ export class StrandInstanceManager {
1315
1481
  * runtime still attached. Skipped when the strand was stopped or released since — a quiesce
1316
1482
  * releases it and the resume after rebuilds the whole runtime — or already has a database.
1317
1483
  * A failure other than an unanswered seed releases the runtime and marks the strand
1318
- * `'error'`, as a failed resume does.
1484
+ * `'error'`, as a failed resume does, unless it is a refusal of a claim's schema the replica
1485
+ * can fall back from ({@link buildJoinDatabaseOrReplica}).
1319
1486
  */
1320
1487
  private async retryUnreachableJoin(instance: StrandInstance): Promise<void> {
1321
1488
  const strandId = instance.strandId;
@@ -1330,7 +1497,7 @@ export class StrandInstanceManager {
1330
1497
  try {
1331
1498
  // Tracked like any runtime build, so a wake, a quiesce or an sApp attach waits for it
1332
1499
  // rather than acting on a database that is still initializing.
1333
- build = await this.trackRuntimeBuild(strandId, this.buildStrandDatabase(instance, config, node));
1500
+ build = await this.trackRuntimeBuild(strandId, this.buildJoinDatabaseOrReplica(instance, config, node));
1334
1501
  } catch (error) {
1335
1502
  if (!this.isCurrentRuntime(instance, node)) {
1336
1503
  log('Strand %s: a database retry failed after its runtime was released: %o', strandId, error);
@@ -1349,6 +1516,39 @@ export class StrandInstanceManager {
1349
1516
  }
1350
1517
  }
1351
1518
 
1519
+ /**
1520
+ * A deferred join's database phase ({@link buildStrandDatabase}), run once more as the replica
1521
+ * when it fails on the schema of a claim that has not applied yet ({@link revertRefusedAttach}).
1522
+ * The failed attempt's database is closed first: a failure leaves it registered with its gate.
1523
+ * `'released'` when a stop began while it closed.
1524
+ */
1525
+ private async buildJoinDatabaseOrReplica(
1526
+ instance: StrandInstance,
1527
+ config: StartStrandConfig,
1528
+ node: Libp2pNodeWithRepo
1529
+ ): Promise<StrandDatabaseBuild> {
1530
+ try {
1531
+ return await this.buildStrandDatabase(instance, config, node);
1532
+ } catch (error) {
1533
+ const replicaConfig = this.isCurrentRuntime(instance, node)
1534
+ ? this.revertRefusedAttach(instance, config.sAppConfig, error)
1535
+ : undefined;
1536
+ if (!replicaConfig) {
1537
+ throw error;
1538
+ }
1539
+ const failedAttempt = this.firstSyncGates.get(instance.strandId);
1540
+ if (failedAttempt) {
1541
+ await this.discardDatabaseAttempt(instance.strandId, failedAttempt);
1542
+ }
1543
+ if (!this.isCurrentRuntime(instance, node) || instance.status === 'stopping') {
1544
+ // A stop that began while the failed attempt closed found no gate to release, so a
1545
+ // database built now would outlive the stop, open and unreleased.
1546
+ return 'released';
1547
+ }
1548
+ return await this.buildStrandDatabase(instance, replicaConfig, node);
1549
+ }
1550
+ }
1551
+
1352
1552
  /** Whether `instance` is still tracked, with `node` still its runtime's libp2p node. */
1353
1553
  private isCurrentRuntime(instance: StrandInstance, node: Libp2p): boolean {
1354
1554
  return !this.stopping && this.instances.get(instance.strandId) === instance && instance.libp2pNode === node;
@@ -1384,6 +1584,9 @@ export class StrandInstanceManager {
1384
1584
  }
1385
1585
  this.peerRedials.get(instance.strandId)?.stop();
1386
1586
  this.peerRedials.delete(instance.strandId);
1587
+ // The party-machine tracker with the loop and gate that read it; a resume reads afresh.
1588
+ this.partyMachines.get(instance.strandId)?.stop();
1589
+ this.partyMachines.delete(instance.strandId);
1387
1590
  // Backfill next — before the database closes and the libp2p node stops — so
1388
1591
  // no NEW catch-up push is issued against a torn-down transport. A push already
1389
1592
  // in flight is not awaited; it fails into the module's own per-chunk catch.
@@ -1541,12 +1744,146 @@ export class StrandInstanceManager {
1541
1744
  * loop's own serialized chain and never rejects.
1542
1745
  */
1543
1746
  notifyMembershipInviteStaged(strandId: string): void {
1747
+ if (!this.rearmMembershipReconciler(strandId, 'a fresh invitation')) {
1748
+ log('notifyMembershipInviteStaged: strand %s has no armed membership reconciler — bring-up will find the invitation', strandId);
1749
+ }
1750
+ }
1751
+
1752
+ /**
1753
+ * The party's machines changed in the control database — a `StrandPeer` row, a `CadrePeer`
1754
+ * row or a tombstone arrived or was written here (`CadreNode`'s watch on those tables,
1755
+ * coalesced). Re-arm every armed membership reconciler, so a sibling's row is bound, or a
1756
+ * removed machine's binding cleared, within the watch's window rather than at the next
1757
+ * resume, and read every strand's party machines again, so an offline queue waits for a
1758
+ * machine as soon as its row arrives and stops waiting for one as soon as it is removed.
1759
+ * Table events carry no row keys, so every strand's loop and tracker is woken; a loop with
1760
+ * nothing to do confirms and stops again. Returns at once; each pass runs on its loop's own
1761
+ * serialized chain and never rejects.
1762
+ */
1763
+ notifyPartyPeersChanged(): void {
1764
+ for (const strandId of this.membershipReconcilers.keys()) {
1765
+ this.rearmMembershipReconciler(strandId, 'a change to the party\'s machines');
1766
+ }
1767
+ for (const partyMachines of this.partyMachines.values()) {
1768
+ partyMachines.refresh();
1769
+ }
1770
+ }
1771
+
1772
+ /** Re-arm `strandId`'s membership reconciler for `cause`; `false` when none is armed. */
1773
+ private rearmMembershipReconciler(strandId: string, cause: string): boolean {
1544
1774
  const reconciler = this.membershipReconcilers.get(strandId);
1545
1775
  if (!reconciler) {
1546
- log('notifyMembershipInviteStaged: strand %s has no armed membership reconciler — bring-up will find the invitation', strandId);
1776
+ return false;
1777
+ }
1778
+ void reconciler.rearm(cause);
1779
+ return true;
1780
+ }
1781
+
1782
+ /**
1783
+ * Build and start `instance`'s membership reconciler from `config`, for a closed strand that
1784
+ * carries the party's own membership key with the loop enabled; nothing otherwise. Called by
1785
+ * {@link buildStrandRuntime} after the database phase, and by {@link rekeyParty} over a
1786
+ * running instance with the re-keyed config. Every dependency is read per pass, never
1787
+ * captured, so the loop follows the instance through quiesce and resume.
1788
+ */
1789
+ private armMembershipReconciler(
1790
+ instance: StrandInstance,
1791
+ config: StartStrandConfig,
1792
+ revocationEnforcer: StrandRevocationEnforcer | undefined
1793
+ ): void {
1794
+ if (config.strandRow.Type !== 'c' || !config.partyMemberPrivateKey || config.membershipReconciliation?.enabled === false) {
1547
1795
  return;
1548
1796
  }
1549
- void reconciler.rearm();
1797
+ const strandId = instance.strandId;
1798
+ const reconciler = new StrandMembershipReconciler({
1799
+ label: strandId,
1800
+ partyMemberPrivateKey: config.partyMemberPrivateKey,
1801
+ // Read per pass, never captured — same lifecycle argument as the
1802
+ // enforcer's getNetwork: quiesce drops both handles.
1803
+ getDatabase: () => instance.database?.getDatabase(),
1804
+ getOwnPeerId: () => instance.libp2pNode?.peerId.toString(),
1805
+ pendingInvite: config.pendingMembershipInvite,
1806
+ partyPeers: config.partyPeers,
1807
+ // The enforcer's CURRENT snapshot view of this node's own peer id — the
1808
+ // reconciler stops rather than fight a self-revocation. Absent when the
1809
+ // gate is disarmed (fail-open: the loop just runs).
1810
+ isSelfRevoked: revocationEnforcer
1811
+ ? () => {
1812
+ const ownPeerId = instance.libp2pNode?.peerId.toString();
1813
+ return ownPeerId !== undefined && revocationEnforcer.isRevoked(ownPeerId);
1814
+ }
1815
+ : undefined,
1816
+ onRejoinBlocked: () => config.onRejoinBlocked?.(strandId),
1817
+ onPendingKeySeated: () => config.onPartyKeySeated?.(strandId)
1818
+ }, config.membershipReconciliation);
1819
+ this.membershipReconcilers.set(strandId, reconciler);
1820
+ reconciler.start();
1821
+ }
1822
+
1823
+ /**
1824
+ * Move a tracked closed strand onto `partyMemberPrivateKey`, the party's membership key the
1825
+ * control record now names (a party key rotation finished here or replicated from the machine
1826
+ * that finished it: `strand-party-key-rotation.ts`). The retained launch config is replaced
1827
+ * with a fresh object carrying the key ({@link foundExistingStrand}'s idiom: the caller's
1828
+ * config object is not ours to rewrite), so every later resume rebuilds under it, and the
1829
+ * founder bootstrap a resume re-runs derives from it (insert-if-absent; the strand's rows
1830
+ * already hold the new key as member and manager, so it writes nothing). The running
1831
+ * instance's membership reconciler, which signs with the key, is stopped and awaited, then
1832
+ * rebuilt and started over the re-keyed config, so its next pass binds under the new key.
1833
+ *
1834
+ * A tracked instance with no party key before (a storage replica launched before the party's
1835
+ * row reached this node) is keyed the same way and gains its reconciler now rather than at its
1836
+ * next resume. A build in flight is waited out first, so the reconciler it arms is the one
1837
+ * replaced here rather than a second one beside it; a key the retained config already names
1838
+ * is answered before that wait, since the party key watch asks this for every tracked closed
1839
+ * strand on every change to the key tables.
1840
+ *
1841
+ * @returns `rekeyed` when a running instance's reconciler was rebuilt; `retained` when only the
1842
+ * config changed (a hibernating instance, or one with the loop disabled); `unchanged` when
1843
+ * the key already matched or the strand is open; `untracked` when the strand is not here.
1844
+ */
1845
+ async rekeyParty(strandId: string, partyMemberPrivateKey: string): Promise<'rekeyed' | 'retained' | 'unchanged' | 'untracked'> {
1846
+ const before = this.rekeyNeeded(strandId, partyMemberPrivateKey);
1847
+ if (before !== 'needed') {
1848
+ return before;
1849
+ }
1850
+ await this.settleRuntimeBuilds(strandId);
1851
+ const after = this.rekeyNeeded(strandId, partyMemberPrivateKey);
1852
+ if (after !== 'needed') {
1853
+ return after;
1854
+ }
1855
+ const instance = this.instances.get(strandId)!;
1856
+ const config = this.launchConfigs.get(strandId)!;
1857
+ const rekeyed: StartStrandConfig = { ...config, partyMemberPrivateKey };
1858
+ this.launchConfigs.set(strandId, rekeyed);
1859
+ const reconciler = this.membershipReconcilers.get(strandId);
1860
+ if (reconciler) {
1861
+ reconciler.stop();
1862
+ await reconciler.settle();
1863
+ this.membershipReconcilers.delete(strandId);
1864
+ }
1865
+ if (!instance.libp2pNode || this.isQuiescing(strandId)) {
1866
+ log('rekeyParty: strand %s has no live runtime; the re-keyed config waits for its resume', strandId);
1867
+ return 'retained';
1868
+ }
1869
+ this.armMembershipReconciler(instance, rekeyed, this.revocationEnforcers.get(strandId));
1870
+ const armed = this.membershipReconcilers.has(strandId);
1871
+ log('rekeyParty: strand %s re-keyed (%s)', strandId, armed ? 'membership reconciler rebuilt' : 'membership reconciliation disabled');
1872
+ return armed ? 'rekeyed' : 'retained';
1873
+ }
1874
+
1875
+ /** Whether {@link rekeyParty} has anything to do for `strandId`: the retained config is a closed strand's and names another key. */
1876
+ private rekeyNeeded(strandId: string, partyMemberPrivateKey: string): 'needed' | 'unchanged' | 'untracked' {
1877
+ const config = this.launchConfigs.get(strandId);
1878
+ if (!config || !this.instances.has(strandId)) {
1879
+ return 'untracked';
1880
+ }
1881
+ return config.strandRow.Type !== 'c' || config.partyMemberPrivateKey === partyMemberPrivateKey ? 'unchanged' : 'needed';
1882
+ }
1883
+
1884
+ /** The ids of every tracked closed strand, running or hibernating. */
1885
+ trackedClosedStrandIds(): string[] {
1886
+ return [...this.launchConfigs].filter(([, config]) => config.strandRow.Type === 'c').map(([strandId]) => strandId);
1550
1887
  }
1551
1888
 
1552
1889
  /**
@@ -1566,13 +1903,16 @@ export class StrandInstanceManager {
1566
1903
  * and its in-flight pass awaited — FIRST, so a pass that was already past its
1567
1904
  * own stopped check cannot re-register the binding this is about to clear.
1568
1905
  *
1569
- * NOTE: deliberately NOT handled here (or anywhere yet): clearing the bindings
1570
- * of a machine removed from the CADRE at the control layer, or of a party's
1571
- * OTHER machines when the party unpublishes — the party still holds the key on
1572
- * every surviving machine and can clear from any of them, and the stale rows
1573
- * grant nothing while admission is deny-list only. Revisit when
1574
- * `feat-strand-member-allowlist-admission` lands and a stale binding starts
1575
- * granting admission rather than merely mis-crediting diversity.
1906
+ * A machine removed from the CADRE at the control layer is not cleared here either: the
1907
+ * party replaces its key in the strand instead (`strand-party-key-rotation.ts`), which
1908
+ * leaves that machine's binding an orphan the revoked-peer gate denies, and the membership
1909
+ * reconciler clears what a lagging sibling wrote under the new key.
1910
+ *
1911
+ * NOTE: deliberately NOT handled here (or anywhere yet): clearing the bindings of a party's
1912
+ * OTHER machines when the party unpublishes — the party still holds the key on every
1913
+ * surviving machine and can clear from any of them, and the stale rows grant nothing while
1914
+ * admission is deny-list only. Revisit when `feat-strand-member-allowlist-admission` lands
1915
+ * and a stale binding starts granting admission rather than merely mis-crediting diversity.
1576
1916
  */
1577
1917
  async clearOwnMemberPeerBinding(strandId: string): Promise<void> {
1578
1918
  const instance = this.instances.get(strandId);
@@ -1755,13 +2095,14 @@ export class StrandInstanceManager {
1755
2095
  // count — a strand whose member rows became unreadable — this merge must gain an explicit
1756
2096
  // clear rather than silently declaring a stale number over a serving set it can no longer
1757
2097
  // see. Same applies to `bootstrapNodes` above, where a stale seed is harmless.
1758
- servingMachines: overrides?.servingMachines ?? launchConfig.servingMachines
2098
+ servingMachines: overrides?.servingMachines ?? launchConfig.servingMachines,
2099
+ partyMemberPrivateKey: overrides?.partyMemberPrivateKey ?? launchConfig.partyMemberPrivateKey
1759
2100
  };
1760
2101
  this.launchConfigs.set(strandId, resumeConfig);
1761
2102
 
1762
2103
  instance.status = 'starting';
1763
2104
  try {
1764
- await this.trackRuntimeBuild(strandId, this.buildStrandRuntime(instance, resumeConfig));
2105
+ await this.trackRuntimeBuild(strandId, this.buildRuntimeOrReplica(instance, resumeConfig));
1765
2106
  timing('[resumeStrand:%s] total: %dms', strandId, Math.round(performance.now() - tTotal));
1766
2107
  log('Strand %s resumed successfully', strandId);
1767
2108
  return instance;
@@ -1773,6 +2114,66 @@ export class StrandInstanceManager {
1773
2114
  }
1774
2115
  }
1775
2116
 
2117
+ /**
2118
+ * {@link buildStrandRuntime}, run once more as the replica when it fails on the schema of a
2119
+ * claim that has not applied yet ({@link revertRefusedAttach}). Safe to run twice: a failed
2120
+ * build releases both handles before it rejects.
2121
+ */
2122
+ private async buildRuntimeOrReplica(instance: StrandInstance, config: StartStrandConfig): Promise<void> {
2123
+ try {
2124
+ await this.buildStrandRuntime(instance, config);
2125
+ } catch (error) {
2126
+ const replicaConfig = this.revertRefusedAttach(instance, config.sAppConfig, error);
2127
+ if (!replicaConfig) {
2128
+ throw error;
2129
+ }
2130
+ await this.buildStrandRuntime(instance, replicaConfig);
2131
+ }
2132
+ }
2133
+
2134
+ /**
2135
+ * Undo a claim of a storage replica ({@link attachSApp}) after an apply of its schema was refused
2136
+ * (`AppSchemaRefusedError`): the retained launch config drops the sApp, so later rebuilds run the
2137
+ * replica, and the instance gets back the replica's unset `sAppInfo` and its latency hint. Only
2138
+ * when `error` is such a refusal, `refused` is the claim the strand has not applied yet, and the
2139
+ * retained config still carries it, so a config rewritten since is left alone.
2140
+ *
2141
+ * @returns the replica's launch config, or `undefined` when nothing was undone.
2142
+ */
2143
+ private revertRefusedAttach(
2144
+ instance: StrandInstance,
2145
+ refused: SAppConfig | undefined,
2146
+ error: unknown
2147
+ ): StartStrandConfig | undefined {
2148
+ const strandId = instance.strandId;
2149
+ const unapplied = this.unappliedAttaches.get(strandId);
2150
+ const config = this.launchConfigs.get(strandId);
2151
+ const refusal = appSchemaRefusalOf(error);
2152
+ if (!refusal || !unapplied || !config || this.stopping || this.instances.get(strandId) !== instance
2153
+ || refused !== unapplied.sAppConfig || config.sAppConfig !== refused) {
2154
+ return undefined;
2155
+ }
2156
+ this.unappliedAttaches.delete(strandId);
2157
+ const { sAppConfig: _refused, ...replicaConfig } = config;
2158
+ this.launchConfigs.set(strandId, replicaConfig);
2159
+ instance.sAppInfo = undefined;
2160
+ instance.latencyHint = unapplied.latencyHint;
2161
+ log('Strand %s: the schema of sApp %s, which claimed this storage replica, was refused here; ' +
2162
+ 'the strand runs as a replica again: %s', strandId, refused.id, refusal.message);
2163
+ return replicaConfig;
2164
+ }
2165
+
2166
+ /**
2167
+ * Forget the unapplied claim of `strandId` once `database`, given the claim's sApp config as
2168
+ * `applied`, has applied its schema. An apply still deferred keeps it, since its retry can still be
2169
+ * refused by the strand's rows.
2170
+ */
2171
+ private forgetAppliedAttach(strandId: string, applied: SAppConfig | undefined, database: StrandDatabase): void {
2172
+ if (applied && this.unappliedAttaches.get(strandId)?.sAppConfig === applied && database.appSchemaState() === 'applied') {
2173
+ this.unappliedAttaches.delete(strandId);
2174
+ }
2175
+ }
2176
+
1776
2177
  /**
1777
2178
  * Honor a founder request against an ALREADY-TRACKED strand — the seam that
1778
2179
  * closes the "whoever launches first decides whether the bootstrap runs" gap:
@@ -1845,19 +2246,24 @@ export class StrandInstanceManager {
1845
2246
  *
1846
2247
  * A runtime build in flight (the replica's launch, or a hibernation wake) is waited out
1847
2248
  * first, so the attach acts on the database that build produced. Then, in order: the
1848
- * schema signature is checked before anything changes; the retained launch config takes
1849
- * the sApp, so every later rebuild applies it through `composeStrand`; the live database —
1850
- * published, or still held by the first-sync gate — gets the schema; and only then does
1851
- * the instance record `sAppInfo` and the sApp's latency hint. An instance with no live
1852
- * database gets the config alone: a quiesced one applies the schema at its next resume, a
1853
- * launch waiting for a seed peer at its next database retry.
2249
+ * schema signature, and the refusals the schema's text alone decides (`checkAppSchema`: a
2250
+ * `seed` item, an item the parser skipped, a syntax error), are checked before anything
2251
+ * changes; the retained launch config takes the sApp, so every later rebuild applies it
2252
+ * through `composeStrand`; the live database — published, or still held by the first-sync
2253
+ * gate — gets the schema; and only then does the instance record `sAppInfo` and the sApp's
2254
+ * latency hint. An instance with no live database gets the config alone: a quiesced one
2255
+ * applies the schema at its next resume, a launch waiting for a seed peer at its next
2256
+ * database retry, and that build falls back to the replica if the strand's tables and rows
2257
+ * refuse the schema ({@link revertRefusedAttach}).
1854
2258
  *
1855
2259
  * @returns `'already-attached'` when the instance already runs an sApp — a DIFFERENT one
1856
2260
  * is logged and left as it is, as a second claim of a claimed strand always has been —
1857
2261
  * else `'attached'`.
1858
2262
  * @throws when the strand is not tracked (a caller bug, or a launch that failed while
1859
- * this waited on it); when the schema signature is refused, having changed nothing; and
1860
- * whatever the live apply throws (e.g. a quiesce closed the database mid-apply) — the
2263
+ * this waited on it); when the schema signature or the schema's text is refused, having
2264
+ * changed nothing; `AppSchemaRefusedError` when the live apply refuses the schema against
2265
+ * the replica's tables and rows, having put the retained config back to the replica's; and
2266
+ * whatever else the live apply throws (e.g. a quiesce closed the database mid-apply) — the
1861
2267
  * retained config then still carries the sApp and `sAppInfo` stays unset, so the next
1862
2268
  * claim retries the apply.
1863
2269
  *
@@ -1872,26 +2278,34 @@ export class StrandInstanceManager {
1872
2278
  options: { requireSignedSchemas?: boolean } = {}
1873
2279
  ): Promise<'attached' | 'already-attached'> {
1874
2280
  await this.settleRuntimeBuilds(strandId);
1875
- const instance = this.instances.get(strandId);
1876
- const config = this.launchConfigs.get(strandId);
1877
- if (!instance || !config) {
1878
- throw new Error(`Cannot attach an sApp to strand ${strandId}: not tracked`);
1879
- }
1880
- if (instance.sAppInfo) {
1881
- if (instance.sAppInfo.id !== sAppConfig.id) {
1882
- log('attachSApp: strand %s already runs sApp %s — the claim for sApp %s is ignored',
1883
- strandId, instance.sAppInfo.id, sAppConfig.id);
1884
- }
2281
+ if (this.claimTarget(strandId, sAppConfig) === 'already-attached') {
1885
2282
  return 'already-attached';
1886
2283
  }
1887
2284
  const sAppInfo = verifiedSAppInfo(strandId, sAppConfig, options.requireSignedSchemas);
2285
+ await checkAppSchema(sAppConfig.schema);
2286
+ // The check yielded, so a wake or another claim may have started meanwhile: wait out its build
2287
+ // and read the instance and config again, or the config written below would drop what a
2288
+ // resume just retained (its fresh `bootstrapNodes`).
2289
+ await this.settleRuntimeBuilds(strandId);
2290
+ const target = this.claimTarget(strandId, sAppConfig);
2291
+ if (target === 'already-attached') {
2292
+ return target;
2293
+ }
2294
+ const { instance, config } = target;
1888
2295
  // A fresh object rather than mutating in place: startStrand retains the CALLER'S
1889
2296
  // config object, which is not ours to rewrite.
1890
2297
  this.launchConfigs.set(strandId, { ...config, sAppConfig });
2298
+ this.unappliedAttaches.set(strandId, { sAppConfig, latencyHint: instance.latencyHint });
1891
2299
  const database = instance.database ?? this.firstSyncGates.get(strandId)?.database;
1892
2300
  if (database) {
1893
- await database.attachAppSchema(sAppConfig);
2301
+ await this.applyClaimedSchema(instance, database, sAppConfig);
1894
2302
  } else {
2303
+ // NOTE: accepted gap — this claim resolves `'attached'` before any apply, so the app learns of
2304
+ // a refusal by the strand's rows only from the log and from `sAppInfo` going back to unset when
2305
+ // the build falls back to the replica; `CadreNode.sAppConfigs` keeps the claim, so a restart's
2306
+ // launch with it is refused and suppressed (`suppressIfAppSchemaRefused`). Failing the claim
2307
+ // instead would mean waking a quiesced replica to apply now, and would still not cover a
2308
+ // launch waiting for a seed peer.
1895
2309
  log('attachSApp: strand %s has no live database — its next build applies the sApp schema', strandId);
1896
2310
  }
1897
2311
  instance.sAppInfo = sAppInfo;
@@ -1905,6 +2319,48 @@ export class StrandInstanceManager {
1905
2319
  return 'attached';
1906
2320
  }
1907
2321
 
2322
+ /**
2323
+ * The tracked instance and retained config an {@link attachSApp} claim acts on, or
2324
+ * `'already-attached'` when the instance already runs an sApp (a claim for a different one is
2325
+ * logged and ignored).
2326
+ *
2327
+ * @throws when the strand is not tracked.
2328
+ */
2329
+ private claimTarget(
2330
+ strandId: string,
2331
+ sAppConfig: SAppConfig
2332
+ ): { instance: StrandInstance; config: StartStrandConfig } | 'already-attached' {
2333
+ const instance = this.instances.get(strandId);
2334
+ const config = this.launchConfigs.get(strandId);
2335
+ if (!instance || !config) {
2336
+ throw new Error(`Cannot attach an sApp to strand ${strandId}: not tracked`);
2337
+ }
2338
+ if (!instance.sAppInfo) {
2339
+ return { instance, config };
2340
+ }
2341
+ if (instance.sAppInfo.id !== sAppConfig.id) {
2342
+ log('attachSApp: strand %s already runs sApp %s — the claim for sApp %s is ignored',
2343
+ strandId, instance.sAppInfo.id, sAppConfig.id);
2344
+ }
2345
+ return 'already-attached';
2346
+ }
2347
+
2348
+ /**
2349
+ * Apply a claim's schema to the replica's live database. A refusal by the replica's tables and
2350
+ * rows puts the retained config back to the replica's ({@link revertRefusedAttach}): the replica
2351
+ * holds no `App` schema, so the refused apply left nothing to drop. Any other failure leaves the
2352
+ * claim retained and unapplied, for the next claim or build to retry.
2353
+ */
2354
+ private async applyClaimedSchema(instance: StrandInstance, database: StrandDatabase, sAppConfig: SAppConfig): Promise<void> {
2355
+ try {
2356
+ await database.attachAppSchema(sAppConfig);
2357
+ } catch (error) {
2358
+ this.revertRefusedAttach(instance, sAppConfig, error);
2359
+ throw error;
2360
+ }
2361
+ this.forgetAppliedAttach(instance.strandId, sAppConfig, database);
2362
+ }
2363
+
1908
2364
  /**
1909
2365
  * Whether `strandId` is launched but still waiting for its first sync — a joiner whose
1910
2366
  * runtime is up while its database is withheld (status `'syncing'`, or `'idle'` after
@@ -2179,6 +2635,8 @@ export class StrandInstanceManager {
2179
2635
 
2180
2636
  log('Stopping strand instance: %s', strandId);
2181
2637
  instance.status = 'stopping';
2638
+ // Before the release awaits, so a build failing meanwhile does not rebuild as the replica.
2639
+ this.unappliedAttaches.delete(strandId);
2182
2640
  this.rejectWritableWaiters(strandId, 'was stopped');
2183
2641
 
2184
2642
  try {
@@ -2186,6 +2644,7 @@ export class StrandInstanceManager {
2186
2644
  instance.status = 'stopped';
2187
2645
  this.instances.delete(strandId);
2188
2646
  this.launchConfigs.delete(strandId);
2647
+ this.seedRemovalsAnnounced.delete(strandId);
2189
2648
  this.closedQueues.delete(strandId);
2190
2649
  // Storage is released only here — NOT in releaseRuntime, which a quiesce shares.
2191
2650
  await this.disposeStrandStorage(strandId);