@serfab/cadre-core 1.22.0 → 1.24.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 (314) hide show
  1. package/README.md +216 -294
  2. package/dist/arachnode-stub.d.ts +12 -4
  3. package/dist/arachnode-stub.js +15 -8
  4. package/dist/arachnode-stub.js.map +1 -1
  5. package/dist/cadre-invite-protocol.js +5 -4
  6. package/dist/cadre-invite-protocol.js.map +1 -1
  7. package/dist/cadre-node.d.ts +159 -53
  8. package/dist/cadre-node.js +276 -89
  9. package/dist/cadre-node.js.map +1 -1
  10. package/dist/control-authorization.d.ts +14 -2
  11. package/dist/control-authorization.js +8 -3
  12. package/dist/control-authorization.js.map +1 -1
  13. package/dist/control-cohort.d.ts +27 -13
  14. package/dist/control-cohort.js +21 -14
  15. package/dist/control-cohort.js.map +1 -1
  16. package/dist/control-database.d.ts +18 -16
  17. package/dist/control-database.js +57 -22
  18. package/dist/control-database.js.map +1 -1
  19. package/dist/control-protocol-guard.d.ts +1 -1
  20. package/dist/control-protocol-guard.js +7 -3
  21. package/dist/control-protocol-guard.js.map +1 -1
  22. package/dist/control-read-retry.d.ts +49 -11
  23. package/dist/control-read-retry.js +56 -15
  24. package/dist/control-read-retry.js.map +1 -1
  25. package/dist/control-retry.d.ts +32 -3
  26. package/dist/control-retry.js +35 -4
  27. package/dist/control-retry.js.map +1 -1
  28. package/dist/control-schema-version.d.ts +5 -5
  29. package/dist/control-schema-version.js +5 -5
  30. package/dist/control-schema-version.js.map +1 -1
  31. package/dist/control-schema.d.ts +5 -5
  32. package/dist/control-schema.js +1032 -1011
  33. package/dist/control-schema.js.map +1 -1
  34. package/dist/control-write-retry.d.ts +54 -65
  35. package/dist/control-write-retry.js +134 -158
  36. package/dist/control-write-retry.js.map +1 -1
  37. package/dist/delegate-admission.d.ts +1 -1
  38. package/dist/delegate-admission.js +1 -1
  39. package/dist/edge-node/config.d.ts +4 -3
  40. package/dist/edge-node/config.js +11 -9
  41. package/dist/edge-node/config.js.map +1 -1
  42. package/dist/edge-node/dissolve.d.ts +4 -4
  43. package/dist/edge-node/dissolve.js +4 -4
  44. package/dist/edge-node/edge-join.d.ts +1 -1
  45. package/dist/edge-node/edge-join.js +1 -1
  46. package/dist/edge-node/edge-node.js +2 -2
  47. package/dist/edge-node/edge-node.js.map +1 -1
  48. package/dist/edge-node/index.d.ts +1 -0
  49. package/dist/edge-node/index.js +1 -0
  50. package/dist/edge-node/index.js.map +1 -1
  51. package/dist/edge-node/join-credential.d.ts +1 -1
  52. package/dist/edge-node/join-credential.js +1 -1
  53. package/dist/edge-node/lazy-raw-storage.js +12 -0
  54. package/dist/edge-node/lazy-raw-storage.js.map +1 -1
  55. package/dist/edge-node/listen-addrs.d.ts +21 -0
  56. package/dist/edge-node/listen-addrs.js +25 -0
  57. package/dist/edge-node/listen-addrs.js.map +1 -0
  58. package/dist/edge-node/owner-grant.d.ts +1 -1
  59. package/dist/edge-node/owner-grant.js +1 -1
  60. package/dist/edge-node/platform.d.ts +5 -4
  61. package/dist/edge-node/platform.js.map +1 -1
  62. package/dist/edge-node/strand-move.d.ts +1 -1
  63. package/dist/edge-node/strand-move.js +1 -1
  64. package/dist/edge-node/strands.js +27 -11
  65. package/dist/edge-node/strands.js.map +1 -1
  66. package/dist/index.d.ts +7 -5
  67. package/dist/index.js +18 -7
  68. package/dist/index.js.map +1 -1
  69. package/dist/invitation-bootstrap.d.ts +28 -5
  70. package/dist/invitation-bootstrap.js +41 -8
  71. package/dist/invitation-bootstrap.js.map +1 -1
  72. package/dist/link-budget.d.ts +53 -4
  73. package/dist/link-budget.js +58 -5
  74. package/dist/link-budget.js.map +1 -1
  75. package/dist/machine-removal.d.ts +2 -2
  76. package/dist/machine-removal.js +4 -3
  77. package/dist/machine-removal.js.map +1 -1
  78. package/dist/membership-connection-gater.d.ts +2 -2
  79. package/dist/membership-connection-gater.js +2 -2
  80. package/dist/membership-view.d.ts +2 -2
  81. package/dist/membership-view.js +6 -3
  82. package/dist/membership-view.js.map +1 -1
  83. package/dist/node-claim-payload.d.ts +15 -7
  84. package/dist/node-claim-payload.js +25 -9
  85. package/dist/node-claim-payload.js.map +1 -1
  86. package/dist/node-class.d.ts +36 -0
  87. package/dist/node-class.js +26 -0
  88. package/dist/node-class.js.map +1 -0
  89. package/dist/node-default-transports.d.ts +50 -3
  90. package/dist/node-default-transports.js +48 -3
  91. package/dist/node-default-transports.js.map +1 -1
  92. package/dist/node-roles.d.ts +118 -0
  93. package/dist/node-roles.js +142 -0
  94. package/dist/node-roles.js.map +1 -0
  95. package/dist/node-transports.d.ts +6 -2
  96. package/dist/node-transports.js +39 -7
  97. package/dist/node-transports.js.map +1 -1
  98. package/dist/owner-anchor-sync.js +1 -1
  99. package/dist/owner-key-export.js +1 -1
  100. package/dist/owner-key-flows.d.ts +1 -1
  101. package/dist/owner-key-store.js +1 -1
  102. package/dist/owner-signer.js +1 -1
  103. package/dist/peer-authorization.d.ts +3 -1
  104. package/dist/peer-authorization.js +3 -1
  105. package/dist/peer-authorization.js.map +1 -1
  106. package/dist/peer-dial.d.ts +74 -10
  107. package/dist/peer-dial.js +89 -17
  108. package/dist/peer-dial.js.map +1 -1
  109. package/dist/peer-join-backfill.js +4 -4
  110. package/dist/peer-join-backfill.js.map +1 -1
  111. package/dist/peer-record.d.ts +34 -9
  112. package/dist/peer-record.js +66 -13
  113. package/dist/peer-record.js.map +1 -1
  114. package/dist/pending-join-runner.d.ts +1 -1
  115. package/dist/pending-join-runner.js +1 -1
  116. package/dist/provider/client.d.ts +6 -5
  117. package/dist/provider/client.js +3 -3
  118. package/dist/provider/client.js.map +1 -1
  119. package/dist/provider/descriptor.d.ts +1 -1
  120. package/dist/provider/descriptor.js +1 -1
  121. package/dist/provider/oauth.d.ts +1 -1
  122. package/dist/provider/oauth.js +1 -1
  123. package/dist/provider/rent-node.d.ts +4 -3
  124. package/dist/provider/rent-node.js +3 -3
  125. package/dist/provider/rent-node.js.map +1 -1
  126. package/dist/relay-addrs.d.ts +62 -7
  127. package/dist/relay-addrs.js +74 -11
  128. package/dist/relay-addrs.js.map +1 -1
  129. package/dist/relay-reservation.d.ts +1 -1
  130. package/dist/relay-reservation.js +1 -1
  131. package/dist/relay-server.d.ts +6 -5
  132. package/dist/relay-server.js +5 -5
  133. package/dist/relay-server.js.map +1 -1
  134. package/dist/schema-verification.d.ts +13 -10
  135. package/dist/schema-verification.js +32 -24
  136. package/dist/schema-verification.js.map +1 -1
  137. package/dist/sealed-party-key.js +1 -1
  138. package/dist/seed-bootstrap.d.ts +4 -3
  139. package/dist/seed-bootstrap.js +6 -7
  140. package/dist/seed-bootstrap.js.map +1 -1
  141. package/dist/strand-addr-protocol.d.ts +8 -6
  142. package/dist/strand-addr-protocol.js +12 -10
  143. package/dist/strand-addr-protocol.js.map +1 -1
  144. package/dist/strand-app-schema-report.d.ts +16 -2
  145. package/dist/strand-app-schema-report.js +15 -0
  146. package/dist/strand-app-schema-report.js.map +1 -1
  147. package/dist/strand-cohort.d.ts +1 -4
  148. package/dist/strand-cohort.js.map +1 -1
  149. package/dist/strand-commit-durability.d.ts +1 -1
  150. package/dist/strand-database.d.ts +13 -6
  151. package/dist/strand-database.js +17 -9
  152. package/dist/strand-database.js.map +1 -1
  153. package/dist/strand-first-sync-gate.d.ts +3 -2
  154. package/dist/strand-first-sync-gate.js +3 -2
  155. package/dist/strand-first-sync-gate.js.map +1 -1
  156. package/dist/strand-formation-deadlines.d.ts +2 -2
  157. package/dist/strand-formation-deadlines.js +2 -2
  158. package/dist/strand-formation-protocol.d.ts +1 -1
  159. package/dist/strand-formation-protocol.js +51 -16
  160. package/dist/strand-formation-protocol.js.map +1 -1
  161. package/dist/strand-instance-manager.d.ts +134 -42
  162. package/dist/strand-instance-manager.js +331 -76
  163. package/dist/strand-instance-manager.js.map +1 -1
  164. package/dist/strand-membership-reconciler.d.ts +8 -3
  165. package/dist/strand-membership-reconciler.js +8 -3
  166. package/dist/strand-membership-reconciler.js.map +1 -1
  167. package/dist/strand-membership-writer.d.ts +2 -2
  168. package/dist/strand-membership-writer.js +41 -39
  169. package/dist/strand-membership-writer.js.map +1 -1
  170. package/dist/strand-move.js +1 -1
  171. package/dist/strand-network-config.d.ts +15 -5
  172. package/dist/strand-network-config.js +7 -6
  173. package/dist/strand-network-config.js.map +1 -1
  174. package/dist/strand-party-key-rotation.d.ts +7 -3
  175. package/dist/strand-party-key-rotation.js +7 -3
  176. package/dist/strand-party-key-rotation.js.map +1 -1
  177. package/dist/strand-party-machines.d.ts +19 -8
  178. package/dist/strand-party-machines.js +26 -11
  179. package/dist/strand-party-machines.js.map +1 -1
  180. package/dist/strand-party-peers.d.ts +36 -14
  181. package/dist/strand-party-peers.js +24 -15
  182. package/dist/strand-party-peers.js.map +1 -1
  183. package/dist/strand-peer-redial.d.ts +1 -1
  184. package/dist/strand-peer-redial.js +1 -1
  185. package/dist/strand-reactivity.d.ts +20 -17
  186. package/dist/strand-reactivity.js +31 -18
  187. package/dist/strand-reactivity.js.map +1 -1
  188. package/dist/strand-revocation-enforcer.d.ts +3 -3
  189. package/dist/strand-revocation-enforcer.js +3 -3
  190. package/dist/strand-wake-protocol.d.ts +19 -7
  191. package/dist/strand-wake-protocol.js +22 -10
  192. package/dist/strand-wake-protocol.js.map +1 -1
  193. package/dist/strand-watcher.d.ts +1 -1
  194. package/dist/strand-watcher.js +1 -1
  195. package/dist/table-change-watch.js +1 -1
  196. package/dist/types.d.ts +127 -57
  197. package/dist/types.js.map +1 -1
  198. package/dist/webrtc-upgrade.d.ts +254 -0
  199. package/dist/webrtc-upgrade.js +355 -0
  200. package/dist/webrtc-upgrade.js.map +1 -0
  201. package/package.json +9 -9
  202. package/src/announce-addrs.ts +93 -93
  203. package/src/arachnode-stub.ts +18 -10
  204. package/src/bootstrap-peer-store-file.ts +44 -44
  205. package/src/bootstrap-peer-store.ts +214 -214
  206. package/src/cadre-invite-protocol.ts +741 -740
  207. package/src/cadre-node.ts +12462 -12252
  208. package/src/claim-proof.ts +147 -147
  209. package/src/control-authorization.ts +290 -276
  210. package/src/control-cohort.ts +223 -204
  211. package/src/control-database.ts +72 -28
  212. package/src/control-formation-recorder.ts +359 -359
  213. package/src/control-protocol-guard.ts +370 -366
  214. package/src/control-read-retry.ts +222 -180
  215. package/src/control-retry.ts +36 -4
  216. package/src/control-schema-version.ts +301 -301
  217. package/src/control-schema.ts +1108 -1087
  218. package/src/control-write-retry.ts +639 -669
  219. package/src/delegate-admission.ts +351 -351
  220. package/src/describe-thrown.ts +60 -60
  221. package/src/ed25519-key.ts +185 -185
  222. package/src/edge-node/config.ts +13 -10
  223. package/src/edge-node/dissolve.ts +252 -252
  224. package/src/edge-node/edge-join.ts +320 -320
  225. package/src/edge-node/edge-node.ts +1095 -1095
  226. package/src/edge-node/index.ts +60 -59
  227. package/src/edge-node/join-credential.ts +16 -16
  228. package/src/edge-node/lazy-raw-storage.ts +194 -178
  229. package/src/edge-node/listen-addrs.ts +26 -0
  230. package/src/edge-node/node-local.ts +84 -84
  231. package/src/edge-node/options.ts +195 -195
  232. package/src/edge-node/owner-grant.ts +63 -63
  233. package/src/edge-node/platform.ts +5 -4
  234. package/src/edge-node/strand-move.ts +266 -266
  235. package/src/edge-node/strands.ts +27 -12
  236. package/src/enrolled-machine-store-file.ts +43 -43
  237. package/src/enrolled-machine-store.ts +280 -280
  238. package/src/fetch-impl.ts +23 -23
  239. package/src/file-durable-slot.ts +64 -64
  240. package/src/file-safe-name.ts +32 -32
  241. package/src/formation-approval.ts +604 -604
  242. package/src/formation-token.ts +63 -63
  243. package/src/fs-atomic.ts +92 -92
  244. package/src/index.ts +987 -957
  245. package/src/invitation-bootstrap.ts +152 -118
  246. package/src/joined-strand-store.ts +553 -553
  247. package/src/key-store-file.ts +142 -142
  248. package/src/link-budget.ts +61 -5
  249. package/src/machine-removal.ts +211 -210
  250. package/src/member-redemption.ts +643 -643
  251. package/src/membership-connection-gater.ts +650 -650
  252. package/src/membership-view.ts +147 -144
  253. package/src/node-claim-payload.ts +34 -12
  254. package/src/node-class.ts +47 -0
  255. package/src/node-default-transports.ts +65 -3
  256. package/src/node-roles.ts +220 -0
  257. package/src/node-transports.ts +86 -49
  258. package/src/owner-anchor-sync.ts +172 -172
  259. package/src/owner-grant-protocol.ts +547 -547
  260. package/src/owner-key-export.ts +348 -348
  261. package/src/owner-key-flows.ts +109 -109
  262. package/src/owner-key-store.ts +1 -1
  263. package/src/owner-keys.ts +179 -179
  264. package/src/owner-signer.ts +92 -92
  265. package/src/peer-addr-book.ts +252 -252
  266. package/src/peer-authorization.ts +584 -582
  267. package/src/peer-dial.ts +698 -605
  268. package/src/peer-join-backfill.ts +961 -961
  269. package/src/peer-record.ts +71 -16
  270. package/src/pending-join-runner.ts +798 -798
  271. package/src/primary-lan-address.ts +47 -47
  272. package/src/provider/client.ts +327 -326
  273. package/src/provider/descriptor.ts +129 -129
  274. package/src/provider/index.ts +59 -59
  275. package/src/provider/oauth.ts +285 -285
  276. package/src/provider/rent-node.ts +276 -275
  277. package/src/relay-addrs.ts +90 -12
  278. package/src/relay-reservation.ts +1 -1
  279. package/src/relay-server.ts +99 -98
  280. package/src/schema-verification.ts +38 -23
  281. package/src/sealed-party-key.ts +190 -190
  282. package/src/seed-bootstrap.ts +8 -11
  283. package/src/seed-trust-policy.ts +353 -353
  284. package/src/self-address-update.ts +19 -19
  285. package/src/strand-addr-protocol.ts +17 -14
  286. package/src/strand-app-schema-report.ts +147 -122
  287. package/src/strand-cohort.ts +1 -5
  288. package/src/strand-commit-durability.ts +165 -165
  289. package/src/strand-database.ts +522 -510
  290. package/src/strand-first-sync-gate.ts +3 -2
  291. package/src/strand-formation-deadlines.ts +227 -227
  292. package/src/strand-formation-manager.ts +731 -731
  293. package/src/strand-formation-protocol.ts +1174 -1138
  294. package/src/strand-fret-addrs.ts +179 -179
  295. package/src/strand-instance-manager.ts +381 -85
  296. package/src/strand-membership-reconciler.ts +1315 -1310
  297. package/src/strand-membership-writer.ts +2152 -2150
  298. package/src/strand-move.ts +1 -1
  299. package/src/strand-network-config.ts +16 -6
  300. package/src/strand-offline.ts +178 -178
  301. package/src/strand-party-key-rotation.ts +440 -436
  302. package/src/strand-party-machines.ts +308 -293
  303. package/src/strand-party-peers.ts +151 -129
  304. package/src/strand-peer-redial.ts +1 -1
  305. package/src/strand-reactivity.ts +36 -19
  306. package/src/strand-revocation-enforcer.ts +758 -758
  307. package/src/strand-wake-protocol.ts +406 -394
  308. package/src/strand-watcher.ts +1 -1
  309. package/src/table-change-watch.ts +285 -285
  310. package/src/timed-step.ts +28 -28
  311. package/src/timeout-scheduler.ts +29 -29
  312. package/src/trusted-owner-store.ts +242 -242
  313. package/src/types.ts +3182 -3112
  314. package/src/webrtc-upgrade.ts +439 -0
