@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,12 +1,13 @@
1
1
  import debug from 'debug';
2
2
  import { createLibp2pNode } from '@optimystic/db-p2p';
3
- import { wrapStorageWithCache, disposeStorageCache } from '@serfab/quereus-plugin-sereus';
3
+ import { wrapStorageWithCache, disposeStorageCache, checkAppSchema, appSchemaRefusalOf } from '@serfab/quereus-plugin-sereus';
4
4
  import { StrandDatabase } from './strand-database.js';
5
5
  import { PeerJoinBackfill } from './peer-join-backfill.js';
6
6
  import { strandNetworkStatePersistence } from './strand-network-state.js';
7
7
  import { StrandRevocationEnforcer, createRevocationConnectionGater, readStrandRevocationRows } from './strand-revocation-enforcer.js';
8
8
  import { StrandMembershipReconciler } from './strand-membership-reconciler.js';
9
9
  import { removeMemberPeer } from './strand-membership-writer.js';
10
+ import { StrandPartyMachines, cohortGateWaitingForMachines, watchRemovedMachinesInSeed } from './strand-party-machines.js';
10
11
  import { strandMemberKeyPair } from './strand-member-key.js';
11
12
  import { assertSchemaSignature } from './schema-verification.js';
12
13
  import { assertStrandScopeKey } from './storage-scope.js';
@@ -211,6 +212,21 @@ export class StrandInstanceManager {
211
212
  * nobody and a resume redials over the new node.
212
213
  */
213
214
  this.peerRedials = new Map();
215
+ /**
216
+ * The party's other machines known to hold each strand (`strand-party-machines.ts`), keyed
217
+ * by strand id, on a node offering offline mode for a launch with a party-machine seam. Same
218
+ * lifecycle as {@link peerRedials}: built in `buildStrandRuntime` before the libp2p node (the
219
+ * node's redial loop, the database's offline gate and its commit record read it), stopped and dropped in
220
+ * `releaseRuntime`, so a resume reads the control database afresh. Refreshed by
221
+ * {@link notifyPartyPeersChanged}.
222
+ */
223
+ this.partyMachines = new Map();
224
+ /**
225
+ * Per strand, the removed machines' peer ids a rebuild was asked for
226
+ * ({@link watchRemovedMachinesInSeed}). Outlives a runtime, which is its point: it is what stops
227
+ * a rebuilt node whose seed still names one from asking again. Dropped with the launch config.
228
+ */
229
+ this.seedRemovalsAnnounced = new Map();
214
230
  /**
215
231
  * The resolved (cache-wrapped) raw storage per strand id — the instance's OWN
216
232
  * store, resolved once in `startStrand` and held until `stopStrand` disposes it.
@@ -255,6 +271,14 @@ export class StrandInstanceManager {
255
271
  * {@link releaseRuntime}, so a stop or a quiesce cancels it.
256
272
  */
257
273
  this.unreachableJoinRetries = new Map();
274
+ /**
275
+ * Per strand id, the sApp claim ({@link attachSApp}) whose schema the retained launch config
276
+ * carries but no apply has landed yet: the claim found no live database, or its live apply failed
277
+ * for a reason that may pass. Lets a build that refuses that schema fall back to the replica
278
+ * ({@link revertRefusedAttach}). Deleted when a database applies the schema, by that fallback,
279
+ * and when {@link stopStrand} begins.
280
+ */
281
+ this.unappliedAttaches = new Map();
258
282
  /**
259
283
  * The offline mode set per strand id ({@link setOfflineMode}); a strand absent here runs in its
260
284
  * launch's `initialMode`. Never cleared: the mode belongs to the strand, not to one database, so
@@ -375,6 +399,7 @@ export class StrandInstanceManager {
375
399
  // reads both, and a config without an instance would strand the config.
376
400
  this.instances.delete(strandId);
377
401
  this.launchConfigs.delete(strandId);
402
+ this.seedRemovalsAnnounced.delete(strandId);
378
403
  // The cleanup above remembered the half-built database's queue; an untracked strand keeps none.
379
404
  this.closedQueues.delete(strandId);
380
405
  // The store this launch resolved goes with it: nothing owns it any more, and a
@@ -495,7 +520,11 @@ export class StrandInstanceManager {
495
520
  // therefore means "no transport right now", which the enforcer
496
521
  // treats as "nothing to tear down".
497
522
  getNetwork: () => instance.libp2pNode,
498
- onSelfRevoked: () => config.onSelfRevoked?.(strandId)
523
+ onSelfRevoked: () => config.onSelfRevoked?.(strandId),
524
+ // The membership reconciler below stops on a self-revocation ("stop rather than
525
+ // fight"); a sibling binding this machine back in is what restarts it. Looked up
526
+ // at call time: the reconciler is built after the enforcer, and dropped with it.
527
+ onSelfRestored: () => this.rearmMembershipReconciler(strandId, 'this machine is no longer revoked')
499
528
  }, config.revocationEnforcement)
500
529
  : undefined;
501
530
  if (revocationEnforcer) {
@@ -516,12 +545,36 @@ export class StrandInstanceManager {
516
545
  if (reactivityOption.cohortTopic) {
517
546
  log('strand %s: change notifications on', strandId);
518
547
  }
548
+ // The party's other machines holding this strand, for the offline queue's gate, each commit's
549
+ // durability record and the redial loop below (`strand-party-machines.ts`). Only a node offering offline mode pays
550
+ // for the control reads, which leaves out the always-on programs. Built BEFORE the libp2p
551
+ // node, and its first read started now, so a queue restored at launch waits on rows that
552
+ // were asked for before the node existed. Registered in the map at once, so the failure
553
+ // rollback (releaseRuntime) stops it like every other runtime component.
554
+ const partyMachines = config.offline && config.partyPeers
555
+ ? new StrandPartyMachines({ label: strandId, source: config.partyPeers })
556
+ : undefined;
557
+ if (partyMachines) {
558
+ this.partyMachines.set(strandId, partyMachines);
559
+ this.watchSeedForRemovedMachines(strandId, config, partyMachines);
560
+ partyMachines.refresh();
561
+ }
519
562
  try {
520
563
  let t0 = performance.now();
521
564
  const node = await createLibp2pNode({
522
565
  port: 0, // Random port
523
566
  bootstrapNodes: config.bootstrapNodes ?? [],
524
567
  networkName,
568
+ // A machine removed from the party stops counting as a member, ahead of whatever this node
569
+ // remembers of it, so a queue stops waiting for it. Read live, and everyone else takes the
570
+ // path they would with no predicate.
571
+ //
572
+ // NOTE: a machine can state any id in its own `StrandPeer` row before its removal, and that
573
+ // id is then refused here, leaving that peer out of this node's cohorts. One id per
574
+ // (strand, machine), in a row a machine the party trusted then signed, and an id a live
575
+ // sibling recorded is never read as removed. If a peer is ever seen left out of cohorts
576
+ // this way, the row needs a proof that the id it states is the machine's own.
577
+ ...(partyMachines && { isNetworkMember: (peerId) => !partyMachines.removed().has(peerId) }),
525
578
  storage: strandStorage,
526
579
  fretProfile: config.profile === 'storage' ? 'core' : 'edge',
527
580
  relay: relayServer.enabled,
@@ -616,6 +669,16 @@ export class StrandInstanceManager {
616
669
  });
617
670
  timing('[buildStrandRuntime:%s] createLibp2pNode: %dms', strandId, Math.round(performance.now() - t0));
618
671
  instance.libp2pNode = node;
672
+ // This machine's statement of its peer id in the strand, for the party's control
673
+ // database (`StrandPeer`): a background write that never fails or delays the launch.
674
+ // The seam defers it while a write could fork the party and retries it on cohort
675
+ // growth and from every membership reconciler pass, so a refusal here is not final.
676
+ // Written for open strands too: their row is what a sibling's offline queue waits for.
677
+ if (config.partyPeers) {
678
+ void config.partyPeers.publishOwn(node.peerId.toString()).catch((error) => {
679
+ log('Strand %s: publishing this machine\'s StrandPeer row threw (retried later): %o', strandId, error);
680
+ });
681
+ }
619
682
  // One reservation supervisor PER RELAY, started now so the first attempts
620
683
  // overlap the database bring-up below (the relay is never in a strand's
621
684
  // Optimystic cohort — its protocol ids are namespaced `/optimystic/strand-<id>/…`
@@ -628,12 +691,20 @@ export class StrandInstanceManager {
628
691
  // declared link gives a relayed dial — what reconnects two restarted phones on a slow
629
692
  // link, where FRET's own redial cannot (`strand-peer-redial.ts`). The relays are
630
693
  // excluded by peer id: the node is connected to them throughout, and they are no member.
694
+ // The party's machines holding the strand are dialed too, at the addresses the
695
+ // strand-addr RPC put in the address book, so a sibling's blocked port that opens is
696
+ // reached without a connection ever having been made to it.
697
+ // A machine removed from the party is revoked to this loop on an open strand too: neither a
698
+ // peer to dial nor a connection that stands in for reaching the party's other machines.
631
699
  this.peerRedials.set(strandId, superviseStrandPeerRedial({
632
700
  label: strandId,
633
701
  node,
634
702
  seed: config.bootstrapNodes ?? [],
635
703
  excluded: new Set(groupAddrsByPeerId([...relayDialAddrs]).keys()),
636
- ...(revocationEnforcer && { isRevoked: (peerId) => revocationEnforcer.isRevoked(peerId) })
704
+ ...((revocationEnforcer || partyMachines) && {
705
+ isRevoked: (peerId) => revocationEnforcer?.isRevoked(peerId) === true || partyMachines?.removed().has(peerId) === true
706
+ }),
707
+ ...(partyMachines && { partyMachines: () => partyMachines.machines().map((machine) => machine.strandPeerId) })
637
708
  }, strandRedialTimings(config.network?.linkRoundTripMs)));
638
709
  const databaseBuild = await this.buildStrandDatabase(instance, config, node);
639
710
  if (!this.isCurrentRuntime(instance, node)) {
@@ -657,30 +728,7 @@ export class StrandInstanceManager {
657
728
  // (`bindFounderPeer`), so the first pass finds them and stops. Armed AFTER the database
658
729
  // phase above, so a gated or deferred launch always has a reconciler registered by the
659
730
  // time it can publish.
660
- if (config.strandRow.Type === 'c' && config.partyMemberPrivateKey
661
- && config.membershipReconciliation?.enabled !== false) {
662
- const reconciler = new StrandMembershipReconciler({
663
- label: strandId,
664
- partyMemberPrivateKey: config.partyMemberPrivateKey,
665
- // Read per pass, never captured — same lifecycle argument as the
666
- // enforcer's getNetwork: quiesce drops both handles.
667
- getDatabase: () => instance.database?.getDatabase(),
668
- getOwnPeerId: () => instance.libp2pNode?.peerId.toString(),
669
- pendingInvite: config.pendingMembershipInvite,
670
- // The enforcer's CURRENT snapshot view of this node's own peer id — the
671
- // reconciler stops rather than fight a self-revocation. Absent when the
672
- // gate is disarmed (fail-open: the loop just runs).
673
- isSelfRevoked: revocationEnforcer
674
- ? () => {
675
- const ownPeerId = instance.libp2pNode?.peerId.toString();
676
- return ownPeerId !== undefined && revocationEnforcer.isRevoked(ownPeerId);
677
- }
678
- : undefined,
679
- onRejoinBlocked: () => config.onRejoinBlocked?.(strandId)
680
- }, config.membershipReconciliation);
681
- this.membershipReconcilers.set(strandId, reconciler);
682
- reconciler.start();
683
- }
731
+ this.armMembershipReconciler(instance, config, revocationEnforcer);
684
732
  // Peer-join block catch-up: push this strand's own blocks to each newly
685
733
  // connected peer, so a machine that joined after blocks were committed
686
734
  // still ends up physically holding them (without per-strand storage there
@@ -782,6 +830,7 @@ export class StrandInstanceManager {
782
830
  // a partially-initialized db), and the app only ever sees `instance.database` once this
783
831
  // machine is allowed to write to the strand.
784
832
  let t0 = performance.now();
833
+ const partyMachines = this.partyMachines.get(strandId);
785
834
  const strandDb = new StrandDatabase({
786
835
  strandId,
787
836
  sAppConfig: config.sAppConfig,
@@ -801,8 +850,9 @@ export class StrandInstanceManager {
801
850
  bindFounderPeer: config.membershipReconciliation?.enabled !== false,
802
851
  onCommitDurability: config.onCommitDurability,
803
852
  onCommitHeld: config.onCommitHeld,
804
- offline: this.offlineDatabaseConfig(strandId, config.offline),
805
- appSchema: config.appSchema
853
+ offline: this.offlineDatabaseConfig(strandId, config.offline, this.offlineCohortGate(strandId, node)),
854
+ appSchema: config.appSchema,
855
+ ...(partyMachines && { partyMachines: () => partyMachines.machines() })
806
856
  });
807
857
  const storageRepo = node.storageRepo;
808
858
  const gate = new StrandFirstSyncGate({
@@ -840,6 +890,7 @@ export class StrandInstanceManager {
840
890
  await strandDb.close();
841
891
  return 'released';
842
892
  }
893
+ this.forgetAppliedAttach(strandId, config.sAppConfig, strandDb);
843
894
  // The first-sync write gate. A founder just wrote the Header in its bootstrap; any
844
895
  // other machine may commit only once it holds the Header — which it can only have
845
896
  // received from a peer (now, or on an earlier run over the same store) — and has read
@@ -877,10 +928,10 @@ export class StrandInstanceManager {
877
928
  }
878
929
  /**
879
930
  * One build's {@link StrandDatabaseOffline}: the strand's journal, which the database resolves as
880
- * it initializes (a throw or rejection fails the build), and the strand's mode, which it reads each
881
- * time it applies it.
931
+ * it initializes (a throw or rejection fails the build), the strand's mode, which it reads each
932
+ * time it applies it, and the gate its queue asks, when one could be built.
882
933
  */
883
- offlineDatabaseConfig(strandId, offline) {
934
+ offlineDatabaseConfig(strandId, offline, cohortReachability) {
884
935
  if (!offline) {
885
936
  return undefined;
886
937
  }
@@ -888,9 +939,59 @@ export class StrandInstanceManager {
888
939
  return {
889
940
  ...listeners,
890
941
  journal: () => journal(strandId),
891
- mode: () => this.currentOfflineMode(strandId, offline)
942
+ mode: () => this.currentOfflineMode(strandId, offline),
943
+ ...(cohortReachability && { cohortReachability })
892
944
  };
893
945
  }
946
+ /**
947
+ * The gate a build's offline queue asks: the node's own, closed also while the party has
948
+ * machines holding the strand that this node is alone in a cohort without
949
+ * (`cohortGateWaitingForMachines`). None when the launch tracks no party machines (no offline
950
+ * mode, or no party-machine seam), or when the node carries no gate or key network to compose
951
+ * over; the queue then asks the node's own gate, as before.
952
+ */
953
+ offlineCohortGate(strandId, node) {
954
+ const partyMachines = this.partyMachines.get(strandId);
955
+ if (!partyMachines) {
956
+ return undefined;
957
+ }
958
+ if (!node.cohortReachability || !node.keyNetwork) {
959
+ log('Strand %s: its node carries no %s, so its offline queue does not wait for the party\'s machines', strandId, node.cohortReachability ? 'key network' : 'reachability gate');
960
+ return undefined;
961
+ }
962
+ return cohortGateWaitingForMachines(node.cohortReachability, node.keyNetwork, node.peerId.toString(), partyMachines);
963
+ }
964
+ /** Ask the launcher for a rebuild when a machine removed from the party is in this runtime's seed. */
965
+ watchSeedForRemovedMachines(strandId, config, machines) {
966
+ const { onRemovedMachineInSeed } = config;
967
+ if (!onRemovedMachineInSeed) {
968
+ return;
969
+ }
970
+ let announced = this.seedRemovalsAnnounced.get(strandId);
971
+ if (!announced) {
972
+ announced = new Set();
973
+ this.seedRemovalsAnnounced.set(strandId, announced);
974
+ }
975
+ const seedPeers = new Set(groupAddrsByPeerId(config.bootstrapNodes ?? []).keys());
976
+ watchRemovedMachinesInSeed(machines, seedPeers, announced, () => onRemovedMachineInSeed(strandId), strandId);
977
+ }
978
+ /**
979
+ * The party's other machines known to hold `strandId` with no open connection from its strand
980
+ * node: what an offline queue reporting `waitingFor: 'cohort'` may be waiting for
981
+ * (`docs/strands.md` → "Waiting for the party's own machines"). Empty for a strand not tracked
982
+ * or not running here, and on a launch that tracks no party machines.
983
+ */
984
+ unreachedPartyMachines(strandId) {
985
+ const partyMachines = this.partyMachines.get(strandId);
986
+ const node = this.instances.get(strandId)?.libp2pNode;
987
+ if (!partyMachines || !node) {
988
+ return [];
989
+ }
990
+ const connected = new Set(node.getConnections()
991
+ .filter((connection) => connection.status === 'open')
992
+ .map((connection) => connection.remotePeer.toString()));
993
+ return partyMachines.machines().filter((machine) => !connected.has(machine.strandPeerId));
994
+ }
894
995
  /**
895
996
  * Whether this strand's raw store holds no block. False for a store that cannot list its
896
997
  * blocks, or whose listing fails, so such a launch probes at once.
@@ -952,7 +1053,8 @@ export class StrandInstanceManager {
952
1053
  * runtime still attached. Skipped when the strand was stopped or released since — a quiesce
953
1054
  * releases it and the resume after rebuilds the whole runtime — or already has a database.
954
1055
  * A failure other than an unanswered seed releases the runtime and marks the strand
955
- * `'error'`, as a failed resume does.
1056
+ * `'error'`, as a failed resume does, unless it is a refusal of a claim's schema the replica
1057
+ * can fall back from ({@link buildJoinDatabaseOrReplica}).
956
1058
  */
957
1059
  async retryUnreachableJoin(instance) {
958
1060
  const strandId = instance.strandId;
@@ -967,7 +1069,7 @@ export class StrandInstanceManager {
967
1069
  try {
968
1070
  // Tracked like any runtime build, so a wake, a quiesce or an sApp attach waits for it
969
1071
  // rather than acting on a database that is still initializing.
970
- build = await this.trackRuntimeBuild(strandId, this.buildStrandDatabase(instance, config, node));
1072
+ build = await this.trackRuntimeBuild(strandId, this.buildJoinDatabaseOrReplica(instance, config, node));
971
1073
  }
972
1074
  catch (error) {
973
1075
  if (!this.isCurrentRuntime(instance, node)) {
@@ -986,6 +1088,35 @@ export class StrandInstanceManager {
986
1088
  this.deferUnreachableJoin(instance);
987
1089
  }
988
1090
  }
1091
+ /**
1092
+ * A deferred join's database phase ({@link buildStrandDatabase}), run once more as the replica
1093
+ * when it fails on the schema of a claim that has not applied yet ({@link revertRefusedAttach}).
1094
+ * The failed attempt's database is closed first: a failure leaves it registered with its gate.
1095
+ * `'released'` when a stop began while it closed.
1096
+ */
1097
+ async buildJoinDatabaseOrReplica(instance, config, node) {
1098
+ try {
1099
+ return await this.buildStrandDatabase(instance, config, node);
1100
+ }
1101
+ catch (error) {
1102
+ const replicaConfig = this.isCurrentRuntime(instance, node)
1103
+ ? this.revertRefusedAttach(instance, config.sAppConfig, error)
1104
+ : undefined;
1105
+ if (!replicaConfig) {
1106
+ throw error;
1107
+ }
1108
+ const failedAttempt = this.firstSyncGates.get(instance.strandId);
1109
+ if (failedAttempt) {
1110
+ await this.discardDatabaseAttempt(instance.strandId, failedAttempt);
1111
+ }
1112
+ if (!this.isCurrentRuntime(instance, node) || instance.status === 'stopping') {
1113
+ // A stop that began while the failed attempt closed found no gate to release, so a
1114
+ // database built now would outlive the stop, open and unreleased.
1115
+ return 'released';
1116
+ }
1117
+ return await this.buildStrandDatabase(instance, replicaConfig, node);
1118
+ }
1119
+ }
989
1120
  /** Whether `instance` is still tracked, with `node` still its runtime's libp2p node. */
990
1121
  isCurrentRuntime(instance, node) {
991
1122
  return !this.stopping && this.instances.get(instance.strandId) === instance && instance.libp2pNode === node;
@@ -1020,6 +1151,9 @@ export class StrandInstanceManager {
1020
1151
  }
1021
1152
  this.peerRedials.get(instance.strandId)?.stop();
1022
1153
  this.peerRedials.delete(instance.strandId);
1154
+ // The party-machine tracker with the loop and gate that read it; a resume reads afresh.
1155
+ this.partyMachines.get(instance.strandId)?.stop();
1156
+ this.partyMachines.delete(instance.strandId);
1023
1157
  // Backfill next — before the database closes and the libp2p node stops — so
1024
1158
  // no NEW catch-up push is issued against a torn-down transport. A push already
1025
1159
  // in flight is not awaited; it fails into the module's own per-chunk catch.
@@ -1167,12 +1301,136 @@ export class StrandInstanceManager {
1167
1301
  * loop's own serialized chain and never rejects.
1168
1302
  */
1169
1303
  notifyMembershipInviteStaged(strandId) {
1304
+ if (!this.rearmMembershipReconciler(strandId, 'a fresh invitation')) {
1305
+ log('notifyMembershipInviteStaged: strand %s has no armed membership reconciler — bring-up will find the invitation', strandId);
1306
+ }
1307
+ }
1308
+ /**
1309
+ * The party's machines changed in the control database — a `StrandPeer` row, a `CadrePeer`
1310
+ * row or a tombstone arrived or was written here (`CadreNode`'s watch on those tables,
1311
+ * coalesced). Re-arm every armed membership reconciler, so a sibling's row is bound, or a
1312
+ * removed machine's binding cleared, within the watch's window rather than at the next
1313
+ * resume, and read every strand's party machines again, so an offline queue waits for a
1314
+ * machine as soon as its row arrives and stops waiting for one as soon as it is removed.
1315
+ * Table events carry no row keys, so every strand's loop and tracker is woken; a loop with
1316
+ * nothing to do confirms and stops again. Returns at once; each pass runs on its loop's own
1317
+ * serialized chain and never rejects.
1318
+ */
1319
+ notifyPartyPeersChanged() {
1320
+ for (const strandId of this.membershipReconcilers.keys()) {
1321
+ this.rearmMembershipReconciler(strandId, 'a change to the party\'s machines');
1322
+ }
1323
+ for (const partyMachines of this.partyMachines.values()) {
1324
+ partyMachines.refresh();
1325
+ }
1326
+ }
1327
+ /** Re-arm `strandId`'s membership reconciler for `cause`; `false` when none is armed. */
1328
+ rearmMembershipReconciler(strandId, cause) {
1170
1329
  const reconciler = this.membershipReconcilers.get(strandId);
1171
1330
  if (!reconciler) {
1172
- log('notifyMembershipInviteStaged: strand %s has no armed membership reconciler — bring-up will find the invitation', strandId);
1331
+ return false;
1332
+ }
1333
+ void reconciler.rearm(cause);
1334
+ return true;
1335
+ }
1336
+ /**
1337
+ * Build and start `instance`'s membership reconciler from `config`, for a closed strand that
1338
+ * carries the party's own membership key with the loop enabled; nothing otherwise. Called by
1339
+ * {@link buildStrandRuntime} after the database phase, and by {@link rekeyParty} over a
1340
+ * running instance with the re-keyed config. Every dependency is read per pass, never
1341
+ * captured, so the loop follows the instance through quiesce and resume.
1342
+ */
1343
+ armMembershipReconciler(instance, config, revocationEnforcer) {
1344
+ if (config.strandRow.Type !== 'c' || !config.partyMemberPrivateKey || config.membershipReconciliation?.enabled === false) {
1173
1345
  return;
1174
1346
  }
1175
- void reconciler.rearm();
1347
+ const strandId = instance.strandId;
1348
+ const reconciler = new StrandMembershipReconciler({
1349
+ label: strandId,
1350
+ partyMemberPrivateKey: config.partyMemberPrivateKey,
1351
+ // Read per pass, never captured — same lifecycle argument as the
1352
+ // enforcer's getNetwork: quiesce drops both handles.
1353
+ getDatabase: () => instance.database?.getDatabase(),
1354
+ getOwnPeerId: () => instance.libp2pNode?.peerId.toString(),
1355
+ pendingInvite: config.pendingMembershipInvite,
1356
+ partyPeers: config.partyPeers,
1357
+ // The enforcer's CURRENT snapshot view of this node's own peer id — the
1358
+ // reconciler stops rather than fight a self-revocation. Absent when the
1359
+ // gate is disarmed (fail-open: the loop just runs).
1360
+ isSelfRevoked: revocationEnforcer
1361
+ ? () => {
1362
+ const ownPeerId = instance.libp2pNode?.peerId.toString();
1363
+ return ownPeerId !== undefined && revocationEnforcer.isRevoked(ownPeerId);
1364
+ }
1365
+ : undefined,
1366
+ onRejoinBlocked: () => config.onRejoinBlocked?.(strandId),
1367
+ onPendingKeySeated: () => config.onPartyKeySeated?.(strandId)
1368
+ }, config.membershipReconciliation);
1369
+ this.membershipReconcilers.set(strandId, reconciler);
1370
+ reconciler.start();
1371
+ }
1372
+ /**
1373
+ * Move a tracked closed strand onto `partyMemberPrivateKey`, the party's membership key the
1374
+ * control record now names (a party key rotation finished here or replicated from the machine
1375
+ * that finished it: `strand-party-key-rotation.ts`). The retained launch config is replaced
1376
+ * with a fresh object carrying the key ({@link foundExistingStrand}'s idiom: the caller's
1377
+ * config object is not ours to rewrite), so every later resume rebuilds under it, and the
1378
+ * founder bootstrap a resume re-runs derives from it (insert-if-absent; the strand's rows
1379
+ * already hold the new key as member and manager, so it writes nothing). The running
1380
+ * instance's membership reconciler, which signs with the key, is stopped and awaited, then
1381
+ * rebuilt and started over the re-keyed config, so its next pass binds under the new key.
1382
+ *
1383
+ * A tracked instance with no party key before (a storage replica launched before the party's
1384
+ * row reached this node) is keyed the same way and gains its reconciler now rather than at its
1385
+ * next resume. A build in flight is waited out first, so the reconciler it arms is the one
1386
+ * replaced here rather than a second one beside it; a key the retained config already names
1387
+ * is answered before that wait, since the party key watch asks this for every tracked closed
1388
+ * strand on every change to the key tables.
1389
+ *
1390
+ * @returns `rekeyed` when a running instance's reconciler was rebuilt; `retained` when only the
1391
+ * config changed (a hibernating instance, or one with the loop disabled); `unchanged` when
1392
+ * the key already matched or the strand is open; `untracked` when the strand is not here.
1393
+ */
1394
+ async rekeyParty(strandId, partyMemberPrivateKey) {
1395
+ const before = this.rekeyNeeded(strandId, partyMemberPrivateKey);
1396
+ if (before !== 'needed') {
1397
+ return before;
1398
+ }
1399
+ await this.settleRuntimeBuilds(strandId);
1400
+ const after = this.rekeyNeeded(strandId, partyMemberPrivateKey);
1401
+ if (after !== 'needed') {
1402
+ return after;
1403
+ }
1404
+ const instance = this.instances.get(strandId);
1405
+ const config = this.launchConfigs.get(strandId);
1406
+ const rekeyed = { ...config, partyMemberPrivateKey };
1407
+ this.launchConfigs.set(strandId, rekeyed);
1408
+ const reconciler = this.membershipReconcilers.get(strandId);
1409
+ if (reconciler) {
1410
+ reconciler.stop();
1411
+ await reconciler.settle();
1412
+ this.membershipReconcilers.delete(strandId);
1413
+ }
1414
+ if (!instance.libp2pNode || this.isQuiescing(strandId)) {
1415
+ log('rekeyParty: strand %s has no live runtime; the re-keyed config waits for its resume', strandId);
1416
+ return 'retained';
1417
+ }
1418
+ this.armMembershipReconciler(instance, rekeyed, this.revocationEnforcers.get(strandId));
1419
+ const armed = this.membershipReconcilers.has(strandId);
1420
+ log('rekeyParty: strand %s re-keyed (%s)', strandId, armed ? 'membership reconciler rebuilt' : 'membership reconciliation disabled');
1421
+ return armed ? 'rekeyed' : 'retained';
1422
+ }
1423
+ /** Whether {@link rekeyParty} has anything to do for `strandId`: the retained config is a closed strand's and names another key. */
1424
+ rekeyNeeded(strandId, partyMemberPrivateKey) {
1425
+ const config = this.launchConfigs.get(strandId);
1426
+ if (!config || !this.instances.has(strandId)) {
1427
+ return 'untracked';
1428
+ }
1429
+ return config.strandRow.Type !== 'c' || config.partyMemberPrivateKey === partyMemberPrivateKey ? 'unchanged' : 'needed';
1430
+ }
1431
+ /** The ids of every tracked closed strand, running or hibernating. */
1432
+ trackedClosedStrandIds() {
1433
+ return [...this.launchConfigs].filter(([, config]) => config.strandRow.Type === 'c').map(([strandId]) => strandId);
1176
1434
  }
1177
1435
  /**
1178
1436
  * Best-effort removal of THIS machine's own `Strand.MemberPeer` binding — the
@@ -1191,13 +1449,16 @@ export class StrandInstanceManager {
1191
1449
  * and its in-flight pass awaited — FIRST, so a pass that was already past its
1192
1450
  * own stopped check cannot re-register the binding this is about to clear.
1193
1451
  *
1194
- * NOTE: deliberately NOT handled here (or anywhere yet): clearing the bindings
1195
- * of a machine removed from the CADRE at the control layer, or of a party's
1196
- * OTHER machines when the party unpublishes — the party still holds the key on
1197
- * every surviving machine and can clear from any of them, and the stale rows
1198
- * grant nothing while admission is deny-list only. Revisit when
1199
- * `feat-strand-member-allowlist-admission` lands and a stale binding starts
1200
- * granting admission rather than merely mis-crediting diversity.
1452
+ * A machine removed from the CADRE at the control layer is not cleared here either: the
1453
+ * party replaces its key in the strand instead (`strand-party-key-rotation.ts`), which
1454
+ * leaves that machine's binding an orphan the revoked-peer gate denies, and the membership
1455
+ * reconciler clears what a lagging sibling wrote under the new key.
1456
+ *
1457
+ * NOTE: deliberately NOT handled here (or anywhere yet): clearing the bindings of a party's
1458
+ * OTHER machines when the party unpublishes — the party still holds the key on every
1459
+ * surviving machine and can clear from any of them, and the stale rows grant nothing while
1460
+ * admission is deny-list only. Revisit when `feat-strand-member-allowlist-admission` lands
1461
+ * and a stale binding starts granting admission rather than merely mis-crediting diversity.
1201
1462
  */
1202
1463
  async clearOwnMemberPeerBinding(strandId) {
1203
1464
  const instance = this.instances.get(strandId);
@@ -1368,12 +1629,13 @@ export class StrandInstanceManager {
1368
1629
  // count — a strand whose member rows became unreadable — this merge must gain an explicit
1369
1630
  // clear rather than silently declaring a stale number over a serving set it can no longer
1370
1631
  // see. Same applies to `bootstrapNodes` above, where a stale seed is harmless.
1371
- servingMachines: overrides?.servingMachines ?? launchConfig.servingMachines
1632
+ servingMachines: overrides?.servingMachines ?? launchConfig.servingMachines,
1633
+ partyMemberPrivateKey: overrides?.partyMemberPrivateKey ?? launchConfig.partyMemberPrivateKey
1372
1634
  };
1373
1635
  this.launchConfigs.set(strandId, resumeConfig);
1374
1636
  instance.status = 'starting';
1375
1637
  try {
1376
- await this.trackRuntimeBuild(strandId, this.buildStrandRuntime(instance, resumeConfig));
1638
+ await this.trackRuntimeBuild(strandId, this.buildRuntimeOrReplica(instance, resumeConfig));
1377
1639
  timing('[resumeStrand:%s] total: %dms', strandId, Math.round(performance.now() - tTotal));
1378
1640
  log('Strand %s resumed successfully', strandId);
1379
1641
  return instance;
@@ -1385,6 +1647,60 @@ export class StrandInstanceManager {
1385
1647
  throw error;
1386
1648
  }
1387
1649
  }
1650
+ /**
1651
+ * {@link buildStrandRuntime}, run once more as the replica when it fails on the schema of a
1652
+ * claim that has not applied yet ({@link revertRefusedAttach}). Safe to run twice: a failed
1653
+ * build releases both handles before it rejects.
1654
+ */
1655
+ async buildRuntimeOrReplica(instance, config) {
1656
+ try {
1657
+ await this.buildStrandRuntime(instance, config);
1658
+ }
1659
+ catch (error) {
1660
+ const replicaConfig = this.revertRefusedAttach(instance, config.sAppConfig, error);
1661
+ if (!replicaConfig) {
1662
+ throw error;
1663
+ }
1664
+ await this.buildStrandRuntime(instance, replicaConfig);
1665
+ }
1666
+ }
1667
+ /**
1668
+ * Undo a claim of a storage replica ({@link attachSApp}) after an apply of its schema was refused
1669
+ * (`AppSchemaRefusedError`): the retained launch config drops the sApp, so later rebuilds run the
1670
+ * replica, and the instance gets back the replica's unset `sAppInfo` and its latency hint. Only
1671
+ * when `error` is such a refusal, `refused` is the claim the strand has not applied yet, and the
1672
+ * retained config still carries it, so a config rewritten since is left alone.
1673
+ *
1674
+ * @returns the replica's launch config, or `undefined` when nothing was undone.
1675
+ */
1676
+ revertRefusedAttach(instance, refused, error) {
1677
+ const strandId = instance.strandId;
1678
+ const unapplied = this.unappliedAttaches.get(strandId);
1679
+ const config = this.launchConfigs.get(strandId);
1680
+ const refusal = appSchemaRefusalOf(error);
1681
+ if (!refusal || !unapplied || !config || this.stopping || this.instances.get(strandId) !== instance
1682
+ || refused !== unapplied.sAppConfig || config.sAppConfig !== refused) {
1683
+ return undefined;
1684
+ }
1685
+ this.unappliedAttaches.delete(strandId);
1686
+ const { sAppConfig: _refused, ...replicaConfig } = config;
1687
+ this.launchConfigs.set(strandId, replicaConfig);
1688
+ instance.sAppInfo = undefined;
1689
+ instance.latencyHint = unapplied.latencyHint;
1690
+ log('Strand %s: the schema of sApp %s, which claimed this storage replica, was refused here; ' +
1691
+ 'the strand runs as a replica again: %s', strandId, refused.id, refusal.message);
1692
+ return replicaConfig;
1693
+ }
1694
+ /**
1695
+ * Forget the unapplied claim of `strandId` once `database`, given the claim's sApp config as
1696
+ * `applied`, has applied its schema. An apply still deferred keeps it, since its retry can still be
1697
+ * refused by the strand's rows.
1698
+ */
1699
+ forgetAppliedAttach(strandId, applied, database) {
1700
+ if (applied && this.unappliedAttaches.get(strandId)?.sAppConfig === applied && database.appSchemaState() === 'applied') {
1701
+ this.unappliedAttaches.delete(strandId);
1702
+ }
1703
+ }
1388
1704
  /**
1389
1705
  * Honor a founder request against an ALREADY-TRACKED strand — the seam that
1390
1706
  * closes the "whoever launches first decides whether the bootstrap runs" gap:
@@ -1453,19 +1769,24 @@ export class StrandInstanceManager {
1453
1769
  *
1454
1770
  * A runtime build in flight (the replica's launch, or a hibernation wake) is waited out
1455
1771
  * first, so the attach acts on the database that build produced. Then, in order: the
1456
- * schema signature is checked before anything changes; the retained launch config takes
1457
- * the sApp, so every later rebuild applies it through `composeStrand`; the live database —
1458
- * published, or still held by the first-sync gate — gets the schema; and only then does
1459
- * the instance record `sAppInfo` and the sApp's latency hint. An instance with no live
1460
- * database gets the config alone: a quiesced one applies the schema at its next resume, a
1461
- * launch waiting for a seed peer at its next database retry.
1772
+ * schema signature, and the refusals the schema's text alone decides (`checkAppSchema`: a
1773
+ * `seed` item, an item the parser skipped, a syntax error), are checked before anything
1774
+ * changes; the retained launch config takes the sApp, so every later rebuild applies it
1775
+ * through `composeStrand`; the live database — published, or still held by the first-sync
1776
+ * gate — gets the schema; and only then does the instance record `sAppInfo` and the sApp's
1777
+ * latency hint. An instance with no live database gets the config alone: a quiesced one
1778
+ * applies the schema at its next resume, a launch waiting for a seed peer at its next
1779
+ * database retry, and that build falls back to the replica if the strand's tables and rows
1780
+ * refuse the schema ({@link revertRefusedAttach}).
1462
1781
  *
1463
1782
  * @returns `'already-attached'` when the instance already runs an sApp — a DIFFERENT one
1464
1783
  * is logged and left as it is, as a second claim of a claimed strand always has been —
1465
1784
  * else `'attached'`.
1466
1785
  * @throws when the strand is not tracked (a caller bug, or a launch that failed while
1467
- * this waited on it); when the schema signature is refused, having changed nothing; and
1468
- * whatever the live apply throws (e.g. a quiesce closed the database mid-apply) — the
1786
+ * this waited on it); when the schema signature or the schema's text is refused, having
1787
+ * changed nothing; `AppSchemaRefusedError` when the live apply refuses the schema against
1788
+ * the replica's tables and rows, having put the retained config back to the replica's; and
1789
+ * whatever else the live apply throws (e.g. a quiesce closed the database mid-apply) — the
1469
1790
  * retained config then still carries the sApp and `sAppInfo` stays unset, so the next
1470
1791
  * claim retries the apply.
1471
1792
  *
@@ -1476,26 +1797,35 @@ export class StrandInstanceManager {
1476
1797
  */
1477
1798
  async attachSApp(strandId, sAppConfig, options = {}) {
1478
1799
  await this.settleRuntimeBuilds(strandId);
1479
- const instance = this.instances.get(strandId);
1480
- const config = this.launchConfigs.get(strandId);
1481
- if (!instance || !config) {
1482
- throw new Error(`Cannot attach an sApp to strand ${strandId}: not tracked`);
1483
- }
1484
- if (instance.sAppInfo) {
1485
- if (instance.sAppInfo.id !== sAppConfig.id) {
1486
- log('attachSApp: strand %s already runs sApp %s — the claim for sApp %s is ignored', strandId, instance.sAppInfo.id, sAppConfig.id);
1487
- }
1800
+ if (this.claimTarget(strandId, sAppConfig) === 'already-attached') {
1488
1801
  return 'already-attached';
1489
1802
  }
1490
1803
  const sAppInfo = verifiedSAppInfo(strandId, sAppConfig, options.requireSignedSchemas);
1804
+ await checkAppSchema(sAppConfig.schema);
1805
+ // The check yielded, so a wake or another claim may have started meanwhile: wait out its build
1806
+ // and read the instance and config again, or the config written below would drop what a
1807
+ // resume just retained (its fresh `bootstrapNodes`).
1808
+ await this.settleRuntimeBuilds(strandId);
1809
+ const target = this.claimTarget(strandId, sAppConfig);
1810
+ if (target === 'already-attached') {
1811
+ return target;
1812
+ }
1813
+ const { instance, config } = target;
1491
1814
  // A fresh object rather than mutating in place: startStrand retains the CALLER'S
1492
1815
  // config object, which is not ours to rewrite.
1493
1816
  this.launchConfigs.set(strandId, { ...config, sAppConfig });
1817
+ this.unappliedAttaches.set(strandId, { sAppConfig, latencyHint: instance.latencyHint });
1494
1818
  const database = instance.database ?? this.firstSyncGates.get(strandId)?.database;
1495
1819
  if (database) {
1496
- await database.attachAppSchema(sAppConfig);
1820
+ await this.applyClaimedSchema(instance, database, sAppConfig);
1497
1821
  }
1498
1822
  else {
1823
+ // NOTE: accepted gap — this claim resolves `'attached'` before any apply, so the app learns of
1824
+ // a refusal by the strand's rows only from the log and from `sAppInfo` going back to unset when
1825
+ // the build falls back to the replica; `CadreNode.sAppConfigs` keeps the claim, so a restart's
1826
+ // launch with it is refused and suppressed (`suppressIfAppSchemaRefused`). Failing the claim
1827
+ // instead would mean waking a quiesced replica to apply now, and would still not cover a
1828
+ // launch waiting for a seed peer.
1499
1829
  log('attachSApp: strand %s has no live database — its next build applies the sApp schema', strandId);
1500
1830
  }
1501
1831
  instance.sAppInfo = sAppInfo;
@@ -1508,6 +1838,43 @@ export class StrandInstanceManager {
1508
1838
  log('Strand %s upgraded from storage replica to %s', strandId, describeSApp(sAppConfig));
1509
1839
  return 'attached';
1510
1840
  }
1841
+ /**
1842
+ * The tracked instance and retained config an {@link attachSApp} claim acts on, or
1843
+ * `'already-attached'` when the instance already runs an sApp (a claim for a different one is
1844
+ * logged and ignored).
1845
+ *
1846
+ * @throws when the strand is not tracked.
1847
+ */
1848
+ claimTarget(strandId, sAppConfig) {
1849
+ const instance = this.instances.get(strandId);
1850
+ const config = this.launchConfigs.get(strandId);
1851
+ if (!instance || !config) {
1852
+ throw new Error(`Cannot attach an sApp to strand ${strandId}: not tracked`);
1853
+ }
1854
+ if (!instance.sAppInfo) {
1855
+ return { instance, config };
1856
+ }
1857
+ if (instance.sAppInfo.id !== sAppConfig.id) {
1858
+ log('attachSApp: strand %s already runs sApp %s — the claim for sApp %s is ignored', strandId, instance.sAppInfo.id, sAppConfig.id);
1859
+ }
1860
+ return 'already-attached';
1861
+ }
1862
+ /**
1863
+ * Apply a claim's schema to the replica's live database. A refusal by the replica's tables and
1864
+ * rows puts the retained config back to the replica's ({@link revertRefusedAttach}): the replica
1865
+ * holds no `App` schema, so the refused apply left nothing to drop. Any other failure leaves the
1866
+ * claim retained and unapplied, for the next claim or build to retry.
1867
+ */
1868
+ async applyClaimedSchema(instance, database, sAppConfig) {
1869
+ try {
1870
+ await database.attachAppSchema(sAppConfig);
1871
+ }
1872
+ catch (error) {
1873
+ this.revertRefusedAttach(instance, sAppConfig, error);
1874
+ throw error;
1875
+ }
1876
+ this.forgetAppliedAttach(instance.strandId, sAppConfig, database);
1877
+ }
1511
1878
  /**
1512
1879
  * Whether `strandId` is launched but still waiting for its first sync — a joiner whose
1513
1880
  * runtime is up while its database is withheld (status `'syncing'`, or `'idle'` after
@@ -1763,12 +2130,15 @@ export class StrandInstanceManager {
1763
2130
  }
1764
2131
  log('Stopping strand instance: %s', strandId);
1765
2132
  instance.status = 'stopping';
2133
+ // Before the release awaits, so a build failing meanwhile does not rebuild as the replica.
2134
+ this.unappliedAttaches.delete(strandId);
1766
2135
  this.rejectWritableWaiters(strandId, 'was stopped');
1767
2136
  try {
1768
2137
  await this.releaseRuntime(instance);
1769
2138
  instance.status = 'stopped';
1770
2139
  this.instances.delete(strandId);
1771
2140
  this.launchConfigs.delete(strandId);
2141
+ this.seedRemovalsAnnounced.delete(strandId);
1772
2142
  this.closedQueues.delete(strandId);
1773
2143
  // Storage is released only here — NOT in releaseRuntime, which a quiesce shares.
1774
2144
  await this.disposeStrandStorage(strandId);