@@ -2,12 +2,13 @@ import debug from 'debug';
2
2
  import type { Libp2p, PrivateKey } from '@libp2p/interface';
3
3
  import type { ICohortReachability } from '@optimystic/db-core';
4
4
  import { createLibp2pNode, type IRawStorage } from '@optimystic/db-p2p';
5
- import { wrapStorageWithCache, disposeStorageCache } from '@serfab/quereus-plugin-sereus';
5
+ import { wrapStorageWithCache, disposeStorageCache, checkAppSchema, appSchemaRefusalOf } from '@serfab/quereus-plugin-sereus';
6
6
  import { StrandDatabase, type StrandDatabaseOffline } from './strand-database.js';
7
7
  import type { StrandCommitDurability, StrandCommitHeld } from './strand-commit-durability.js';
8
8
  import type { StrandOfflineConfig, StrandOfflineListeners, StrandOfflineMode } from './strand-offline.js';
9
9
  import type { StrandAppSchemaListeners } from './strand-app-schema-report.js';
10
10
  import { PeerJoinBackfill, type PeerJoinBackfillConfig } from './peer-join-backfill.js';
11
+ import { WebrtcUpgradeService } from './webrtc-upgrade.js';
11
12
  import { strandNetworkStatePersistence, type StrandNetworkStateStore } from './strand-network-state.js';
12
13
  import {
13
14
  StrandRevocationEnforcer,
@@ -38,7 +39,6 @@ import type {
38
39
  StorageConfig,
39
40
  NetworkConfig,
40
41
  LatencyHint,
41
- NodeProfile,
42
42
  SAppConfig,
43
43
  SAppInfo,
44
44
  RawStorageProvider,
@@ -46,21 +46,23 @@ import type {
46
46
  } from './types.js';
47
47
  import { DEFAULT_CONNECTION_MONITOR, resolveStrandClusterSize, strandClusterPolicy } from './types.js';
48
48
  import { strandNodeAddrs } from './strand-network-config.js';
49
+ import { listenTransportNodeOptions } from './relay-addrs.js';
49
50
  import { nodeTransportsOption } from './node-transports.js';
50
51
  import { resolveRelayServer } from './relay-server.js';
52
+ import type { NodeRoles } from './node-roles.js';
51
53
  import { strandCohortTopicOption, type StrandReactivityConfig } from './strand-reactivity.js';
52
54
  import { superviseRelayReservation, type RelayReservationSupervisor } from './relay-reservation.js';
53
55
  import { strandRedialTimings, superviseStrandPeerRedial, type StrandPeerRedial } from './strand-peer-redial.js';
54
56
  import { groupAddrsByPeerId } from './peer-addr-book.js';
55
- import { isCohortUnreachableRead } from './control-read-retry.js';
56
- import { declaredCohortReadDeadlineMs, optimysticDialLimits, peerJoinPushBudget, relayReservationBudgetMs, resolveLinkRoundTripMs } from './link-budget.js';
57
+ import { isCohortUnreachableRead, isNoCoordinatorResolved } from './control-read-retry.js';
58
+ import { declaredCohortReadDeadlineMs, optimysticDialLimits, peerJoinPushBudget, relayReservationBudgetMs, resolveLinkRoundTripMs, webrtcUpgradeDialBudgetMs } from './link-budget.js';
57
59
  import { describeThrown } from './describe-thrown.js';
58
60
 
59
61
  const log = debug('sereus:cadre:strand-manager');
60
62
 
61
63
  /**
62
- * How often a joining launch that could not build its database, because no seed peer had
63
- * answered, retries the build on its running libp2p node
64
+ * How often a launch that could not build its database, because no machine that can answer for
65
+ * the strand's blocks was reachable, retries the build on its running libp2p node
64
66
  * (`StrandInstanceManager.deferUnreachableJoin`). Each attempt composes a fresh database and
65
67
  * re-reads the schema catalog over the network, so it is spaced well above the first-sync
66
68
  * gate's probe cadence.
@@ -73,13 +75,29 @@ export const UNREACHABLE_JOIN_RETRY_MS = 5_000;
73
75
 
74
76
  /**
75
77
  * How one database build of a runtime ended ({@link StrandInstanceManager.buildStrandDatabase}):
76
- * published or held by the first-sync gate; failed only because no seed peer has answered yet;
77
- * or overtaken by a release of the runtime it was building on.
78
+ * published or held by the first-sync gate; failed only because no machine that can answer for
79
+ * the strand's blocks was reachable yet; or overtaken by a release of the runtime it was
80
+ * building on.
81
+ *
82
+ * `'awaiting-peer'` rather than "awaiting seed": the peer a launch waits for is a seed for a
83
+ * joining storage replica, but for a client (`roles.strandCohortMember: false`) it is any
84
+ * serving machine, which it may reach by a dial rather than through a seed.
78
85
  */
79
- type StrandDatabaseBuild = 'built' | 'awaiting-seed' | 'released';
86
+ type StrandDatabaseBuild = 'built' | 'awaiting-peer' | 'released';
80
87
 
81
88
  const timing = debug('sereus:cadre:timing');
82
89
 
90
+ /**
91
+ * An sApp claim of a storage replica ({@link StrandInstanceManager.attachSApp}) that the retained
92
+ * launch config carries and that has not been applied to the strand yet.
93
+ */
94
+ interface UnappliedAttach {
95
+ /** The claiming sApp's config, as the retained launch config holds it. */
96
+ sAppConfig: SAppConfig;
97
+ /** The instance's latency hint before the claim, for a fallback to the replica to put back. */
98
+ latencyHint: LatencyHint;
99
+ }
100
+
83
101
  /** One caller blocked in {@link StrandInstanceManager.whenWritable}. */
84
102
  interface WritableWaiter {
85
103
  resolve: () => void;
@@ -131,7 +149,15 @@ export interface StartStrandConfig {
131
149
  sAppConfig?: SAppConfig;
132
150
  storage?: StorageConfig;
133
151
  network?: NetworkConfig;
134
- profile: NodeProfile;
152
+ /**
153
+ * What this node does, resolved once by the owning {@link CadreNode} (`node-roles.ts`).
154
+ * Retained with the launch config, so a strand woken from hibernation is rebuilt with the
155
+ * same roles. Read here for the FRET tier, Ring Zulu, the relay-server default, the
156
+ * cohort-topic host profile, and — `strandCohortMember` — whether the strand node stores
157
+ * the strand's blocks or is built as a client that reads and writes through the machines
158
+ * that do (`buildStrandRuntime`; `startStrand` resolves no store for a client).
159
+ */
160
+ roles: NodeRoles;
135
161
  defaultLatencyHint: LatencyHint;
136
162
  privateKey?: PrivateKey;
137
163
  /** Cohort-derived discovery seed (multiaddr strings). Defaults to [] when omitted. */
@@ -347,7 +373,7 @@ export interface StartStrandConfig {
347
373
  onCommitHeld?: (event: StrandCommitHeld) => void;
348
374
 
349
375
  /**
350
- * Offline mode for this strand (docs/strands.md → "Offline mode"), forwarded from
376
+ * Offline mode for this strand (docs/strands/writes.md → "Offline mode"), forwarded from
351
377
  * `CadreNodeConfig.strandOffline`, with where each database built for the launch reports its
352
378
  * queue (`CadreNode` emits them as events). Absent: no database gets an offline queue. The mode
353
379
  * itself is the manager's, per strand ({@link StrandInstanceManager.setOfflineMode}).
@@ -355,8 +381,9 @@ export interface StartStrandConfig {
355
381
  offline?: StrandOfflineConfig & StrandOfflineListeners;
356
382
 
357
383
  /**
358
- * Where each database built for the launch reports an `App` schema apply it held back
359
- * (`CadreNode` emits them as events). Retained and isolated like {@link onCommitDurability}.
384
+ * Where each database built for the launch reports an `App` schema apply it held back, and a
385
+ * higher App schema version another member recorded (`CadreNode` emits the first as events and
386
+ * stops the strand on the second). Retained and isolated like {@link onCommitDurability}.
360
387
  */
361
388
  appSchema?: StrandAppSchemaListeners;
362
389
 
@@ -494,6 +521,7 @@ function verifiedSAppInfo(strandId: string, sAppConfig: SAppConfig, requireSigne
494
521
  return {
495
522
  id: sAppConfig.id,
496
523
  version: sAppConfig.version,
524
+ schemaVersion: sAppConfig.schemaVersion,
497
525
  schema: sAppConfig.schema,
498
526
  signature: sAppConfig.signature
499
527
  };
@@ -513,7 +541,7 @@ export class StrandInstanceManager {
513
541
  /**
514
542
  * Retained launch config per strand, captured in `startStrand` and cleared in
515
543
  * `stopStrand`. `resumeStrand` reuses it to rebuild a quiesced strand's runtime
516
- * without the caller re-threading storage/network/profile/key/sApp config.
544
+ * without the caller re-threading storage/network/node-class/key/sApp config.
517
545
  */
518
546
  private launchConfigs: Map<string, StartStrandConfig> = new Map();
519
547
  /**
@@ -579,6 +607,13 @@ export class StrandInstanceManager {
579
607
  * nobody and a resume redials over the new node.
580
608
  */
581
609
  private peerRedials: Map<string, StrandPeerRedial> = new Map();
610
+ /**
611
+ * The per-strand background WebRTC upgrade of relayed connections (`webrtc-upgrade.ts`), keyed
612
+ * by strand id. Same lifecycle as {@link peerRedials}: started in `buildStrandRuntime` once
613
+ * the libp2p node exists, stopped first in `releaseRuntime`, so a hibernating strand dials no
614
+ * upgrade and a resume judges the new node's connections with no backoff carried over.
615
+ */
616
+ private webrtcUpgrades: Map<string, WebrtcUpgradeService> = new Map();
582
617
  /**
583
618
  * The party's other machines known to hold each strand (`strand-party-machines.ts`), keyed
584
619
  * by strand id, on a node offering offline mode for a launch with a party-machine seam. Same
@@ -634,10 +669,19 @@ export class StrandInstanceManager {
634
669
  private transitions: Map<string, RuntimeTransition> = new Map();
635
670
  /**
636
671
  * The pending database retry per strand id of a launch whose database could not be built
637
- * because no seed peer had answered yet ({@link deferUnreachableJoin}). Cleared by
672
+ * because no machine that can answer for the strand's blocks was reachable yet
673
+ * ({@link deferUnreachableJoin}). Cleared by
638
674
  * {@link releaseRuntime}, so a stop or a quiesce cancels it.
639
675
  */
640
676
  private unreachableJoinRetries: Map<string, unknown> = new Map();
677
+ /**
678
+ * Per strand id, the sApp claim ({@link attachSApp}) whose schema the retained launch config
679
+ * carries but no apply has landed yet: the claim found no live database, or its live apply failed
680
+ * for a reason that may pass. Lets a build that refuses that schema fall back to the replica
681
+ * ({@link revertRefusedAttach}). Deleted when a database applies the schema, by that fallback,
682
+ * and when {@link stopStrand} begins.
683
+ */
684
+ private unappliedAttaches: Map<string, UnappliedAttach> = new Map();
641
685
  /**
642
686
  * The offline mode set per strand id ({@link setOfflineMode}); a strand absent here runs in its
643
687
  * launch's `initialMode`. Never cleared: the mode belongs to the strand, not to one database, so
@@ -679,6 +723,11 @@ export class StrandInstanceManager {
679
723
  return this.instances.has(strandId);
680
724
  }
681
725
 
726
+ /** The sApp config the tracked strand's next build applies (its retained launch config's), or `undefined` for a replica or an untracked strand. */
727
+ launchedSAppConfig(strandId: string): SAppConfig | undefined {
728
+ return this.launchConfigs.get(strandId)?.sAppConfig;
729
+ }
730
+
682
731
  /**
683
732
  * Start a new strand instance.
684
733
  *
@@ -734,9 +783,19 @@ export class StrandInstanceManager {
734
783
  // function is provided, it is called with the strandId to create strand-specific
735
784
  // storage (e.g. strand-isolated directories). A provider that throws therefore
736
785
  // fails the launch alongside the schema-signature check, leaving nothing tracked.
737
- const strandStorage = resolveStrandStorage(config.storage?.provider, strandId);
786
+ //
787
+ // Never on a client (`roles.strandCohortMember: false`, built so in `buildStrandRuntime`):
788
+ // it stores no blocks, and the provider call itself has a side effect — a per-strand
789
+ // database on a phone, a per-strand directory on a node — so it is not made. Nothing is
790
+ // recorded in `strandStorages`, and every reader of that map (the join catch-up, the
791
+ // first-join test, the storage dispose) already handles the absent store.
792
+ const strandStorage = config.roles.strandCohortMember
793
+ ? resolveStrandStorage(config.storage?.provider, strandId)
794
+ : undefined;
738
795
  if (strandStorage) {
739
796
  log('Strand %s using provided storage provider', strandId);
797
+ } else if (!config.roles.strandCohortMember) {
798
+ log('Strand %s runs as a client: no store is resolved, its blocks live on the serving machines', strandId);
740
799
  }
741
800
 
742
801
  // Determine latency hint: sApp config > default
@@ -816,15 +875,15 @@ export class StrandInstanceManager {
816
875
  * Build (or rebuild) the libp2p node + StrandDatabase for an instance and
817
876
  * attach them, transitioning it to `active`. Shared by `startStrand` (fresh
818
877
  * launch) and `resumeStrand` (rehydrating a quiesced instance). Reads all
819
- * volatile inputs (bootstrapNodes, servingMachines, network, profile,
878
+ * volatile inputs (bootstrapNodes, servingMachines, network, roles,
820
879
  * privateKey, sApp config) from `config`, so the caller controls the
821
880
  * cohort-derived values. Storage is the
822
881
  * one input it does NOT re-read from `config`: that belongs to the instance and
823
882
  * comes from `strandStorages`.
824
883
  *
825
- * A database that cannot be built because no seed peer has answered yet does not fail the
826
- * build: the runtime comes up `'syncing'` without it and the database phase alone is
827
- * retried on the same node ({@link deferUnreachableJoin}).
884
+ * A database that cannot be built because no machine that can answer for the strand's blocks
885
+ * was reachable does not fail the build: the runtime comes up `'syncing'` without it and the
886
+ * database phase alone is retried on the same node ({@link deferUnreachableJoin}).
828
887
  */
829
888
  private async buildStrandRuntime(instance: StrandInstance, config: StartStrandConfig): Promise<void> {
830
889
  const strandId = instance.strandId;
@@ -835,6 +894,12 @@ export class StrandInstanceManager {
835
894
  // surface later inside a path that logs and carries on. `link-budget.ts`.
836
895
  resolveLinkRoundTripMs(config.network?.linkRoundTripMs);
837
896
 
897
+ // Whether this strand node stores and signs the strand's blocks, or is a CLIENT that reads
898
+ // and writes through the machines that do (`NodeRoles.strandCohortMember`). The one place
899
+ // the role is turned into a node: everything below that differs on a client follows from
900
+ // this binding, and `startStrand` resolved no store for one, so `strandStorage` is undefined
901
+ // there and `backfillArms` is false with it.
902
+ const servesBlocks = config.roles.strandCohortMember;
838
903
  // The store the instance OWNS (resolved once in `startStrand`), not a fresh
839
904
  // resolution: a rebuild must reach the same backend through the same warm cache.
840
905
  const strandStorage = this.strandStorages.get(strandId);
@@ -852,7 +917,7 @@ export class StrandInstanceManager {
852
917
 
853
918
  // Whether this node runs the circuit-relay server, and its init — the same
854
919
  // resolution the control node takes from the same config (`relay-server.ts`).
855
- const relayServer = resolveRelayServer(config.network, config.profile);
920
+ const relayServer = resolveRelayServer(config.network, config.roles);
856
921
  // The strand-node VIEW of the machine's one `NetworkConfig`, not the control
857
922
  // node's resolution: fixed direct listen ports become ephemeral (two nodes cannot
858
923
  // bind one port), the announce config is dropped (it names the control node's
@@ -864,8 +929,10 @@ export class StrandInstanceManager {
864
929
  // `strand-network-config.ts` for all three, and `relay-reservation.ts`.
865
930
  //
866
931
  // `relayAddrs` is destructured OFF: it is not a `createLibp2pNode` option, and
867
- // spreading it would hand db-p2p a key it does not know.
868
- const { relayAddrs: relayDialAddrs = [], ...addrOptions } = strandNodeAddrs(config.network);
932
+ // spreading it would hand db-p2p a key it does not know. `listenTransports` is split out
933
+ // for the same reason — `wsPort` is db-p2p's switch but the WebRTC ICE servers beside it
934
+ // are read only by `network.defaultTransports` (`listenTransportNodeOptions` drops them).
935
+ const { relayAddrs: relayDialAddrs = [], listenAddrs, ...listenTransports } = strandNodeAddrs(config.network);
869
936
 
870
937
  // Bound once, before anything is built — so, like the round-trip check above, a
871
938
  // rejected clusterSize fails the build with nothing to release. The breadth is also
@@ -927,9 +994,9 @@ export class StrandInstanceManager {
927
994
  ? { connectionGater: config.network.connectionGater }
928
995
  : {};
929
996
 
930
- const reactivityOption = strandCohortTopicOption(config.reactivity, strandId);
997
+ const reactivityOption = strandCohortTopicOption(config.reactivity, strandId, config.roles.reactivity);
931
998
  if (reactivityOption.cohortTopic) {
932
- log('strand %s: change notifications on', strandId);
999
+ log('strand %s: change notifications on, as %s', strandId, config.roles.reactivity);
933
1000
  }
934
1001
 
935
1002
  // The party's other machines holding this strand, for the offline queue's gate, each commit's
@@ -963,8 +1030,16 @@ export class StrandInstanceManager {
963
1030
  // sibling recorded is never read as removed. If a peer is ever seen left out of cohorts
964
1031
  // this way, the row needs a proof that the id it states is the machine's own.
965
1032
  ...(partyMachines && { isNetworkMember: (peerId: string) => !partyMachines.removed().has(peerId) }),
1033
+ // A client registers none of the four storage protocol services, so every other machine
1034
+ // classifies it from its identify list as not serving and leaves it out of every cohort,
1035
+ // its own view of itself included; its reads and writes go to a coordinator among the
1036
+ // strand's serving machines (`../optimystic/docs/internals.md` → "Client nodes"). The
1037
+ // serving-only options Optimystic would ignore on a client stay off it below: `storage`
1038
+ // is undefined here on a client (`startStrand`), `arachnode` is behind this flag, and
1039
+ // `rebalance` is behind `backfillArms`, which the absent store already made false.
1040
+ servesBlocks,
966
1041
  storage: strandStorage,
967
- fretProfile: config.profile === 'storage' ? 'core' : 'edge',
1042
+ fretProfile: config.roles.overlayTier,
968
1043
  relay: relayServer.enabled,
969
1044
  // NOTE: unlike the control node, a strand node has no unauthorized-reservation budget,
970
1045
  // so with the per-connection cap off any peer that reaches this node can hold one of
@@ -989,10 +1064,15 @@ export class StrandInstanceManager {
989
1064
  servingMachines: config.servingMachines,
990
1065
  cohortQueryTimeoutMs: declaredCohortReadDeadlineMs(config.network)
991
1066
  }),
992
- arachnode: {
993
- enableRingZulu: config.profile === 'storage'
994
- },
995
- // One join catch-up per node. On a storage-profile node Optimystic's rebalance growth
1067
+ // A client builds no Arachnode at all, so the option is not stated for one.
1068
+ ...(servesBlocks && {
1069
+ arachnode: {
1070
+ // Follows `alwaysOn`, for the control node's reason (`cadre-node.ts`): the storage
1071
+ // rings Ring Zulu hints at are unimplemented, so there is no second role to set.
1072
+ enableRingZulu: config.roles.alwaysOn
1073
+ }
1074
+ }),
1075
+ // One join catch-up per node. On an always-on node Optimystic's rebalance growth
996
1076
  // arm pushes a joiner every block whose cohort it entered, one request per block, and
997
1077
  // it never hears of the peer-join catch-up's pushes, so each block would go twice. The
998
1078
  // catch-up pushes every block to every peer it serves, the growth arm's targets
@@ -1025,7 +1105,7 @@ export class StrandInstanceManager {
1025
1105
  // that fills the bare `/p2p-circuit` slots: otherwise a cohort seed running the relay
1026
1106
  // server takes one as soon as it connects (`relay-reservation.ts`, "WHY LIBP2P'S
1027
1107
  // RELAY DISCOVERY IS SWITCHED OFF").
1028
- ...nodeTransportsOption(config.network, addrOptions, relayDialAddrs.length > 0),
1108
+ ...nodeTransportsOption(config.network, listenTransports, relayDialAddrs.length > 0),
1029
1109
  ...(config.network?.noiseCrypto && { noiseCrypto: config.network.noiseCrypto }),
1030
1110
  // Unconditional, and the same default the control node takes: every node of
1031
1111
  // every party runs the monitor over its connection to a slow phone, so the
@@ -1047,7 +1127,8 @@ export class StrandInstanceManager {
1047
1127
  // supervisor below fills. That is what gives a NAT'd strand node a reachable relay
1048
1128
  // slot — and works against a party-run relay because the launch path announced
1049
1129
  // this strand's derived peerId to it first (delegate admission; see cadre-node.ts).
1050
- ...addrOptions,
1130
+ ...(listenAddrs && { listenAddrs }),
1131
+ ...listenTransportNodeOptions(listenTransports),
1051
1132
  // The raw configured gater (open strands), or the revocation-composed
1052
1133
  // gater plus the fail-closed per-stream revoked-peer gate (closed
1053
1134
  // strands) — resolved above, before the try.
@@ -1063,7 +1144,14 @@ export class StrandInstanceManager {
1063
1144
  // database (`StrandPeer`): a background write that never fails or delays the launch.
1064
1145
  // The seam defers it while a write could fork the party and retries it on cohort
1065
1146
  // growth and from every membership reconciler pass, so a refusal here is not final.
1066
- // Written for open strands too: their row is what a sibling's offline queue waits for.
1147
+ //
1148
+ // Written by EVERY machine, client or serving, and for an open strand as well as a closed
1149
+ // one: in a closed strand the row is how a sibling and the party key replacement bind this
1150
+ // machine, which a client needs as much as a server, and an open strand's row is what a
1151
+ // sibling's offline queue waits for (docs/strands/membership.md → "Binding the party's
1152
+ // machines"). Whether this machine serves is the row's role column, which
1153
+ // `CadreNode.publishStrandPeer` fills from the node's own role; the one reader that must
1154
+ // skip a client filters on it (`strand-party-machines.ts`).
1067
1155
  if (config.partyPeers) {
1068
1156
  void config.partyPeers.publishOwn(node.peerId.toString()).catch((error) => {
1069
1157
  log('Strand %s: publishing this machine\'s StrandPeer row threw (retried later): %o', strandId, error);
@@ -1098,6 +1186,19 @@ export class StrandInstanceManager {
1098
1186
  ...(partyMachines && { partyMachines: () => partyMachines.machines().map((machine) => machine.strandPeerId) })
1099
1187
  }, strandRedialTimings(config.network?.linkRoundTripMs)));
1100
1188
 
1189
+ // Try a direct WebRTC connection in the background for each member this node ends up
1190
+ // reaching through a relay, which on a strand is the normal case: a strand's peers are
1191
+ // other parties' machines, so both sides are often behind NAT. Armed here rather than
1192
+ // after the database phase, so a direct path can be in place by the time the first sync's
1193
+ // reads run. Inert unless the embedder passed a WebRTC transport (`webrtc-upgrade.ts`).
1194
+ const webrtcUpgrade = new WebrtcUpgradeService({
1195
+ label: strandId,
1196
+ node,
1197
+ dialTimeoutMs: webrtcUpgradeDialBudgetMs(config.network?.linkRoundTripMs)
1198
+ });
1199
+ this.webrtcUpgrades.set(strandId, webrtcUpgrade);
1200
+ webrtcUpgrade.start();
1201
+
1101
1202
  const databaseBuild = await this.buildStrandDatabase(instance, config, node);
1102
1203
  if (!this.isCurrentRuntime(instance, node)) {
1103
1204
  // A stop released this runtime during the database phase (`stopStrand` does not
@@ -1135,6 +1236,9 @@ export class StrandInstanceManager {
1135
1236
  // peer-join-backfill.ts for the strand-side argument (and why the control
1136
1237
  // network, which DOES gate, is different).
1137
1238
  //
1239
+ // Never on a client: it holds no blocks to push, and `startStrand` resolved it no store,
1240
+ // which is what `backfillArms` reads.
1241
+ //
1138
1242
  // NOTE: cost is one PeerJoinBackfill object + one `peer:identify` listener
1139
1243
  // per running strand — linear in strand count, negligible at the handful a
1140
1244
  // device or host runs today. If a node ever hosts strands by the hundred,
@@ -1186,7 +1290,7 @@ export class StrandInstanceManager {
1186
1290
  // No `lastActivity` stamp: bringing a runtime up is not activity. A check-in marks
1187
1291
  // activity before its resume and must see only what landed while the strand was up.
1188
1292
  instance.status = liveStrandStatus(instance);
1189
- if (databaseBuild === 'awaiting-seed') {
1293
+ if (databaseBuild === 'awaiting-peer') {
1190
1294
  // Armed only now that the build is over: a retry firing mid-build would find the
1191
1295
  // build in flight.
1192
1296
  this.deferUnreachableJoin(instance);
@@ -1212,10 +1316,13 @@ export class StrandInstanceManager {
1212
1316
  * {@link buildStrandRuntime} and again by each {@link retryUnreachableJoin}, with a new
1213
1317
  * StrandDatabase per attempt.
1214
1318
  *
1215
- * Returns `'awaiting-seed'` when initialize failed only because no seed peer has answered
1216
- * (`cohort-unreachable`): that attempt's database is closed and the node keeps running. Any
1217
- * other failure throws, with the attempt's database left with its gate for
1319
+ * Returns `'awaiting-peer'` when initialize failed only because no machine that can answer for
1320
+ * the strand's blocks was reachable: that attempt's database is closed and the node keeps
1321
+ * running. Any other failure throws, with the attempt's database left with its gate for
1218
1322
  * {@link releaseRuntime} to close.
1323
+ *
1324
+ * A client node's database (`roles.strandCohortMember: false`) is published as soon as it
1325
+ * initializes, like a founder's: see the first-sync decision below.
1219
1326
  */
1220
1327
  private async buildStrandDatabase(
1221
1328
  instance: StrandInstance,
@@ -1233,6 +1340,7 @@ export class StrandInstanceManager {
1233
1340
  strandId,
1234
1341
  sAppConfig: config.sAppConfig,
1235
1342
  libp2pNode: node,
1343
+ // Absent on a client, which coordinates no writes; the database then connects without one.
1236
1344
  coordinatedRepo: node.coordinatedRepo,
1237
1345
  // Founder bootstrap inputs: the strand's type drives which membership rows
1238
1346
  // are written, and the PARTY's own key (partyMemberPrivateKey, resolved by the
@@ -1272,14 +1380,20 @@ export class StrandInstanceManager {
1272
1380
  try {
1273
1381
  await strandDb.initialize();
1274
1382
  } catch (error) {
1275
- if (!isCohortUnreachableRead(error)) {
1383
+ // The two shapes of "nobody who can answer for this strand's blocks is reachable yet": a
1384
+ // cohort member that could not be asked (a joining replica whose seed is silent, a founder
1385
+ // whose cohort is), and no coordinator resolvable at all (a client, whose own cohort is
1386
+ // empty by construction, so every block falls through to `findCoordinator`). Any other
1387
+ // failure — a schema that cannot apply here, a refused signature — fails the launch, which
1388
+ // is what matching one error class by type each buys over reading the message.
1389
+ if (!isCohortUnreachableRead(error) && !isNoCoordinatorResolved(error)) {
1276
1390
  throw error;
1277
1391
  }
1278
1392
  await this.discardDatabaseAttempt(strandId, gate);
1279
- log('Strand %s: no seed peer has answered yet, so this joiner cannot build its database (%s); ' +
1280
- 'its runtime stays up and the build is retried every %dms',
1393
+ log('Strand %s: no machine that can answer for this strand is reachable yet, so this launch ' +
1394
+ 'cannot build its database (%s); its runtime stays up and the build is retried every %dms',
1281
1395
  strandId, describeThrown(error), UNREACHABLE_JOIN_RETRY_MS);
1282
- return 'awaiting-seed';
1396
+ return 'awaiting-peer';
1283
1397
  }
1284
1398
  timing('[buildStrandRuntime:%s] strandDatabase.initialize: %dms', strandId, Math.round(performance.now() - t0));
1285
1399
  if (this.firstSyncGates.get(strandId) !== gate) {
@@ -1288,6 +1402,7 @@ export class StrandInstanceManager {
1288
1402
  await strandDb.close();
1289
1403
  return 'released';
1290
1404
  }
1405
+ this.forgetAppliedAttach(strandId, config.sAppConfig, strandDb);
1291
1406
 
1292
1407
  // The first-sync write gate. A founder just wrote the Header in its bootstrap; any
1293
1408
  // other machine may commit only once it holds the Header — which it can only have
@@ -1310,7 +1425,18 @@ export class StrandInstanceManager {
1310
1425
  if (awaitPush) {
1311
1426
  log('Strand %s: first join over an empty store; waiting for a member\'s push before the first sync probe', strandId);
1312
1427
  }
1313
- const synced = config.founder === true || (!awaitPush && await gate.probeOnce());
1428
+ // A client is treated as synced, like a founder. The gate stops a joining machine inventing a
1429
+ // collection while it is the whole cohort for every block; a client is in no cohort, so a
1430
+ // write with no serving machine reachable resolves no coordinator and fails instead of
1431
+ // committing locally — there is no fork to prevent. Gating it would also be wrong in itself:
1432
+ // its probe reads would be remote reads repeated on the backstop (it has no storage change
1433
+ // feed to wake it), and while the database was withheld the app could neither write nor
1434
+ // queue. So on a client `addStrand` resolving means the database is open, not that a member
1435
+ // has been reached: the first read or write fails, retryably, until a serving machine is
1436
+ // reachable (docs/strands/formation.md → "Joining: no writes before the first sync"). The
1437
+ // gate object stays as the handle `releaseRuntime` closes the database through.
1438
+ const client = !config.roles.strandCohortMember;
1439
+ const synced = config.founder === true || client || (!awaitPush && await gate.probeOnce());
1314
1440
  timing('[buildStrandRuntime:%s] first-sync probe: %dms', strandId, Math.round(performance.now() - t0));
1315
1441
  if (this.firstSyncGates.get(strandId) !== gate) {
1316
1442
  // A stop released the runtime during the probe and closed this database through its gate.
@@ -1382,9 +1508,10 @@ export class StrandInstanceManager {
1382
1508
  }
1383
1509
 
1384
1510
  /**
1385
- * The party's other machines known to hold `strandId` with no open connection from its strand
1511
+ * The party's other machines known to STORE `strandId` ({@link StrandPartyMachines.machines},
1512
+ * clients already dropped) with no open connection from its strand
1386
1513
  * node: what an offline queue reporting `waitingFor: 'cohort'` may be waiting for
1387
- * (`docs/strands.md` → "Waiting for the party's own machines"). Empty for a strand not tracked
1514
+ * (`docs/strands/writes.md` → "Waiting for the party's own machines"). Empty for a strand not tracked
1388
1515
  * or not running here, and on a launch that tracks no party machines.
1389
1516
  */
1390
1517
  unreachedPartyMachines(strandId: string): readonly PartyStrandPeer[] {
@@ -1427,22 +1554,31 @@ export class StrandInstanceManager {
1427
1554
  }
1428
1555
 
1429
1556
  /**
1430
- * Keep a launch `'syncing'` when its database could not be built because no seed peer has
1431
- * answered yet, and retry the database build every {@link UNREACHABLE_JOIN_RETRY_MS} on the
1432
- * runtime already up.
1557
+ * Keep a launch `'syncing'` when its database could not be built because no machine that can
1558
+ * answer for the strand's blocks was reachable, and retry the database build every
1559
+ * {@link UNREACHABLE_JOIN_RETRY_MS} on the runtime already up. Which launches reach here and
1560
+ * why waiting beats refusing: `docs/strands/lifecycle.md` → "A launch with nobody to answer
1561
+ * waits". What makes each of them unable to build:
1562
+ *
1563
+ * - **A joining storage replica whose seed is silent.** Optimystic (since 1.11.0) will not rule
1564
+ * a block never-created while any of a node's `bootstrapNodes` is unheard, so a joiner alone
1565
+ * with an unreachable seed cannot build even the schema catalog: `strandDb.initialize()` fails
1566
+ * `cohort-unreachable`.
1567
+ * - **A founder whose cohort is unreachable.** Its membership writes run inside `initialize()`
1568
+ * and fail the same way. Normally a founder has no seed (no sibling runs the strand yet) and
1569
+ * commits alone, so this is the founder given one.
1570
+ * - **A client** (`roles.strandCohortMember: false`) with no serving machine reachable. Its own
1571
+ * cohort is empty by construction, so every block its launch touches falls through to
1572
+ * `findCoordinator`, which resolves nobody at all: the schema catalog it opens first, and a
1573
+ * client founder's membership writes. A node that serves no storage never coordinates a key,
1574
+ * however isolated it is, so founding alone is not open to it either.
1433
1575
  *
1434
- * Optimystic (since 1.11.0) will not rule a block never-created while any of a node's
1435
- * `bootstrapNodes` is unheard, so a joiner alone with an unreachable seed cannot build even
1436
- * the schema catalog: `strandDb.initialize()` fails with `cohort-unreachable`. A founder
1437
- * given a seed is refused the same way (normally it has none: no sibling runs the strand yet). Refusing is
1438
- * right (building it alone would fork the catalog), but failing the launch would drop the
1439
- * strand until the watcher relaunched it, and `addStrand` would reject with a raw Optimystic
1440
- * error. Deferring gives a joiner the same contract the first-sync gate gives one that did
1576
+ * Deferring gives every one of them the contract the first-sync gate gives a joiner that did
1441
1577
  * build: the strand stays tracked, {@link whenWritable} waits and rejects with the retryable
1442
- * `StrandAwaitingFirstSyncError`, and the launch proceeds once a seed peer answers.
1578
+ * `StrandAwaitingFirstSyncError`, and the launch proceeds once a machine answers.
1443
1579
  *
1444
- * The libp2p node, its connections and the background loops stay up meanwhile. A seed peer
1445
- * can answer just after the schema read gave up on it — on a slow link it connects and its
1580
+ * The libp2p node, its connections and the background loops stay up meanwhile. A peer can
1581
+ * answer just after the schema read gave up on it — on a slow link it connects and its
1446
1582
  * peer-join backfill delivers the whole store — and the retry then builds the database, and
1447
1583
  * runs the first-sync probe, while that peer is still connected.
1448
1584
  */
@@ -1460,13 +1596,15 @@ export class StrandInstanceManager {
1460
1596
  * One retry scheduled by {@link deferUnreachableJoin}: the database phase again, on the
1461
1597
  * runtime still attached. Skipped when the strand was stopped or released since — a quiesce
1462
1598
  * releases it and the resume after rebuilds the whole runtime — or already has a database.
1463
- * A failure other than an unanswered seed releases the runtime and marks the strand
1464
- * `'error'`, as a failed resume does.
1599
+ * A failure other than an unreachable machine releases the runtime and marks the strand
1600
+ * `'error'`, as a failed resume does, unless it is a refusal of a claim's schema the replica
1601
+ * can fall back from ({@link buildJoinDatabaseOrReplica}).
1465
1602
  */
1466
1603
  private async retryUnreachableJoin(instance: StrandInstance): Promise<void> {
1467
1604
  const strandId = instance.strandId;
1468
1605
  const config = this.launchConfigs.get(strandId);
1469
- // Every strand node is built by `buildStrandRuntime`, as a node with its coordinated repo.
1606
+ // Every strand node is built by `buildStrandRuntime`, as a node carrying db-p2p's attachments
1607
+ // (a client's without a coordinated repo).
1470
1608
  const node = instance.libp2pNode as Libp2pNodeWithRepo | undefined;
1471
1609
  if (!config || !node || !this.isCurrentRuntime(instance, node) || instance.database
1472
1610
  || this.firstSyncGates.has(strandId) || this.isQuiescing(strandId)) {
@@ -1476,7 +1614,7 @@ export class StrandInstanceManager {
1476
1614
  try {
1477
1615
  // Tracked like any runtime build, so a wake, a quiesce or an sApp attach waits for it
1478
1616
  // rather than acting on a database that is still initializing.
1479
- build = await this.trackRuntimeBuild(strandId, this.buildStrandDatabase(instance, config, node));
1617
+ build = await this.trackRuntimeBuild(strandId, this.buildJoinDatabaseOrReplica(instance, config, node));
1480
1618
  } catch (error) {
1481
1619
  if (!this.isCurrentRuntime(instance, node)) {
1482
1620
  log('Strand %s: a database retry failed after its runtime was released: %o', strandId, error);
@@ -1487,14 +1625,48 @@ export class StrandInstanceManager {
1487
1625
  });
1488
1626
  instance.status = 'error';
1489
1627
  instance.error = describeThrown(error);
1490
- log('Strand %s: building the database of a joiner that was waiting for a seed peer failed: %s', strandId, instance.error);
1628
+ log('Strand %s: building the database of a launch that was waiting for a reachable machine failed: %s',
1629
+ strandId, instance.error);
1491
1630
  return;
1492
1631
  }
1493
- if (build === 'awaiting-seed' && this.isCurrentRuntime(instance, node) && !this.isQuiescing(strandId)) {
1632
+ if (build === 'awaiting-peer' && this.isCurrentRuntime(instance, node) && !this.isQuiescing(strandId)) {
1494
1633
  this.deferUnreachableJoin(instance);
1495
1634
  }
1496
1635
  }
1497
1636
 
1637
+ /**
1638
+ * A deferred join's database phase ({@link buildStrandDatabase}), run once more as the replica
1639
+ * when it fails on the schema of a claim that has not applied yet ({@link revertRefusedAttach}).
1640
+ * The failed attempt's database is closed first: a failure leaves it registered with its gate.
1641
+ * `'released'` when a stop began while it closed.
1642
+ */
1643
+ private async buildJoinDatabaseOrReplica(
1644
+ instance: StrandInstance,
1645
+ config: StartStrandConfig,
1646
+ node: Libp2pNodeWithRepo
1647
+ ): Promise<StrandDatabaseBuild> {
1648
+ try {
1649
+ return await this.buildStrandDatabase(instance, config, node);
1650
+ } catch (error) {
1651
+ const replicaConfig = this.isCurrentRuntime(instance, node)
1652
+ ? this.revertRefusedAttach(instance, config.sAppConfig, error)
1653
+ : undefined;
1654
+ if (!replicaConfig) {
1655
+ throw error;
1656
+ }
1657
+ const failedAttempt = this.firstSyncGates.get(instance.strandId);
1658
+ if (failedAttempt) {
1659
+ await this.discardDatabaseAttempt(instance.strandId, failedAttempt);
1660
+ }
1661
+ if (!this.isCurrentRuntime(instance, node) || instance.status === 'stopping') {
1662
+ // A stop that began while the failed attempt closed found no gate to release, so a
1663
+ // database built now would outlive the stop, open and unreleased.
1664
+ return 'released';
1665
+ }
1666
+ return await this.buildStrandDatabase(instance, replicaConfig, node);
1667
+ }
1668
+ }
1669
+
1498
1670
  /** Whether `instance` is still tracked, with `node` still its runtime's libp2p node. */
1499
1671
  private isCurrentRuntime(instance: StrandInstance, node: Libp2p): boolean {
1500
1672
  return !this.stopping && this.instances.get(instance.strandId) === instance && instance.libp2pNode === node;
@@ -1530,6 +1702,10 @@ export class StrandInstanceManager {
1530
1702
  }
1531
1703
  this.peerRedials.get(instance.strandId)?.stop();
1532
1704
  this.peerRedials.delete(instance.strandId);
1705
+ // The WebRTC upgrade service before the node it dials on: its stop() also aborts the attempt
1706
+ // in flight, so a hibernating strand holds no ICE negotiation open.
1707
+ this.webrtcUpgrades.get(instance.strandId)?.stop();
1708
+ this.webrtcUpgrades.delete(instance.strandId);
1533
1709
  // The party-machine tracker with the loop and gate that read it; a resume reads afresh.
1534
1710
  this.partyMachines.get(instance.strandId)?.stop();
1535
1711
  this.partyMachines.delete(instance.strandId);
@@ -2048,7 +2224,7 @@ export class StrandInstanceManager {
2048
2224
 
2049
2225
  instance.status = 'starting';
2050
2226
  try {
2051
- await this.trackRuntimeBuild(strandId, this.buildStrandRuntime(instance, resumeConfig));
2227
+ await this.trackRuntimeBuild(strandId, this.buildRuntimeOrReplica(instance, resumeConfig));
2052
2228
  timing('[resumeStrand:%s] total: %dms', strandId, Math.round(performance.now() - tTotal));
2053
2229
  log('Strand %s resumed successfully', strandId);
2054
2230
  return instance;
@@ -2060,6 +2236,66 @@ export class StrandInstanceManager {
2060
2236
  }
2061
2237
  }
2062
2238
 
2239
+ /**
2240
+ * {@link buildStrandRuntime}, run once more as the replica when it fails on the schema of a
2241
+ * claim that has not applied yet ({@link revertRefusedAttach}). Safe to run twice: a failed
2242
+ * build releases both handles before it rejects.
2243
+ */
2244
+ private async buildRuntimeOrReplica(instance: StrandInstance, config: StartStrandConfig): Promise<void> {
2245
+ try {
2246
+ await this.buildStrandRuntime(instance, config);
2247
+ } catch (error) {
2248
+ const replicaConfig = this.revertRefusedAttach(instance, config.sAppConfig, error);
2249
+ if (!replicaConfig) {
2250
+ throw error;
2251
+ }
2252
+ await this.buildStrandRuntime(instance, replicaConfig);
2253
+ }
2254
+ }
2255
+
2256
+ /**
2257
+ * Undo a claim of a storage replica ({@link attachSApp}) after an apply of its schema was refused
2258
+ * (`AppSchemaRefusedError`): the retained launch config drops the sApp, so later rebuilds run the
2259
+ * replica, and the instance gets back the replica's unset `sAppInfo` and its latency hint. Only
2260
+ * when `error` is such a refusal, `refused` is the claim the strand has not applied yet, and the
2261
+ * retained config still carries it, so a config rewritten since is left alone.
2262
+ *
2263
+ * @returns the replica's launch config, or `undefined` when nothing was undone.
2264
+ */
2265
+ private revertRefusedAttach(
2266
+ instance: StrandInstance,
2267
+ refused: SAppConfig | undefined,
2268
+ error: unknown
2269
+ ): StartStrandConfig | undefined {
2270
+ const strandId = instance.strandId;
2271
+ const unapplied = this.unappliedAttaches.get(strandId);
2272
+ const config = this.launchConfigs.get(strandId);
2273
+ const refusal = appSchemaRefusalOf(error);
2274
+ if (!refusal || !unapplied || !config || this.stopping || this.instances.get(strandId) !== instance
2275
+ || refused !== unapplied.sAppConfig || config.sAppConfig !== refused) {
2276
+ return undefined;
2277
+ }
2278
+ this.unappliedAttaches.delete(strandId);
2279
+ const { sAppConfig: _refused, ...replicaConfig } = config;
2280
+ this.launchConfigs.set(strandId, replicaConfig);
2281
+ instance.sAppInfo = undefined;
2282
+ instance.latencyHint = unapplied.latencyHint;
2283
+ log('Strand %s: the schema of sApp %s, which claimed this storage replica, was refused here; ' +
2284
+ 'the strand runs as a replica again: %s', strandId, refused.id, refusal.message);
2285
+ return replicaConfig;
2286
+ }
2287
+
2288
+ /**
2289
+ * Forget the unapplied claim of `strandId` once `database`, given the claim's sApp config as
2290
+ * `applied`, has applied its schema. An apply still deferred keeps it, since its retry can still be
2291
+ * refused by the strand's rows.
2292
+ */
2293
+ private forgetAppliedAttach(strandId: string, applied: SAppConfig | undefined, database: StrandDatabase): void {
2294
+ if (applied && this.unappliedAttaches.get(strandId)?.sAppConfig === applied && database.appSchemaState() === 'applied') {
2295
+ this.unappliedAttaches.delete(strandId);
2296
+ }
2297
+ }
2298
+
2063
2299
  /**
2064
2300
  * Honor a founder request against an ALREADY-TRACKED strand — the seam that
2065
2301
  * closes the "whoever launches first decides whether the bootstrap runs" gap:
@@ -2132,19 +2368,24 @@ export class StrandInstanceManager {
2132
2368
  *
2133
2369
  * A runtime build in flight (the replica's launch, or a hibernation wake) is waited out
2134
2370
  * first, so the attach acts on the database that build produced. Then, in order: the
2135
- * schema signature is checked before anything changes; the retained launch config takes
2136
- * the sApp, so every later rebuild applies it through `composeStrand`; the live database —
2137
- * published, or still held by the first-sync gate — gets the schema; and only then does
2138
- * the instance record `sAppInfo` and the sApp's latency hint. An instance with no live
2139
- * database gets the config alone: a quiesced one applies the schema at its next resume, a
2140
- * launch waiting for a seed peer at its next database retry.
2371
+ * schema signature, and the refusals the schema's text alone decides (`checkAppSchema`: a
2372
+ * `seed` item, an item the parser skipped, a syntax error), are checked before anything
2373
+ * changes; the retained launch config takes the sApp, so every later rebuild applies it
2374
+ * through `composeStrand`; the live database — published, or still held by the first-sync
2375
+ * gate — gets the schema; and only then does the instance record `sAppInfo` and the sApp's
2376
+ * latency hint. An instance with no live database gets the config alone: a quiesced one
2377
+ * applies the schema at its next resume, a launch waiting for a seed peer at its next
2378
+ * database retry, and that build falls back to the replica if the strand's tables and rows
2379
+ * refuse the schema ({@link revertRefusedAttach}).
2141
2380
  *
2142
2381
  * @returns `'already-attached'` when the instance already runs an sApp — a DIFFERENT one
2143
2382
  * is logged and left as it is, as a second claim of a claimed strand always has been —
2144
2383
  * else `'attached'`.
2145
2384
  * @throws when the strand is not tracked (a caller bug, or a launch that failed while
2146
- * this waited on it); when the schema signature is refused, having changed nothing; and
2147
- * whatever the live apply throws (e.g. a quiesce closed the database mid-apply) — the
2385
+ * this waited on it); when the schema signature or the schema's text is refused, having
2386
+ * changed nothing; `AppSchemaRefusedError` when the live apply refuses the schema against
2387
+ * the replica's tables and rows, having put the retained config back to the replica's; and
2388
+ * whatever else the live apply throws (e.g. a quiesce closed the database mid-apply) — the
2148
2389
  * retained config then still carries the sApp and `sAppInfo` stays unset, so the next
2149
2390
  * claim retries the apply.
2150
2391
  *
@@ -2159,26 +2400,34 @@ export class StrandInstanceManager {
2159
2400
  options: { requireSignedSchemas?: boolean } = {}
2160
2401
  ): Promise<'attached' | 'already-attached'> {
2161
2402
  await this.settleRuntimeBuilds(strandId);
2162
- const instance = this.instances.get(strandId);
2163
- const config = this.launchConfigs.get(strandId);
2164
- if (!instance || !config) {
2165
- throw new Error(`Cannot attach an sApp to strand ${strandId}: not tracked`);
2166
- }
2167
- if (instance.sAppInfo) {
2168
- if (instance.sAppInfo.id !== sAppConfig.id) {
2169
- log('attachSApp: strand %s already runs sApp %s — the claim for sApp %s is ignored',
2170
- strandId, instance.sAppInfo.id, sAppConfig.id);
2171
- }
2403
+ if (this.claimTarget(strandId, sAppConfig) === 'already-attached') {
2172
2404
  return 'already-attached';
2173
2405
  }
2174
2406
  const sAppInfo = verifiedSAppInfo(strandId, sAppConfig, options.requireSignedSchemas);
2407
+ await checkAppSchema(sAppConfig);
2408
+ // The check yielded, so a wake or another claim may have started meanwhile: wait out its build
2409
+ // and read the instance and config again, or the config written below would drop what a
2410
+ // resume just retained (its fresh `bootstrapNodes`).
2411
+ await this.settleRuntimeBuilds(strandId);
2412
+ const target = this.claimTarget(strandId, sAppConfig);
2413
+ if (target === 'already-attached') {
2414
+ return target;
2415
+ }
2416
+ const { instance, config } = target;
2175
2417
  // A fresh object rather than mutating in place: startStrand retains the CALLER'S
2176
2418
  // config object, which is not ours to rewrite.
2177
2419
  this.launchConfigs.set(strandId, { ...config, sAppConfig });
2420
+ this.unappliedAttaches.set(strandId, { sAppConfig, latencyHint: instance.latencyHint });
2178
2421
  const database = instance.database ?? this.firstSyncGates.get(strandId)?.database;
2179
2422
  if (database) {
2180
- await database.attachAppSchema(sAppConfig);
2423
+ await this.applyClaimedSchema(instance, database, sAppConfig);
2181
2424
  } else {
2425
+ // NOTE: accepted gap — this claim resolves `'attached'` before any apply, so the app learns of
2426
+ // a refusal by the strand's rows only from the log and from `sAppInfo` going back to unset when
2427
+ // the build falls back to the replica; `CadreNode.sAppConfigs` keeps the claim, so a restart's
2428
+ // launch with it is refused and suppressed (`suppressIfAppSchemaRefused`). Failing the claim
2429
+ // instead would mean waking a quiesced replica to apply now, and would still not cover a
2430
+ // launch waiting for a seed peer.
2182
2431
  log('attachSApp: strand %s has no live database — its next build applies the sApp schema', strandId);
2183
2432
  }
2184
2433
  instance.sAppInfo = sAppInfo;
@@ -2192,11 +2441,54 @@ export class StrandInstanceManager {
2192
2441
  return 'attached';
2193
2442
  }
2194
2443
 
2444
+ /**
2445
+ * The tracked instance and retained config an {@link attachSApp} claim acts on, or
2446
+ * `'already-attached'` when the instance already runs an sApp (a claim for a different one is
2447
+ * logged and ignored).
2448
+ *
2449
+ * @throws when the strand is not tracked.
2450
+ */
2451
+ private claimTarget(
2452
+ strandId: string,
2453
+ sAppConfig: SAppConfig
2454
+ ): { instance: StrandInstance; config: StartStrandConfig } | 'already-attached' {
2455
+ const instance = this.instances.get(strandId);
2456
+ const config = this.launchConfigs.get(strandId);
2457
+ if (!instance || !config) {
2458
+ throw new Error(`Cannot attach an sApp to strand ${strandId}: not tracked`);
2459
+ }
2460
+ if (!instance.sAppInfo) {
2461
+ return { instance, config };
2462
+ }
2463
+ if (instance.sAppInfo.id !== sAppConfig.id) {
2464
+ log('attachSApp: strand %s already runs sApp %s — the claim for sApp %s is ignored',
2465
+ strandId, instance.sAppInfo.id, sAppConfig.id);
2466
+ }
2467
+ return 'already-attached';
2468
+ }
2469
+
2470
+ /**
2471
+ * Apply a claim's schema to the replica's live database. A refusal by the replica's tables and
2472
+ * rows puts the retained config back to the replica's ({@link revertRefusedAttach}): the replica
2473
+ * holds no `App` schema, so the refused apply left nothing to drop. Any other failure leaves the
2474
+ * claim retained and unapplied, for the next claim or build to retry.
2475
+ */
2476
+ private async applyClaimedSchema(instance: StrandInstance, database: StrandDatabase, sAppConfig: SAppConfig): Promise<void> {
2477
+ try {
2478
+ await database.attachAppSchema(sAppConfig);
2479
+ } catch (error) {
2480
+ this.revertRefusedAttach(instance, sAppConfig, error);
2481
+ throw error;
2482
+ }
2483
+ this.forgetAppliedAttach(instance.strandId, sAppConfig, database);
2484
+ }
2485
+
2195
2486
  /**
2196
2487
  * Whether `strandId` is launched but still waiting for its first sync — a joiner whose
2197
2488
  * runtime is up while its database is withheld (status `'syncing'`, or `'idle'` after
2198
2489
  * the hibernation manager's idle timer fired on it), including one whose database build
2199
- * waits for a seed peer to answer ({@link deferUnreachableJoin}). `false` for a writable,
2490
+ * waits for a machine that can answer for the strand to be reachable
2491
+ * ({@link deferUnreachableJoin}). `false` for a writable,
2200
2492
  * quiesced, or untracked strand. The predicate {@link whenWritable}'s callers gate on.
2201
2493
  */
2202
2494
  isAwaitingFirstSync(strandId: string): boolean {
@@ -2299,7 +2591,9 @@ export class StrandInstanceManager {
2299
2591
  // (see the build's end in `buildStrandRuntime`).
2300
2592
  instance.lastActivity = new Date();
2301
2593
  instance.status = 'active';
2302
- log('Strand %s is now writable: Strand.Header held', strandId);
2594
+ // No reason given here: the gate logs what its probe found when it opens, and a database
2595
+ // published by a deferred build held no Header at all — it had nobody to read one from.
2596
+ log('Strand %s is now writable', strandId);
2303
2597
  }
2304
2598
  const waiters = this.writableWaiters.get(strandId);
2305
2599
  if (waiters) {
@@ -2466,6 +2760,8 @@ export class StrandInstanceManager {
2466
2760
 
2467
2761
  log('Stopping strand instance: %s', strandId);
2468
2762
  instance.status = 'stopping';
2763
+ // Before the release awaits, so a build failing meanwhile does not rebuild as the replica.
2764
+ this.unappliedAttaches.delete(strandId);
2469
2765
  this.rejectWritableWaiters(strandId, 'was stopped');
2470
2766
 
2471
2767
  try {