@serfab/cadre-core 1.19.0 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/dist/cadre-node.d.ts +118 -16
  2. package/dist/cadre-node.js +210 -31
  3. package/dist/cadre-node.js.map +1 -1
  4. package/dist/control-database.d.ts +2 -1
  5. package/dist/control-database.js +128 -126
  6. package/dist/control-database.js.map +1 -1
  7. package/dist/control-protocol-guard.js +3 -2
  8. package/dist/control-protocol-guard.js.map +1 -1
  9. package/dist/control-read-retry.d.ts +19 -16
  10. package/dist/control-read-retry.js +22 -54
  11. package/dist/control-read-retry.js.map +1 -1
  12. package/dist/control-retry.d.ts +50 -6
  13. package/dist/control-retry.js +53 -6
  14. package/dist/control-retry.js.map +1 -1
  15. package/dist/control-stream.js +2 -1
  16. package/dist/control-stream.js.map +1 -1
  17. package/dist/control-write-retry.d.ts +24 -16
  18. package/dist/control-write-retry.js +58 -30
  19. package/dist/control-write-retry.js.map +1 -1
  20. package/dist/describe-thrown.d.ts +12 -0
  21. package/dist/describe-thrown.js +59 -0
  22. package/dist/describe-thrown.js.map +1 -0
  23. package/dist/edge-node/config.d.ts +8 -2
  24. package/dist/edge-node/config.js +5 -1
  25. package/dist/edge-node/config.js.map +1 -1
  26. package/dist/edge-node/dissolve.d.ts +1 -1
  27. package/dist/edge-node/dissolve.js +1 -1
  28. package/dist/edge-node/dissolve.js.map +1 -1
  29. package/dist/edge-node/edge-join.js +4 -1
  30. package/dist/edge-node/edge-join.js.map +1 -1
  31. package/dist/edge-node/edge-node.d.ts +10 -0
  32. package/dist/edge-node/edge-node.js +54 -9
  33. package/dist/edge-node/edge-node.js.map +1 -1
  34. package/dist/edge-node/options.d.ts +11 -2
  35. package/dist/edge-node/options.js +11 -4
  36. package/dist/edge-node/options.js.map +1 -1
  37. package/dist/edge-node/platform.d.ts +15 -3
  38. package/dist/edge-node/strand-move.d.ts +0 -2
  39. package/dist/edge-node/strand-move.js +1 -4
  40. package/dist/edge-node/strand-move.js.map +1 -1
  41. package/dist/edge-node/strands.js +5 -3
  42. package/dist/edge-node/strands.js.map +1 -1
  43. package/dist/enrollment.js +2 -1
  44. package/dist/enrollment.js.map +1 -1
  45. package/dist/index.d.ts +6 -2
  46. package/dist/index.js +9 -1
  47. package/dist/index.js.map +1 -1
  48. package/dist/member-redemption.js +3 -9
  49. package/dist/member-redemption.js.map +1 -1
  50. package/dist/node-local-snapshot.js +2 -1
  51. package/dist/node-local-snapshot.js.map +1 -1
  52. package/dist/peer-dial.js +3 -2
  53. package/dist/peer-dial.js.map +1 -1
  54. package/dist/pending-join-runner.d.ts +29 -2
  55. package/dist/pending-join-runner.js +60 -20
  56. package/dist/pending-join-runner.js.map +1 -1
  57. package/dist/push-notifier-apns.js +8 -7
  58. package/dist/push-notifier-apns.js.map +1 -1
  59. package/dist/push-notifier-fcm.js +6 -5
  60. package/dist/push-notifier-fcm.js.map +1 -1
  61. package/dist/push-notifier-shared.d.ts +0 -2
  62. package/dist/push-notifier-shared.js +4 -4
  63. package/dist/push-notifier-shared.js.map +1 -1
  64. package/dist/relay-reservation.js +4 -3
  65. package/dist/relay-reservation.js.map +1 -1
  66. package/dist/strand-addr-protocol.js +2 -1
  67. package/dist/strand-addr-protocol.js.map +1 -1
  68. package/dist/strand-app-schema-report.d.ts +53 -0
  69. package/dist/strand-app-schema-report.js +77 -0
  70. package/dist/strand-app-schema-report.js.map +1 -0
  71. package/dist/strand-database.d.ts +60 -0
  72. package/dist/strand-database.js +93 -0
  73. package/dist/strand-database.js.map +1 -1
  74. package/dist/strand-first-sync-gate.js +4 -3
  75. package/dist/strand-first-sync-gate.js.map +1 -1
  76. package/dist/strand-formation-protocol.js +4 -3
  77. package/dist/strand-formation-protocol.js.map +1 -1
  78. package/dist/strand-instance-manager.d.ts +73 -2
  79. package/dist/strand-instance-manager.js +112 -9
  80. package/dist/strand-instance-manager.js.map +1 -1
  81. package/dist/strand-membership-reconciler.d.ts +13 -1
  82. package/dist/strand-membership-reconciler.js +25 -16
  83. package/dist/strand-membership-reconciler.js.map +1 -1
  84. package/dist/strand-membership-writer.d.ts +16 -2
  85. package/dist/strand-membership-writer.js +54 -8
  86. package/dist/strand-membership-writer.js.map +1 -1
  87. package/dist/strand-move.js +4 -6
  88. package/dist/strand-move.js.map +1 -1
  89. package/dist/strand-offline.d.ts +102 -0
  90. package/dist/strand-offline.js +97 -0
  91. package/dist/strand-offline.js.map +1 -0
  92. package/dist/types.d.ts +37 -0
  93. package/dist/types.js.map +1 -1
  94. package/package.json +8 -8
  95. package/src/cadre-node.ts +230 -31
  96. package/src/control-database.ts +5594 -5592
  97. package/src/control-protocol-guard.ts +3 -2
  98. package/src/control-read-retry.ts +22 -58
  99. package/src/control-retry.ts +54 -6
  100. package/src/control-stream.ts +2 -1
  101. package/src/control-write-retry.ts +58 -30
  102. package/src/describe-thrown.ts +60 -0
  103. package/src/edge-node/config.ts +11 -2
  104. package/src/edge-node/dissolve.ts +2 -1
  105. package/src/edge-node/edge-join.ts +2 -1
  106. package/src/edge-node/edge-node.ts +57 -7
  107. package/src/edge-node/options.ts +20 -4
  108. package/src/edge-node/platform.ts +15 -3
  109. package/src/edge-node/strand-move.ts +1 -5
  110. package/src/edge-node/strands.ts +74 -72
  111. package/src/enrollment.ts +2 -1
  112. package/src/index.ts +27 -1
  113. package/src/member-redemption.ts +3 -9
  114. package/src/node-local-snapshot.ts +2 -1
  115. package/src/peer-dial.ts +605 -604
  116. package/src/pending-join-runner.ts +68 -22
  117. package/src/push-notifier-apns.ts +8 -7
  118. package/src/push-notifier-fcm.ts +6 -5
  119. package/src/push-notifier-shared.ts +5 -5
  120. package/src/relay-reservation.ts +1212 -1211
  121. package/src/strand-addr-protocol.ts +2 -1
  122. package/src/strand-app-schema-report.ts +115 -0
  123. package/src/strand-database.ts +123 -1
  124. package/src/strand-first-sync-gate.ts +600 -599
  125. package/src/strand-formation-protocol.ts +4 -3
  126. package/src/strand-instance-manager.ts +137 -10
  127. package/src/strand-membership-reconciler.ts +942 -928
  128. package/src/strand-membership-writer.ts +61 -14
  129. package/src/strand-move.ts +594 -597
  130. package/src/strand-offline.ts +178 -0
  131. package/src/types.ts +36 -0
@@ -1,599 +1,600 @@
1
- /**
2
- * The first-sync write gate for a JOINING machine.
3
- *
4
- * A machine that has never received anything from another member of a strand must not
5
- * commit to it. With no strand peer connected, Optimystic's cohort for every block is the
6
- * machine itself, so the first write to a table finds no collection locally and INVENTS
7
- * one — exactly what a founder writing alone legitimately does. When the connection comes
8
- * up, two independently created histories share one collection id: Optimystic keeps one and
9
- * drops the other's commits, or never reconciles them at all. The joiner's own rows silently
10
- * vanish (`joining-machine-writes-before-first-sync-fork-tables`). Optimystic cannot tell a
11
- * founder from a joiner; sereus can, because the launch knows whether it is founding.
12
- *
13
- * The invariant this module enforces: **a machine that has never held this strand's
14
- * `Strand.Header` row, and has not read every `Strand` and `App` table once, must not commit
15
- * to it.** The founder writes the Header in its bootstrap; every other machine can only receive
16
- * it from a peer, so "no local Header" means "never synced". The gate therefore holds the
17
- * freshly initialized `StrandDatabase` back from the app — `StrandInstance.database` stays
18
- * unset and the instance reports `'syncing'` — and probes, whenever data lands in the strand's
19
- * store and on a backstop timer, until the Header is readable AND a read of each other table
20
- * settles, at which point the database is published and the instance goes `'active'`. A
21
- * machine whose store already holds the Header and every other table (a founder, and normally
22
- * a restart or a hibernation resume) passes the probe on the first try and is never gated, so
23
- * offline-first writes on a machine that has synced before keep working.
24
- *
25
- * "Has synced before" is decided by what the local store actually holds, not by whether this
26
- * machine once read the strand: a machine that left soon after its first sync can hold less
27
- * than it read, and is then gated like a joiner. The re-attach measurement on
28
- * {@link DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS} saw exactly that — a machine back over the store
29
- * it kept, without the `Strand.Header` collection it had read before it left. Gating it is
30
- * right: writing into a collection this machine does not hold would fork it.
31
- *
32
- * Why the other tables too: the Header is ONE collection. It reaches a joiner ahead of the
33
- * founder's other collections (peer-join backfill and pull-on-read deliver those separately),
34
- * and a write to a table whose collection this machine has not yet fetched invents one exactly
35
- * as a lone joiner did. Measured on the reference chat schema (2026-09-16, direct connections,
36
- * Header-only probe): the joiner's participant + message written the instant `addStrand`
37
- * resolved diverged in 3 of 4 runs. The same holds for the `Strand` tables, which reach a joiner
38
- * by the same backfill: the membership loop writes `ConsumedInvite`, `Member` and `MemberPeer`
39
- * about a second after publication, and a manager writes `Invite`, `CancelledInvite`, `Manager`
40
- * and `Revocation`. Reading each table once pulls its collection while the founder is
41
- * reachable, so the write that follows appends.
42
- *
43
- * Every probe read is `select 1 from <table> limit 1` (`Strand.Header`, then each other `Strand`
44
- * table, then each `App` table, skipping those already seen settled): opening the table fetches
45
- * its collection header, and one row walks the root to the first leaf. Reads never commit a
46
- * collection (one ruled authoritatively absent is staged empty in memory only, and an
47
- * unreachable one throws), so probing is safe to repeat and a throw is just "not yet". Every
48
- * table declared at founding has a collection from the start (the founder bootstrap commits the
49
- * rest empty before its founding transaction writes the Header and the membership rows), so a
50
- * probe read fetches it; a table a later schema version adds reads as absent until its first
51
- * write creates the collection — see `docs/strands.md` ("Joining") for that residual.
52
- *
53
- * Owned by `StrandInstanceManager`: created in `buildStrandDatabase` for every database build, armed
54
- * only for a non-founder launch whose first probe fails, stopped and dropped in
55
- * `releaseRuntime` (so a quiesce → resume rebuild re-probes over the same store), and opened
56
- * by `publishDatabase` whenever the database is published without its loop — a launch that
57
- * needed no gate, or a founder request that ran the bootstrap against the still-gated
58
- * database (`foundExistingStrand`).
59
- *
60
- * NOTE: the gate covers app and membership tables, not the schema catalog. A launch with no
61
- * seed writes the catalog collection (`optimystic/schema` plus two hash-named blocks,
62
- * measured 2026-09-16) alone, during `connectToStrand`'s schema apply, before any peer
63
- * contact. (One with a seed cannot until a seed peer answers — Optimystic refuses the
64
- * absence ruling — and retries its database build on a timer, `StrandInstanceManager.deferUnreachableJoin`.) That is the same "two histories under one id" shape this gate
65
- * exists to prevent, and it is only safe because both sides derive byte-identical content
66
- * from the same schema text. If the catalog ever carries per-machine or ordering-dependent
67
- * content (optimystic's own `0.5-same-named-tables-in-two-schemas-share-storage` re-keys
68
- * it), a joiner's catalog will fork against the founder's — gate the schema apply on the
69
- * Header too, or have optimystic open the catalog read-only when a peer already holds it.
70
- */
71
-
72
- import debug from 'debug';
73
- import type { Database } from '@quereus/quereus';
74
- import type { StrandDatabase } from './strand-database.js';
75
- import { scheduleRuns, TABLE_CHANGE_COALESCE_MS, type TableChangeWatch } from './table-change-watch.js';
76
- import { defaultTimeoutScheduler, type TimeoutScheduler } from './timeout-scheduler.js';
77
-
78
- const log = debug('sereus:cadre:strand-first-sync');
79
-
80
- /**
81
- * How long a gated launch goes without probing when no data lands in the strand's store: the
82
- * gate probes when data arrives, and this long after its last probe settled when none has. It
83
- * covers a probe that failed for a reason no storage event follows — a consult that missed its
84
- * deadline while the founder held the block, or a push that never comes.
85
- *
86
- * Why 2 s: arrivals wake the gate, so this timer is the fallback rather than the main path. At
87
- * the supported 3 s link round trip one consult takes about 6 s (two round trips, per the 1.8.0
88
- * measurements on {@link DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS}), so a 2 s idle gap after a failed
89
- * probe adds at most a third of one probe round, and it is under 1% of that 360 s budget. Shorter
90
- * brings back the cost of polling (the gate re-probed every 500 ms before it woke on arrivals);
91
- * much longer (5 s) delays the case with no storage event by most of a probe round for nothing.
92
- */
93
- export const DEFAULT_STRAND_FIRST_SYNC_BACKSTOP_MS = 2_000;
94
-
95
- /**
96
- * How long `CadreNode.addStrand` waits for a machine's first sync before rejecting with
97
- * {@link StrandAwaitingFirstSyncError}. It has to cover the slowest attach sereus carries,
98
- * which is not a first join: a machine RE-attaching through a relay on a slow link can take
99
- * longer than one joining for the first time.
100
- *
101
- * Measured over a DIRECT connection (2026-09-16): the joiner reads the founder's rows about
102
- * 1.3 s after `addStrand` would previously have resolved. That is the fast case, and it is not
103
- * what this budget has to cover.
104
- *
105
- * Every harness figure below was taken on one shape: one Windows developer machine, two
106
- * relay-only `CadreNode`s (`listenAddrs: []`) on a shared loopback dedicated relay, with a
107
- * one-way per-frame outbound delay applied to every websocket by
108
- * `integration-tests/src/harness/ws-latency.ts` in `pipelined` mode — frames stay overlapped
109
- * in flight, so the figure is latency and bandwidth stays unlimited; the harness's other mode
110
- * (`serial`) is a per-socket frame-rate cap and its delays are NOT comparable
111
- * (`docs/testing.md` → "Link latency"). Two delays were used: 900 ms one-way, a round trip
112
- * near 1.8 s, the band sereus supported first; and 1 500 ms one-way, the supported 3-second
113
- * round trip. Times run from the `addStrand` call to writable.
114
- *
115
- * FRESH JOIN at 900 ms (2026-09-26), a machine holding nothing of the strand yet: 23, 27, 31
116
- * and 41 s over four runs at optimystic's 1000 ms cohort read deadline, and 35, 42 and 46 s
117
- * over three runs at a 5000 ms one; the re-attach scenario below later took 38.7, 38.7 and
118
- * 56.9 s for the same fresh join. At that delay the 5000 ms band, 35-57 s, was the one in
119
- * force: sereus then declared 5000 ms, because 1000 ms is shorter than one round trip on
120
- * that link and leaves every cohort read with no answer to corroborate against. Widening that
121
- * deadline makes a consult against a peer that cannot answer cost longer, and this phase runs
122
- * several of those — which is why both bands are recorded here, and why a change to either
123
- * number has to be weighed against the other.
124
- *
125
- * AT THE SUPPORTED LINK ON `@optimystic/*` 1.17.0 (2026-10-21), 1 500 ms one-way, the same
126
- * scenario, one run per arm, with the probe reading every `Strand` table as well as the `App`
127
- * one (`debt-first-sync-gate-reads-every-strand-table`); the kept-store arm was not run:
128
- * - Fresh join: writable at 28.7 s and NOT gated, as on 1.15.0.
129
- * - Re-attach over an EMPTY store: writable at 105.8 and 105.9 s over two runs, the row A wrote
130
- * while B was away readable at the same moment. B's first database build fails at 7.0 s (no
131
- * seed peer has answered; `StrandInstanceManager.deferUnreachableJoin` retries it), B's strand
132
- * node connects to A's at 15.1 s, the retried build's `connectToStrand` takes 21.2 s, and the
133
- * launch's first probe then takes 72.6 s and passes with no read failing, so the gate never
134
- * arms.
135
- * - The same arm with the probe held to the Header and the `App` table (one run, otherwise the
136
- * same build): that probe took 12.1 s, writable at 45.4 s, the row at 63.5 s. So the seven
137
- * `Strand` reads cost about 60 s here, about 8.6 s each, against about 6 s for each of the
138
- * baseline's two reads — more than the 42 s estimated from one 6 s consult per read.
139
- *
140
- * AT THE SUPPORTED LINK ON `@optimystic/*` 1.15.0 (2026-10-20), 1 500 ms one-way, the same
141
- * scenario, one fresh-join run, with the one-row probes woken by data landing in the store
142
- * (`first-sync-gate-probes-cheaply`; the full-count probes polled every 500 ms gave the same
143
- * figures):
144
- * - Fresh join: writable at 28.8 s, and NOT gated. The launch waits 27.3 s in
145
- * `connectToStrand` for its seed peer (it hydrates the founder's catalog, 9 tables), and by
146
- * then the store holds the strand: the first probe passed in 24 ms.
147
- * - The strand case of `message-cost-accounting` (two relay-only parties on loopback) agrees:
148
- * B's `addStrand` took 471 ms, with 13 `sync` streams to A, 4 block reads from the Header
149
- * probe and 8 from the table probes. Its two tables are empty, so a full count would fetch
150
- * the same blocks as a one-row read.
151
- * - Neither arms the gate, so neither times the woken path. That was checked on
152
- * `harness-topology`'s cross-party share (a joiner launched with no seed, dialed afterwards)
153
- * with the backstop raised to 10 s: the founder's join backfill push opened the gate 2.1 s
154
- * after it armed.
155
- *
156
- * AT THE SUPPORTED LINK ON `@optimystic/*` 1.8.0 (2026-09-29), 1 500 ms one-way, the read
157
- * deadline derived from the declared link at 7 000 ms (`cohortReadDeadlineMs` in
158
- * `link-budget.ts`; the plugin's `COHORT_READ_DEADLINE_MS` is the same number), and cadre
159
- * stating its declared link to Optimystic, the same scenario, all under the coordinator debug
160
- * channel:
161
- * - Fresh join: writable at 63.9 and 63.8 s over two runs, the row A wrote before the join
162
- * readable at 88.0 s in both. B's strand node connected to A's at 18.3-18.4 s. No read was
163
- * declined: every consult on B completed, 6.03-6.05 s after the one before it (two link
164
- * round trips each). The time did not fall, because B's consults ran one after another and
165
- * the gate opened only after the seventh.
166
- * - Re-attach over the store B kept: no longer bimodal. All 3 runs held everything and came
167
- * up writable at launch (9.2 s), and the row A wrote while B was away was readable at
168
- * 35.6 s in each, read with one consult for the collection and its data block together. No
169
- * read was declined during the attach. The empty-store arm was not re-run.
170
- *
171
- * AT THE SUPPORTED LINK ON `@optimystic/*` 1.7.0 (2026-09-29), same delay, deadline and
172
- * scenario, before cadre stated its link to Optimystic:
173
- * - Fresh join: writable at 52.1 and 82.1 s over two runs, and 63.6 s in a third run under
174
- * the coordinator debug channel; a fourth run with the deadline set back to 5 000 ms took
175
- * 70.2 s. B's strand node connected to A's at 18.2-18.3 s in every run at this delay. The
176
- * row A wrote before the join was readable at 67-124 s.
177
- * - Re-attach over the store B kept: bimodal again. 1 of 3 runs held everything and came up
178
- * writable at launch (9.1 s; the row at 33.4 s). The other 2 were gated and writable at
179
- * 75.7 and 78.7 s (the row at 120.8 and 175.0 s). The empty-store arm was not re-run; at
180
- * 900 ms it matched a fresh join.
181
- * - What that band was NOT: a measure of the 7 000 ms deadline. Every cohort consult in those
182
- * runs ended 3.00-3.02 s after the one before it, at 5 000 and 7 000 alike, because
183
- * Optimystic's then-fixed 3 000 ms request dial deadline also bounded the protocol
184
- * negotiation on an already-open connection, and one negotiation is one link round trip —
185
- * 3 s here. So it was the band of a join whose every consult failed and whose blocks
186
- * arrived by peer-join backfill.
187
- *
188
- * RE-ATTACH at 900 ms (2026-09-26, the opt-in
189
- * `integration-tests/src/scenarios/strand-reattach-first-sync-measure.integration.ts` — re-run
190
- * it before changing this number): B attached once on an undelayed link, left with
191
- * `stopStrand`, A wrote while it was away, the delay was raised, and B called `addStrand`
192
- * again.
193
- * - Over an EMPTY store (one minted per launch, cadre's default with no storage provider):
194
- * gated in all four runs and writable at 38.7-56.8 s, the same as a fresh join.
195
- * - Over the store it KEPT (a phone with durable storage), bimodal. In 3 of 8 runs the store
196
- * held everything and the launch came up writable (5.6 s, the launch itself). In the other
197
- * 5 it lacked the `Strand.Header` collection B had read on its first attach, so B was gated
198
- * like a joiner and became writable at 64.1-78.7 s — the slowest attach measured, about
199
- * twice a fresh join. Why syncing over a partial store is slower sits inside optimystic
200
- * (`tickets/blocked/report-reattach-over-partial-replica-to-optimystic`).
201
- * - Neither a redial nor catching up on missed writes explains the time: B's strand node
202
- * connected to A's at 11 s in every arm, fresh join included, and a run with 20 missed
203
- * writes fell inside the run-to-run spread of those with 1.
204
- * This budget covers WRITABLE, not caught up: in the gated kept-store runs the row A wrote
205
- * while B was away became readable only at 140-162 s (121-175 s at the supported link).
206
- *
207
- * Two samples from outside this harness, neither reproduced here and neither discarded: a
208
- * reporter's re-attach of the same shape (optimystic #22; their harness, storage and delay
209
- * injector are unknown to us) opened the gate at about 150 s, after the previous 120 s budget
210
- * had already rejected; and a real Galaxy S7 joining fresh through relay.sereus.org took 178 s.
211
- *
212
- * 360 s clears the worst harness sample (105.9 s, a re-attach over an empty store at the
213
- * supported link on 1.17.0) by about 3.4x, the reporter's re-attach by 2.4x and the device join
214
- * by about 2x. Set by the rule every re-measure applies: keep it while the worst harness sample
215
- * is at most 100 s, which holds a margin of at least 3x; otherwise raise it to 3x the worst
216
- * sample, rounded up to the next whole minute. The 1.17.0 sample crossed 100 s, and 3x 105.9 s
217
- * is 318 s, so 360 s (2026-10-21); the 1.7.0 and 1.8.0 re-measures (worst 82 s and 64 s) had
218
- * kept the 300 s before it. 240 s was rejected earlier: it clears the device join by only 1.35x,
219
- * and that sample was not a re-attach. History: the original 30 s sat INSIDE the 1000 ms fresh
220
- * band and refused about half of those joins while their sync was progressing normally; 120 s
221
- * was sized from fresh joins only and refused the reporter's re-attach.
222
- *
223
- * NOTE: accepted tradeoff — what 360 s costs. This wait is what an app's `addStrand` sits in
224
- * before it is told "not yet", so a strand none of whose members is reachable at all takes six
225
- * minutes to report instead of two. The slow report was weighed against refusing attaches that
226
- * were working, and the refusal is the worse failure. The cost is bounded — the rejection is
227
- * retryable, the strand stays launched and keeps probing, and `strand:writable` fires the
228
- * moment the sync lands, so an app that listens for the event rather than awaiting the call is
229
- * unaffected either way. Revisit if the gate ever learns whether ANY other member is connected:
230
- * "no peer at all" could then be reported at once and this budget would only ever be spent on a
231
- * sync that is actually in progress — worth more the longer this budget gets.
232
- */
233
- // eslint-disable-next-line no-restricted-syntax -- measured, not derived: the bands above, from integration-tests' strand-reattach-first-sync-measure.integration.ts; a whole first sync has no round-trip count
234
- export const DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS = 360_000;
235
-
236
- /** Embedder-facing tuning for the gate, threaded from `CadreNodeConfig.strandFirstSync`. */
237
- export interface StrandFirstSyncConfig {
238
- /**
239
- * Default wait for `CadreNode.addStrand` (and `whenStrandWritable`) before a machine whose
240
- * first sync has not completed is reported as not yet writable. Default
241
- * {@link DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS}.
242
- */
243
- timeoutMs?: number;
244
- /**
245
- * While gated, probe this long after the last probe settled when no data has landed in the
246
- * strand's store. Default {@link DEFAULT_STRAND_FIRST_SYNC_BACKSTOP_MS}.
247
- */
248
- backstopMs?: number;
249
- }
250
-
251
- /**
252
- * Thrown by `CadreNode.addStrand` / `whenStrandWritable` when a machine has not received the
253
- * strand's data from another member within the wait budget — because no other member is
254
- * reachable, or because one is and the sync is still arriving over a slow link; the gate
255
- * cannot tell the two apart. RETRYABLE: the strand stays launched and keeps probing, so a
256
- * later `addStrand` (or `whenStrandWritable`) for the same strand completes the attach once
257
- * the data has arrived; the `strand:writable` event fires at that moment too.
258
- */
259
- export class StrandAwaitingFirstSyncError extends Error {
260
- readonly strandId: string;
261
- readonly waitedMs: number;
262
-
263
- constructor(strandId: string, waitedMs: number) {
264
- super(
265
- `Strand ${strandId} is not writable yet: this machine has not yet received the strand's data ` +
266
- `from another member (waited ${waitedMs} ms). Either no other member is reachable, or the ` +
267
- 'link to one is slow and the sync is still in progress. The strand stays launched and keeps ' +
268
- 'trying — call addStrand or whenStrandWritable(strandId) again to keep waiting, or listen ' +
269
- "for the 'strand:writable' event."
270
- );
271
- this.name = 'StrandAwaitingFirstSyncError';
272
- this.strandId = strandId;
273
- this.waitedMs = waitedMs;
274
- }
275
- }
276
-
277
- /**
278
- * What one gate has established, kept for the gate's lifetime so a later probe reads only what
279
- * is still missing: whether the Header is held, and the tables (qualified, `'App.Message'`)
280
- * whose probe read settled. It only ever gains entries; a collection this machine holds stays
281
- * held.
282
- */
283
- interface FirstSyncProgress {
284
- header: boolean;
285
- tables: Set<string>;
286
- }
287
-
288
- /** A table the probe reads. */
289
- interface ProbedTable {
290
- schema: string;
291
- name: string;
292
- }
293
-
294
- const STRAND_HEADER: ProbedTable = { schema: 'Strand', name: 'Header' };
295
-
296
- function qualifiedName(table: ProbedTable): string {
297
- return `${table.schema}.${table.name}`;
298
- }
299
-
300
- /** The read `openTables` in `quereus-plugin-sereus/src/empty-collections.ts` opens a collection with. */
301
- function probeSql(table: ProbedTable): string {
302
- return `select 1 from ${table.schema}."${table.name}" limit 1`;
303
- }
304
-
305
- /**
306
- * Whether this machine holds the strand's `Strand.Header` row — the "has synced at least once
307
- * (or founded)" signal: held when the read returns a row. A throwing read (an unreachable cohort
308
- * mid-sync, a store still hydrating) reports `false` with a log, since the caller's only
309
- * response to either answer is "probe again".
310
- */
311
- async function headerHeld(db: Database, label: string): Promise<boolean> {
312
- try {
313
- for await (const _row of db.eval(probeSql(STRAND_HEADER))) {
314
- return true;
315
- }
316
- return false;
317
- } catch (error) {
318
- log('[%s] Header probe failed (treated as not yet held): %s', label,
319
- error instanceof Error ? error.message : String(error));
320
- return false;
321
- }
322
- }
323
-
324
- /**
325
- * Whether a read of `table` settles on this machine — its collection has been fetched from the
326
- * cohort, or is authoritatively absent. Only a throwing read (an unreachable cohort, a block not
327
- * yet arrived) reports `false`; an empty table is a settled read, because the founder commits
328
- * an empty collection for every declared table.
329
- */
330
- async function tableReadable(db: Database, table: ProbedTable, label: string): Promise<boolean> {
331
- try {
332
- for await (const _row of db.eval(probeSql(table))) {
333
- break;
334
- }
335
- return true;
336
- } catch (error) {
337
- log('[%s] %s probe failed (treated as not yet synced): %s', label, qualifiedName(table),
338
- error instanceof Error ? error.message : String(error));
339
- return false;
340
- }
341
- }
342
-
343
- /** The tables `schemaName` declares, views excluded; none when the schema is absent. */
344
- function schemaTables(db: Database, schemaName: string): ProbedTable[] {
345
- const schema = db.schemaManager.getSchema(schemaName);
346
- return schema
347
- ? Array.from(schema.getAllTables()).filter((table) => !table.isView).map((table) => ({ schema: schemaName, name: table.name }))
348
- : [];
349
- }
350
-
351
- /**
352
- * Every table this machine may write, in probe order: the membership tables in `Strand` (a fixed
353
- * set every strand has) and then the sApp's in `App`. The Header is left out, compared
354
- * case-insensitively as SQL identifiers are, because it is read first and alone, and its read
355
- * means something else (held = a row came back).
356
- */
357
- function writableTables(db: Database): ProbedTable[] {
358
- const header = STRAND_HEADER.name.toLowerCase();
359
- return [
360
- ...schemaTables(db, STRAND_HEADER.schema).filter((table) => table.name.toLowerCase() !== header),
361
- ...schemaTables(db, 'App')
362
- ];
363
- }
364
-
365
- /**
366
- * The gate's whole probe: the Header is held AND a read of every other `Strand` table and every
367
- * `App` table has settled. Reads only what `progress` does not record yet, and records what it
368
- * establishes.
369
- *
370
- * The Header is read first and alone: a joiner with no peer would otherwise pay one failing
371
- * network read per table for nothing. The tables are then read one after another, stopping at
372
- * the first that fails — the next probe starts there, and while the cohort is unreachable every
373
- * read of a block this machine lacks fails the same way, each after a consult.
374
- *
375
- * NOTE: the reads are serialized (Quereus's default), not `readConcurrency: 'committed'`, though
376
- * committed reads would let the table reads overlap. The Optimystic plugin's committed read
377
- * serves the tree the table already holds and never refreshes it from the network, and schema
378
- * apply initializes every table when the joiner has no catalog to hydrate, over an empty
379
- * collection staged in memory when no peer could answer. A committed probe of such a table reads
380
- * that empty collection as settled and opens the gate onto a fork. A serialized read refreshes
381
- * the tree first (`Collection.update`), which adopts the founder's log once a peer holds it.
382
- * Revisit if the plugin's committed read ever refreshes a tree it has never synced, or the gate
383
- * can ask Optimystic directly whether a collection is held.
384
- */
385
- async function strandFirstSyncComplete(db: Database, label: string, progress: FirstSyncProgress): Promise<boolean> {
386
- if (!progress.header) {
387
- if (!await headerHeld(db, label)) {
388
- return false;
389
- }
390
- progress.header = true;
391
- }
392
- for (const table of writableTables(db)) {
393
- const name = qualifiedName(table);
394
- if (progress.tables.has(name)) {
395
- continue;
396
- }
397
- if (!await tableReadable(db, table, label)) {
398
- return false;
399
- }
400
- progress.tables.add(name);
401
- }
402
- return true;
403
- }
404
-
405
- export interface StrandFirstSyncGateDeps {
406
- /** Log tag naming which strand this gate holds (the strand id). */
407
- label: string;
408
- /** The initialized database being held back from the app until the first sync completes. */
409
- database: StrandDatabase;
410
- /**
411
- * Called exactly once, from the gate's own probe, when the first sync completes. NOT called
412
- * by {@link StrandFirstSyncGate.open} — a caller that force-opens the gate (a founder
413
- * bootstrap it just ran) publishes the database itself.
414
- */
415
- onHeaderHeld: () => void;
416
- /**
417
- * Subscribe `onChange` to every block landing in this strand's store — a push such as join
418
- * backfill, a fetched block, a commit — and return the unsubscribe. `buildStrandDatabase`
419
- * passes the strand node's `storageRepo.onAnyCollectionChange`. Omitted (test doubles, a node
420
- * without it), the gate probes on its backstop alone.
421
- */
422
- subscribeStorageChanges?: (onChange: () => void) => () => void;
423
- /** Timer seam for the probe schedule; omit for real (unref'd) timeouts. */
424
- scheduler?: TimeoutScheduler;
425
- }
426
-
427
- /**
428
- * Holds one launch's `StrandDatabase` until the first sync completes: the `Strand.Header` row is
429
- * held and a read of every `Strand` and `App` table has settled. What a probe established is
430
- * remembered for the gate's lifetime, so a later probe — the gate's own, after the caller's
431
- * {@link probeOnce} — reads only what is still missing. A gate lives for one database build, so a
432
- * hibernation wake or a deferred-join retry starts over, and over a store that holds everything
433
- * every read answers locally.
434
- *
435
- * While armed it probes when data lands in the strand's store
436
- * ({@link StrandFirstSyncGateDeps.subscribeStorageChanges}, coalesced over
437
- * `TABLE_CHANGE_COALESCE_MS`), and {@link StrandFirstSyncConfig.backstopMs} after its last probe
438
- * settled when nothing has. Probes run on `scheduleRuns`: one at a time, and data landing during
439
- * one produces exactly one more.
440
- *
441
- * The wake source is the node's storage-wide change feed rather than a table watch
442
- * (`StrandDatabase.watchTables`): the Optimystic plugin arms a table's replicated-change bridge
443
- * only after the table initializes successfully, and the tables the gate waits on are the ones
444
- * whose collection could not be fetched yet, so a table watch would not hear the push that
445
- * delivers them. Each strand has its own libp2p node and store, so the feed hears this strand
446
- * only.
447
- *
448
- * NOTE: a probe's reads dial the founder, through the relay when that is the only route, even
449
- * while the founder is unreachable: one run of `joiner-first-commit-over-slow-relay` logged 17
450
- * `hop connect denied` at the relay in about 10 s, each a few frames on the joiner's relay
451
- * connection, when the gate re-probed every 500 ms and re-read every table. It now probes on
452
- * arrivals and a 2 s backstop and skips what it holds, so expect fewer. If that connection ever
453
- * shows saturated while no strand member is connected, hold the probe while the strand member
454
- * redial (`strand-peer-redial.ts`) reports none connected.
455
- */
456
- export class StrandFirstSyncGate {
457
- private readonly scheduler: TimeoutScheduler;
458
- private readonly backstopMs: number;
459
- private readonly progress: FirstSyncProgress = { header: false, tables: new Set() };
460
- private probes: TableChangeWatch | undefined;
461
- private unsubscribeStorage: (() => void) | undefined;
462
- private listening = false;
463
- /**
464
- * Data landed since the last probe started (or, before any probe, since {@link listen}), so one
465
- * is already due and will read it.
466
- */
467
- private landedSinceProbe = false;
468
- private stopped = false;
469
- private opened = false;
470
-
471
- constructor(private readonly deps: StrandFirstSyncGateDeps, config?: StrandFirstSyncConfig) {
472
- this.scheduler = deps.scheduler ?? defaultTimeoutScheduler;
473
- this.backstopMs = config?.backstopMs ?? DEFAULT_STRAND_FIRST_SYNC_BACKSTOP_MS;
474
- }
475
-
476
- /** The database this gate is holding back. */
477
- get database(): StrandDatabase {
478
- return this.deps.database;
479
- }
480
-
481
- /** True once the first sync completed (or the gate was force-opened); probing is then done. */
482
- get isOpen(): boolean {
483
- return this.opened;
484
- }
485
-
486
- /** Whether a block landed since the last probe started, or since {@link listen} when none has. */
487
- get heardDataSinceProbe(): boolean {
488
- return this.landedSinceProbe;
489
- }
490
-
491
- /**
492
- * Subscribe to the storage change feed ahead of {@link start}, so a block landing before the
493
- * gate is armed is heard: {@link heardDataSinceProbe} reports it, and `start` then probes at
494
- * once. For a first join, which skips the caller's first probe unless a member's push already
495
- * landed while the database was initializing.
496
- */
497
- listen(): void {
498
- if (this.stopped || this.opened || this.listening) return;
499
- this.listening = true;
500
- this.unsubscribeStorage = this.subscribeStorage();
501
- }
502
-
503
- /**
504
- * Arm the probe schedule. It probes when data lands, or one backstop later; and at once when
505
- * data already landed since the last probe (or since {@link listen}). Without `listen`, data
506
- * that landed between the caller's probe and this call raised no event the gate heard, so
507
- * that first backstop is what catches it.
508
- */
509
- start(): void {
510
- if (this.stopped || this.opened || this.probes !== undefined) return;
511
- this.probes = scheduleRuns(() => this.probe(), {
512
- label: `first-sync:${this.deps.label}`,
513
- backstopMs: this.backstopMs,
514
- scheduler: this.scheduler,
515
- });
516
- this.listen();
517
- if (this.landedSinceProbe) {
518
- this.probes.trigger(TABLE_CHANGE_COALESCE_MS);
519
- }
520
- log('[%s] first-sync gate armed: probing when data lands, and %dms after the last probe otherwise',
521
- this.deps.label, this.backstopMs);
522
- }
523
-
524
- /**
525
- * Open without probing: the caller is publishing the database itself — a launch whose first
526
- * probe passed (or a founder's), which never armed the schedule, or a founder bootstrap just
527
- * run against the gated database. Stops probing; `onHeaderHeld` is NOT invoked.
528
- */
529
- open(): void {
530
- if (this.opened) return;
531
- this.opened = true;
532
- this.stop();
533
- log('[%s] database published by the caller; first-sync gate not needed or force-opened', this.deps.label);
534
- }
535
-
536
- /** Disarm: unsubscribe and drop the schedule; a probe already in flight completes and is then ignored. */
537
- stop(): void {
538
- this.stopped = true;
539
- this.unsubscribeStorage?.();
540
- this.unsubscribeStorage = undefined;
541
- this.probes?.dispose();
542
- this.probes = undefined;
543
- }
544
-
545
- /**
546
- * One probe's answer, reading only what this gate has not yet seen settled. A throw from
547
- * OUTSIDE the probe's own read guards — a schema lookup, or `getDatabase()` itself — is
548
- * reported as "not yet" like any failing read, so the caller's first probe cannot fail the
549
- * launch over it and the gate's log says what happened.
550
- */
551
- async probeOnce(): Promise<boolean> {
552
- this.landedSinceProbe = false;
553
- try {
554
- return await strandFirstSyncComplete(this.deps.database.getDatabase(), this.deps.label, this.progress);
555
- } catch (error) {
556
- log('[%s] first-sync probe threw (treated as not yet synced): %s', this.deps.label,
557
- error instanceof Error ? error.message : String(error));
558
- return false;
559
- }
560
- }
561
-
562
- /**
563
- * NOTE: a probe's own reads can land blocks (a fetched block, a read-repair), which fires this
564
- * feed and schedules one follow-up probe. Each follow-up means a block newly arrived, so they
565
- * stop when nothing new lands; if gated launches ever show probe storms in the logs, ignore
566
- * events while a probe is in flight.
567
- */
568
- private subscribeStorage(): (() => void) | undefined {
569
- const subscribe = this.deps.subscribeStorageChanges;
570
- if (!subscribe) {
571
- log('[%s] no storage change feed on this node; probing every %dms only', this.deps.label, this.backstopMs);
572
- return undefined;
573
- }
574
- return subscribe(() => this.onDataLanded());
575
- }
576
-
577
- /**
578
- * Called synchronously by the store after each block lands, so it only arms a timer. A push
579
- * lands its blocks one by one; only the first since the last probe started arms one, since
580
- * that probe has not started yet and will read the rest.
581
- */
582
- private onDataLanded(): void {
583
- if (this.landedSinceProbe) return;
584
- this.landedSinceProbe = true;
585
- this.probes?.trigger(TABLE_CHANGE_COALESCE_MS);
586
- }
587
-
588
- private async probe(): Promise<void> {
589
- if (this.stopped || this.opened) return;
590
- log('[%s] first-sync probe (%s)', this.deps.label, this.landedSinceProbe ? 'data landed' : 'backstop');
591
- const held = await this.probeOnce();
592
- // Re-check after the await: a release or a force-open may have landed mid-read.
593
- if (this.stopped || this.opened || !held) return;
594
- this.opened = true;
595
- this.stop();
596
- log('[%s] first-sync gate opened: Strand.Header, every Strand table and every App table read from a peer', this.deps.label);
597
- this.deps.onHeaderHeld();
598
- }
599
- }
1
+ /**
2
+ * The first-sync write gate for a JOINING machine.
3
+ *
4
+ * A machine that has never received anything from another member of a strand must not
5
+ * commit to it. With no strand peer connected, Optimystic's cohort for every block is the
6
+ * machine itself, so the first write to a table finds no collection locally and INVENTS
7
+ * one — exactly what a founder writing alone legitimately does. When the connection comes
8
+ * up, two independently created histories share one collection id: Optimystic keeps one and
9
+ * drops the other's commits, or never reconciles them at all. The joiner's own rows silently
10
+ * vanish (`joining-machine-writes-before-first-sync-fork-tables`). Optimystic cannot tell a
11
+ * founder from a joiner; sereus can, because the launch knows whether it is founding.
12
+ *
13
+ * The invariant this module enforces: **a machine that has never held this strand's
14
+ * `Strand.Header` row, and has not read every `Strand` and `App` table once, must not commit
15
+ * to it.** The founder writes the Header in its bootstrap; every other machine can only receive
16
+ * it from a peer, so "no local Header" means "never synced". The gate therefore holds the
17
+ * freshly initialized `StrandDatabase` back from the app — `StrandInstance.database` stays
18
+ * unset and the instance reports `'syncing'` — and probes, whenever data lands in the strand's
19
+ * store and on a backstop timer, until the Header is readable AND a read of each other table
20
+ * settles, at which point the database is published and the instance goes `'active'`. A
21
+ * machine whose store already holds the Header and every other table (a founder, and normally
22
+ * a restart or a hibernation resume) passes the probe on the first try and is never gated, so
23
+ * offline-first writes on a machine that has synced before keep working.
24
+ *
25
+ * "Has synced before" is decided by what the local store actually holds, not by whether this
26
+ * machine once read the strand: a machine that left soon after its first sync can hold less
27
+ * than it read, and is then gated like a joiner. The re-attach measurement on
28
+ * {@link DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS} saw exactly that — a machine back over the store
29
+ * it kept, without the `Strand.Header` collection it had read before it left. Gating it is
30
+ * right: writing into a collection this machine does not hold would fork it.
31
+ *
32
+ * Why the other tables too: the Header is ONE collection. It reaches a joiner ahead of the
33
+ * founder's other collections (peer-join backfill and pull-on-read deliver those separately),
34
+ * and a write to a table whose collection this machine has not yet fetched invents one exactly
35
+ * as a lone joiner did. Measured on the reference chat schema (2026-09-16, direct connections,
36
+ * Header-only probe): the joiner's participant + message written the instant `addStrand`
37
+ * resolved diverged in 3 of 4 runs. The same holds for the `Strand` tables, which reach a joiner
38
+ * by the same backfill: the membership loop writes `ConsumedInvite`, `Member` and `MemberPeer`
39
+ * about a second after publication, and a manager writes `Invite`, `CancelledInvite`, `Manager`
40
+ * and `Revocation`. Reading each table once pulls its collection while the founder is
41
+ * reachable, so the write that follows appends.
42
+ *
43
+ * Every probe read is `select 1 from <table> limit 1` (`Strand.Header`, then each other `Strand`
44
+ * table, then each `App` table, skipping those already seen settled): opening the table fetches
45
+ * its collection header, and one row walks the root to the first leaf. Reads never commit a
46
+ * collection (one ruled authoritatively absent is staged empty in memory only, and an
47
+ * unreachable one throws), so probing is safe to repeat and a throw is just "not yet". Every
48
+ * table declared at founding has a collection from the start (the founder bootstrap commits the
49
+ * rest empty before its founding transaction writes the Header and the membership rows), so a
50
+ * probe read fetches it; a table a later schema version adds reads as absent until its first
51
+ * write creates the collection — see `docs/strands.md` ("Joining") for that residual.
52
+ *
53
+ * Owned by `StrandInstanceManager`: created in `buildStrandDatabase` for every database build, armed
54
+ * only for a non-founder launch whose first probe fails, stopped and dropped in
55
+ * `releaseRuntime` (so a quiesce → resume rebuild re-probes over the same store), and opened
56
+ * by `publishDatabase` whenever the database is published without its loop — a launch that
57
+ * needed no gate, or a founder request that ran the bootstrap against the still-gated
58
+ * database (`foundExistingStrand`).
59
+ *
60
+ * NOTE: the gate covers app and membership tables, not the schema catalog. A launch with no
61
+ * seed writes the catalog collection (`optimystic/schema` plus two hash-named blocks,
62
+ * measured 2026-09-16) alone, during `connectToStrand`'s schema apply, before any peer
63
+ * contact. (One with a seed cannot until a seed peer answers — Optimystic refuses the
64
+ * absence ruling — and retries its database build on a timer, `StrandInstanceManager.deferUnreachableJoin`.) That is the same "two histories under one id" shape this gate
65
+ * exists to prevent, and it is only safe because both sides derive byte-identical content
66
+ * from the same schema text. If the catalog ever carries per-machine or ordering-dependent
67
+ * content (optimystic's own `0.5-same-named-tables-in-two-schemas-share-storage` re-keys
68
+ * it), a joiner's catalog will fork against the founder's — gate the schema apply on the
69
+ * Header too, or have optimystic open the catalog read-only when a peer already holds it.
70
+ */
71
+
72
+ import debug from 'debug';
73
+ import type { Database } from '@quereus/quereus';
74
+ import type { StrandDatabase } from './strand-database.js';
75
+ import { scheduleRuns, TABLE_CHANGE_COALESCE_MS, type TableChangeWatch } from './table-change-watch.js';
76
+ import { defaultTimeoutScheduler, type TimeoutScheduler } from './timeout-scheduler.js';
77
+ import { describeThrown } from './describe-thrown.js';
78
+
79
+ const log = debug('sereus:cadre:strand-first-sync');
80
+
81
+ /**
82
+ * How long a gated launch goes without probing when no data lands in the strand's store: the
83
+ * gate probes when data arrives, and this long after its last probe settled when none has. It
84
+ * covers a probe that failed for a reason no storage event follows — a consult that missed its
85
+ * deadline while the founder held the block, or a push that never comes.
86
+ *
87
+ * Why 2 s: arrivals wake the gate, so this timer is the fallback rather than the main path. At
88
+ * the supported 3 s link round trip one consult takes about 6 s (two round trips, per the 1.8.0
89
+ * measurements on {@link DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS}), so a 2 s idle gap after a failed
90
+ * probe adds at most a third of one probe round, and it is under 1% of that 360 s budget. Shorter
91
+ * brings back the cost of polling (the gate re-probed every 500 ms before it woke on arrivals);
92
+ * much longer (5 s) delays the case with no storage event by most of a probe round for nothing.
93
+ */
94
+ export const DEFAULT_STRAND_FIRST_SYNC_BACKSTOP_MS = 2_000;
95
+
96
+ /**
97
+ * How long `CadreNode.addStrand` waits for a machine's first sync before rejecting with
98
+ * {@link StrandAwaitingFirstSyncError}. It has to cover the slowest attach sereus carries,
99
+ * which is not a first join: a machine RE-attaching through a relay on a slow link can take
100
+ * longer than one joining for the first time.
101
+ *
102
+ * Measured over a DIRECT connection (2026-09-16): the joiner reads the founder's rows about
103
+ * 1.3 s after `addStrand` would previously have resolved. That is the fast case, and it is not
104
+ * what this budget has to cover.
105
+ *
106
+ * Every harness figure below was taken on one shape: one Windows developer machine, two
107
+ * relay-only `CadreNode`s (`listenAddrs: []`) on a shared loopback dedicated relay, with a
108
+ * one-way per-frame outbound delay applied to every websocket by
109
+ * `integration-tests/src/harness/ws-latency.ts` in `pipelined` mode — frames stay overlapped
110
+ * in flight, so the figure is latency and bandwidth stays unlimited; the harness's other mode
111
+ * (`serial`) is a per-socket frame-rate cap and its delays are NOT comparable
112
+ * (`docs/testing.md` → "Link latency"). Two delays were used: 900 ms one-way, a round trip
113
+ * near 1.8 s, the band sereus supported first; and 1 500 ms one-way, the supported 3-second
114
+ * round trip. Times run from the `addStrand` call to writable.
115
+ *
116
+ * FRESH JOIN at 900 ms (2026-09-26), a machine holding nothing of the strand yet: 23, 27, 31
117
+ * and 41 s over four runs at optimystic's 1000 ms cohort read deadline, and 35, 42 and 46 s
118
+ * over three runs at a 5000 ms one; the re-attach scenario below later took 38.7, 38.7 and
119
+ * 56.9 s for the same fresh join. At that delay the 5000 ms band, 35-57 s, was the one in
120
+ * force: sereus then declared 5000 ms, because 1000 ms is shorter than one round trip on
121
+ * that link and leaves every cohort read with no answer to corroborate against. Widening that
122
+ * deadline makes a consult against a peer that cannot answer cost longer, and this phase runs
123
+ * several of those — which is why both bands are recorded here, and why a change to either
124
+ * number has to be weighed against the other.
125
+ *
126
+ * AT THE SUPPORTED LINK ON `@optimystic/*` 1.17.0 (2026-10-21), 1 500 ms one-way, the same
127
+ * scenario, one run per arm, with the probe reading every `Strand` table as well as the `App`
128
+ * one (`debt-first-sync-gate-reads-every-strand-table`); the kept-store arm was not run:
129
+ * - Fresh join: writable at 28.7 s and NOT gated, as on 1.15.0.
130
+ * - Re-attach over an EMPTY store: writable at 105.8 and 105.9 s over two runs, the row A wrote
131
+ * while B was away readable at the same moment. B's first database build fails at 7.0 s (no
132
+ * seed peer has answered; `StrandInstanceManager.deferUnreachableJoin` retries it), B's strand
133
+ * node connects to A's at 15.1 s, the retried build's `connectToStrand` takes 21.2 s, and the
134
+ * launch's first probe then takes 72.6 s and passes with no read failing, so the gate never
135
+ * arms.
136
+ * - The same arm with the probe held to the Header and the `App` table (one run, otherwise the
137
+ * same build): that probe took 12.1 s, writable at 45.4 s, the row at 63.5 s. So the seven
138
+ * `Strand` reads cost about 60 s here, about 8.6 s each, against about 6 s for each of the
139
+ * baseline's two reads — more than the 42 s estimated from one 6 s consult per read.
140
+ *
141
+ * AT THE SUPPORTED LINK ON `@optimystic/*` 1.15.0 (2026-10-20), 1 500 ms one-way, the same
142
+ * scenario, one fresh-join run, with the one-row probes woken by data landing in the store
143
+ * (`first-sync-gate-probes-cheaply`; the full-count probes polled every 500 ms gave the same
144
+ * figures):
145
+ * - Fresh join: writable at 28.8 s, and NOT gated. The launch waits 27.3 s in
146
+ * `connectToStrand` for its seed peer (it hydrates the founder's catalog, 9 tables), and by
147
+ * then the store holds the strand: the first probe passed in 24 ms.
148
+ * - The strand case of `message-cost-accounting` (two relay-only parties on loopback) agrees:
149
+ * B's `addStrand` took 471 ms, with 13 `sync` streams to A, 4 block reads from the Header
150
+ * probe and 8 from the table probes. Its two tables are empty, so a full count would fetch
151
+ * the same blocks as a one-row read.
152
+ * - Neither arms the gate, so neither times the woken path. That was checked on
153
+ * `harness-topology`'s cross-party share (a joiner launched with no seed, dialed afterwards)
154
+ * with the backstop raised to 10 s: the founder's join backfill push opened the gate 2.1 s
155
+ * after it armed.
156
+ *
157
+ * AT THE SUPPORTED LINK ON `@optimystic/*` 1.8.0 (2026-09-29), 1 500 ms one-way, the read
158
+ * deadline derived from the declared link at 7 000 ms (`cohortReadDeadlineMs` in
159
+ * `link-budget.ts`; the plugin's `COHORT_READ_DEADLINE_MS` is the same number), and cadre
160
+ * stating its declared link to Optimystic, the same scenario, all under the coordinator debug
161
+ * channel:
162
+ * - Fresh join: writable at 63.9 and 63.8 s over two runs, the row A wrote before the join
163
+ * readable at 88.0 s in both. B's strand node connected to A's at 18.3-18.4 s. No read was
164
+ * declined: every consult on B completed, 6.03-6.05 s after the one before it (two link
165
+ * round trips each). The time did not fall, because B's consults ran one after another and
166
+ * the gate opened only after the seventh.
167
+ * - Re-attach over the store B kept: no longer bimodal. All 3 runs held everything and came
168
+ * up writable at launch (9.2 s), and the row A wrote while B was away was readable at
169
+ * 35.6 s in each, read with one consult for the collection and its data block together. No
170
+ * read was declined during the attach. The empty-store arm was not re-run.
171
+ *
172
+ * AT THE SUPPORTED LINK ON `@optimystic/*` 1.7.0 (2026-09-29), same delay, deadline and
173
+ * scenario, before cadre stated its link to Optimystic:
174
+ * - Fresh join: writable at 52.1 and 82.1 s over two runs, and 63.6 s in a third run under
175
+ * the coordinator debug channel; a fourth run with the deadline set back to 5 000 ms took
176
+ * 70.2 s. B's strand node connected to A's at 18.2-18.3 s in every run at this delay. The
177
+ * row A wrote before the join was readable at 67-124 s.
178
+ * - Re-attach over the store B kept: bimodal again. 1 of 3 runs held everything and came up
179
+ * writable at launch (9.1 s; the row at 33.4 s). The other 2 were gated and writable at
180
+ * 75.7 and 78.7 s (the row at 120.8 and 175.0 s). The empty-store arm was not re-run; at
181
+ * 900 ms it matched a fresh join.
182
+ * - What that band was NOT: a measure of the 7 000 ms deadline. Every cohort consult in those
183
+ * runs ended 3.00-3.02 s after the one before it, at 5 000 and 7 000 alike, because
184
+ * Optimystic's then-fixed 3 000 ms request dial deadline also bounded the protocol
185
+ * negotiation on an already-open connection, and one negotiation is one link round trip —
186
+ * 3 s here. So it was the band of a join whose every consult failed and whose blocks
187
+ * arrived by peer-join backfill.
188
+ *
189
+ * RE-ATTACH at 900 ms (2026-09-26, the opt-in
190
+ * `integration-tests/src/scenarios/strand-reattach-first-sync-measure.integration.ts` — re-run
191
+ * it before changing this number): B attached once on an undelayed link, left with
192
+ * `stopStrand`, A wrote while it was away, the delay was raised, and B called `addStrand`
193
+ * again.
194
+ * - Over an EMPTY store (one minted per launch, cadre's default with no storage provider):
195
+ * gated in all four runs and writable at 38.7-56.8 s, the same as a fresh join.
196
+ * - Over the store it KEPT (a phone with durable storage), bimodal. In 3 of 8 runs the store
197
+ * held everything and the launch came up writable (5.6 s, the launch itself). In the other
198
+ * 5 it lacked the `Strand.Header` collection B had read on its first attach, so B was gated
199
+ * like a joiner and became writable at 64.1-78.7 s — the slowest attach measured, about
200
+ * twice a fresh join. Why syncing over a partial store is slower sits inside optimystic
201
+ * (`tickets/blocked/report-reattach-over-partial-replica-to-optimystic`).
202
+ * - Neither a redial nor catching up on missed writes explains the time: B's strand node
203
+ * connected to A's at 11 s in every arm, fresh join included, and a run with 20 missed
204
+ * writes fell inside the run-to-run spread of those with 1.
205
+ * This budget covers WRITABLE, not caught up: in the gated kept-store runs the row A wrote
206
+ * while B was away became readable only at 140-162 s (121-175 s at the supported link).
207
+ *
208
+ * Two samples from outside this harness, neither reproduced here and neither discarded: a
209
+ * reporter's re-attach of the same shape (optimystic #22; their harness, storage and delay
210
+ * injector are unknown to us) opened the gate at about 150 s, after the previous 120 s budget
211
+ * had already rejected; and a real Galaxy S7 joining fresh through relay.sereus.org took 178 s.
212
+ *
213
+ * 360 s clears the worst harness sample (105.9 s, a re-attach over an empty store at the
214
+ * supported link on 1.17.0) by about 3.4x, the reporter's re-attach by 2.4x and the device join
215
+ * by about 2x. Set by the rule every re-measure applies: keep it while the worst harness sample
216
+ * is at most 100 s, which holds a margin of at least 3x; otherwise raise it to 3x the worst
217
+ * sample, rounded up to the next whole minute. The 1.17.0 sample crossed 100 s, and 3x 105.9 s
218
+ * is 318 s, so 360 s (2026-10-21); the 1.7.0 and 1.8.0 re-measures (worst 82 s and 64 s) had
219
+ * kept the 300 s before it. 240 s was rejected earlier: it clears the device join by only 1.35x,
220
+ * and that sample was not a re-attach. History: the original 30 s sat INSIDE the 1000 ms fresh
221
+ * band and refused about half of those joins while their sync was progressing normally; 120 s
222
+ * was sized from fresh joins only and refused the reporter's re-attach.
223
+ *
224
+ * NOTE: accepted tradeoff — what 360 s costs. This wait is what an app's `addStrand` sits in
225
+ * before it is told "not yet", so a strand none of whose members is reachable at all takes six
226
+ * minutes to report instead of two. The slow report was weighed against refusing attaches that
227
+ * were working, and the refusal is the worse failure. The cost is bounded — the rejection is
228
+ * retryable, the strand stays launched and keeps probing, and `strand:writable` fires the
229
+ * moment the sync lands, so an app that listens for the event rather than awaiting the call is
230
+ * unaffected either way. Revisit if the gate ever learns whether ANY other member is connected:
231
+ * "no peer at all" could then be reported at once and this budget would only ever be spent on a
232
+ * sync that is actually in progress — worth more the longer this budget gets.
233
+ */
234
+ // eslint-disable-next-line no-restricted-syntax -- measured, not derived: the bands above, from integration-tests' strand-reattach-first-sync-measure.integration.ts; a whole first sync has no round-trip count
235
+ export const DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS = 360_000;
236
+
237
+ /** Embedder-facing tuning for the gate, threaded from `CadreNodeConfig.strandFirstSync`. */
238
+ export interface StrandFirstSyncConfig {
239
+ /**
240
+ * Default wait for `CadreNode.addStrand` (and `whenStrandWritable`) before a machine whose
241
+ * first sync has not completed is reported as not yet writable. Default
242
+ * {@link DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS}.
243
+ */
244
+ timeoutMs?: number;
245
+ /**
246
+ * While gated, probe this long after the last probe settled when no data has landed in the
247
+ * strand's store. Default {@link DEFAULT_STRAND_FIRST_SYNC_BACKSTOP_MS}.
248
+ */
249
+ backstopMs?: number;
250
+ }
251
+
252
+ /**
253
+ * Thrown by `CadreNode.addStrand` / `whenStrandWritable` when a machine has not received the
254
+ * strand's data from another member within the wait budget — because no other member is
255
+ * reachable, or because one is and the sync is still arriving over a slow link; the gate
256
+ * cannot tell the two apart. RETRYABLE: the strand stays launched and keeps probing, so a
257
+ * later `addStrand` (or `whenStrandWritable`) for the same strand completes the attach once
258
+ * the data has arrived; the `strand:writable` event fires at that moment too.
259
+ */
260
+ export class StrandAwaitingFirstSyncError extends Error {
261
+ readonly strandId: string;
262
+ readonly waitedMs: number;
263
+
264
+ constructor(strandId: string, waitedMs: number) {
265
+ super(
266
+ `Strand ${strandId} is not writable yet: this machine has not yet received the strand's data ` +
267
+ `from another member (waited ${waitedMs} ms). Either no other member is reachable, or the ` +
268
+ 'link to one is slow and the sync is still in progress. The strand stays launched and keeps ' +
269
+ 'trying — call addStrand or whenStrandWritable(strandId) again to keep waiting, or listen ' +
270
+ "for the 'strand:writable' event."
271
+ );
272
+ this.name = 'StrandAwaitingFirstSyncError';
273
+ this.strandId = strandId;
274
+ this.waitedMs = waitedMs;
275
+ }
276
+ }
277
+
278
+ /**
279
+ * What one gate has established, kept for the gate's lifetime so a later probe reads only what
280
+ * is still missing: whether the Header is held, and the tables (qualified, `'App.Message'`)
281
+ * whose probe read settled. It only ever gains entries; a collection this machine holds stays
282
+ * held.
283
+ */
284
+ interface FirstSyncProgress {
285
+ header: boolean;
286
+ tables: Set<string>;
287
+ }
288
+
289
+ /** A table the probe reads. */
290
+ interface ProbedTable {
291
+ schema: string;
292
+ name: string;
293
+ }
294
+
295
+ const STRAND_HEADER: ProbedTable = { schema: 'Strand', name: 'Header' };
296
+
297
+ function qualifiedName(table: ProbedTable): string {
298
+ return `${table.schema}.${table.name}`;
299
+ }
300
+
301
+ /** The read `openTables` in `quereus-plugin-sereus/src/empty-collections.ts` opens a collection with. */
302
+ function probeSql(table: ProbedTable): string {
303
+ return `select 1 from ${table.schema}."${table.name}" limit 1`;
304
+ }
305
+
306
+ /**
307
+ * Whether this machine holds the strand's `Strand.Header` row — the "has synced at least once
308
+ * (or founded)" signal: held when the read returns a row. A throwing read (an unreachable cohort
309
+ * mid-sync, a store still hydrating) reports `false` with a log, since the caller's only
310
+ * response to either answer is "probe again".
311
+ */
312
+ async function headerHeld(db: Database, label: string): Promise<boolean> {
313
+ try {
314
+ for await (const _row of db.eval(probeSql(STRAND_HEADER))) {
315
+ return true;
316
+ }
317
+ return false;
318
+ } catch (error) {
319
+ log('[%s] Header probe failed (treated as not yet held): %s', label,
320
+ describeThrown(error));
321
+ return false;
322
+ }
323
+ }
324
+
325
+ /**
326
+ * Whether a read of `table` settles on this machine — its collection has been fetched from the
327
+ * cohort, or is authoritatively absent. Only a throwing read (an unreachable cohort, a block not
328
+ * yet arrived) reports `false`; an empty table is a settled read, because the founder commits
329
+ * an empty collection for every declared table.
330
+ */
331
+ async function tableReadable(db: Database, table: ProbedTable, label: string): Promise<boolean> {
332
+ try {
333
+ for await (const _row of db.eval(probeSql(table))) {
334
+ break;
335
+ }
336
+ return true;
337
+ } catch (error) {
338
+ log('[%s] %s probe failed (treated as not yet synced): %s', label, qualifiedName(table),
339
+ describeThrown(error));
340
+ return false;
341
+ }
342
+ }
343
+
344
+ /** The tables `schemaName` declares, views excluded; none when the schema is absent. */
345
+ function schemaTables(db: Database, schemaName: string): ProbedTable[] {
346
+ const schema = db.schemaManager.getSchema(schemaName);
347
+ return schema
348
+ ? Array.from(schema.getAllTables()).filter((table) => !table.isView).map((table) => ({ schema: schemaName, name: table.name }))
349
+ : [];
350
+ }
351
+
352
+ /**
353
+ * Every table this machine may write, in probe order: the membership tables in `Strand` (a fixed
354
+ * set every strand has) and then the sApp's in `App`. The Header is left out, compared
355
+ * case-insensitively as SQL identifiers are, because it is read first and alone, and its read
356
+ * means something else (held = a row came back).
357
+ */
358
+ function writableTables(db: Database): ProbedTable[] {
359
+ const header = STRAND_HEADER.name.toLowerCase();
360
+ return [
361
+ ...schemaTables(db, STRAND_HEADER.schema).filter((table) => table.name.toLowerCase() !== header),
362
+ ...schemaTables(db, 'App')
363
+ ];
364
+ }
365
+
366
+ /**
367
+ * The gate's whole probe: the Header is held AND a read of every other `Strand` table and every
368
+ * `App` table has settled. Reads only what `progress` does not record yet, and records what it
369
+ * establishes.
370
+ *
371
+ * The Header is read first and alone: a joiner with no peer would otherwise pay one failing
372
+ * network read per table for nothing. The tables are then read one after another, stopping at
373
+ * the first that fails — the next probe starts there, and while the cohort is unreachable every
374
+ * read of a block this machine lacks fails the same way, each after a consult.
375
+ *
376
+ * NOTE: the reads are serialized (Quereus's default), not `readConcurrency: 'committed'`, though
377
+ * committed reads would let the table reads overlap. The Optimystic plugin's committed read
378
+ * serves the tree the table already holds and never refreshes it from the network, and schema
379
+ * apply initializes every table when the joiner has no catalog to hydrate, over an empty
380
+ * collection staged in memory when no peer could answer. A committed probe of such a table reads
381
+ * that empty collection as settled and opens the gate onto a fork. A serialized read refreshes
382
+ * the tree first (`Collection.update`), which adopts the founder's log once a peer holds it.
383
+ * Revisit if the plugin's committed read ever refreshes a tree it has never synced, or the gate
384
+ * can ask Optimystic directly whether a collection is held.
385
+ */
386
+ async function strandFirstSyncComplete(db: Database, label: string, progress: FirstSyncProgress): Promise<boolean> {
387
+ if (!progress.header) {
388
+ if (!await headerHeld(db, label)) {
389
+ return false;
390
+ }
391
+ progress.header = true;
392
+ }
393
+ for (const table of writableTables(db)) {
394
+ const name = qualifiedName(table);
395
+ if (progress.tables.has(name)) {
396
+ continue;
397
+ }
398
+ if (!await tableReadable(db, table, label)) {
399
+ return false;
400
+ }
401
+ progress.tables.add(name);
402
+ }
403
+ return true;
404
+ }
405
+
406
+ export interface StrandFirstSyncGateDeps {
407
+ /** Log tag naming which strand this gate holds (the strand id). */
408
+ label: string;
409
+ /** The initialized database being held back from the app until the first sync completes. */
410
+ database: StrandDatabase;
411
+ /**
412
+ * Called exactly once, from the gate's own probe, when the first sync completes. NOT called
413
+ * by {@link StrandFirstSyncGate.open} — a caller that force-opens the gate (a founder
414
+ * bootstrap it just ran) publishes the database itself.
415
+ */
416
+ onHeaderHeld: () => void;
417
+ /**
418
+ * Subscribe `onChange` to every block landing in this strand's store — a push such as join
419
+ * backfill, a fetched block, a commit — and return the unsubscribe. `buildStrandDatabase`
420
+ * passes the strand node's `storageRepo.onAnyCollectionChange`. Omitted (test doubles, a node
421
+ * without it), the gate probes on its backstop alone.
422
+ */
423
+ subscribeStorageChanges?: (onChange: () => void) => () => void;
424
+ /** Timer seam for the probe schedule; omit for real (unref'd) timeouts. */
425
+ scheduler?: TimeoutScheduler;
426
+ }
427
+
428
+ /**
429
+ * Holds one launch's `StrandDatabase` until the first sync completes: the `Strand.Header` row is
430
+ * held and a read of every `Strand` and `App` table has settled. What a probe established is
431
+ * remembered for the gate's lifetime, so a later probe — the gate's own, after the caller's
432
+ * {@link probeOnce} — reads only what is still missing. A gate lives for one database build, so a
433
+ * hibernation wake or a deferred-join retry starts over, and over a store that holds everything
434
+ * every read answers locally.
435
+ *
436
+ * While armed it probes when data lands in the strand's store
437
+ * ({@link StrandFirstSyncGateDeps.subscribeStorageChanges}, coalesced over
438
+ * `TABLE_CHANGE_COALESCE_MS`), and {@link StrandFirstSyncConfig.backstopMs} after its last probe
439
+ * settled when nothing has. Probes run on `scheduleRuns`: one at a time, and data landing during
440
+ * one produces exactly one more.
441
+ *
442
+ * The wake source is the node's storage-wide change feed rather than a table watch
443
+ * (`StrandDatabase.watchTables`): the Optimystic plugin arms a table's replicated-change bridge
444
+ * only after the table initializes successfully, and the tables the gate waits on are the ones
445
+ * whose collection could not be fetched yet, so a table watch would not hear the push that
446
+ * delivers them. Each strand has its own libp2p node and store, so the feed hears this strand
447
+ * only.
448
+ *
449
+ * NOTE: a probe's reads dial the founder, through the relay when that is the only route, even
450
+ * while the founder is unreachable: one run of `joiner-first-commit-over-slow-relay` logged 17
451
+ * `hop connect denied` at the relay in about 10 s, each a few frames on the joiner's relay
452
+ * connection, when the gate re-probed every 500 ms and re-read every table. It now probes on
453
+ * arrivals and a 2 s backstop and skips what it holds, so expect fewer. If that connection ever
454
+ * shows saturated while no strand member is connected, hold the probe while the strand member
455
+ * redial (`strand-peer-redial.ts`) reports none connected.
456
+ */
457
+ export class StrandFirstSyncGate {
458
+ private readonly scheduler: TimeoutScheduler;
459
+ private readonly backstopMs: number;
460
+ private readonly progress: FirstSyncProgress = { header: false, tables: new Set() };
461
+ private probes: TableChangeWatch | undefined;
462
+ private unsubscribeStorage: (() => void) | undefined;
463
+ private listening = false;
464
+ /**
465
+ * Data landed since the last probe started (or, before any probe, since {@link listen}), so one
466
+ * is already due and will read it.
467
+ */
468
+ private landedSinceProbe = false;
469
+ private stopped = false;
470
+ private opened = false;
471
+
472
+ constructor(private readonly deps: StrandFirstSyncGateDeps, config?: StrandFirstSyncConfig) {
473
+ this.scheduler = deps.scheduler ?? defaultTimeoutScheduler;
474
+ this.backstopMs = config?.backstopMs ?? DEFAULT_STRAND_FIRST_SYNC_BACKSTOP_MS;
475
+ }
476
+
477
+ /** The database this gate is holding back. */
478
+ get database(): StrandDatabase {
479
+ return this.deps.database;
480
+ }
481
+
482
+ /** True once the first sync completed (or the gate was force-opened); probing is then done. */
483
+ get isOpen(): boolean {
484
+ return this.opened;
485
+ }
486
+
487
+ /** Whether a block landed since the last probe started, or since {@link listen} when none has. */
488
+ get heardDataSinceProbe(): boolean {
489
+ return this.landedSinceProbe;
490
+ }
491
+
492
+ /**
493
+ * Subscribe to the storage change feed ahead of {@link start}, so a block landing before the
494
+ * gate is armed is heard: {@link heardDataSinceProbe} reports it, and `start` then probes at
495
+ * once. For a first join, which skips the caller's first probe unless a member's push already
496
+ * landed while the database was initializing.
497
+ */
498
+ listen(): void {
499
+ if (this.stopped || this.opened || this.listening) return;
500
+ this.listening = true;
501
+ this.unsubscribeStorage = this.subscribeStorage();
502
+ }
503
+
504
+ /**
505
+ * Arm the probe schedule. It probes when data lands, or one backstop later; and at once when
506
+ * data already landed since the last probe (or since {@link listen}). Without `listen`, data
507
+ * that landed between the caller's probe and this call raised no event the gate heard, so
508
+ * that first backstop is what catches it.
509
+ */
510
+ start(): void {
511
+ if (this.stopped || this.opened || this.probes !== undefined) return;
512
+ this.probes = scheduleRuns(() => this.probe(), {
513
+ label: `first-sync:${this.deps.label}`,
514
+ backstopMs: this.backstopMs,
515
+ scheduler: this.scheduler,
516
+ });
517
+ this.listen();
518
+ if (this.landedSinceProbe) {
519
+ this.probes.trigger(TABLE_CHANGE_COALESCE_MS);
520
+ }
521
+ log('[%s] first-sync gate armed: probing when data lands, and %dms after the last probe otherwise',
522
+ this.deps.label, this.backstopMs);
523
+ }
524
+
525
+ /**
526
+ * Open without probing: the caller is publishing the database itself — a launch whose first
527
+ * probe passed (or a founder's), which never armed the schedule, or a founder bootstrap just
528
+ * run against the gated database. Stops probing; `onHeaderHeld` is NOT invoked.
529
+ */
530
+ open(): void {
531
+ if (this.opened) return;
532
+ this.opened = true;
533
+ this.stop();
534
+ log('[%s] database published by the caller; first-sync gate not needed or force-opened', this.deps.label);
535
+ }
536
+
537
+ /** Disarm: unsubscribe and drop the schedule; a probe already in flight completes and is then ignored. */
538
+ stop(): void {
539
+ this.stopped = true;
540
+ this.unsubscribeStorage?.();
541
+ this.unsubscribeStorage = undefined;
542
+ this.probes?.dispose();
543
+ this.probes = undefined;
544
+ }
545
+
546
+ /**
547
+ * One probe's answer, reading only what this gate has not yet seen settled. A throw from
548
+ * OUTSIDE the probe's own read guards — a schema lookup, or `getDatabase()` itself — is
549
+ * reported as "not yet" like any failing read, so the caller's first probe cannot fail the
550
+ * launch over it and the gate's log says what happened.
551
+ */
552
+ async probeOnce(): Promise<boolean> {
553
+ this.landedSinceProbe = false;
554
+ try {
555
+ return await strandFirstSyncComplete(this.deps.database.getDatabase(), this.deps.label, this.progress);
556
+ } catch (error) {
557
+ log('[%s] first-sync probe threw (treated as not yet synced): %s', this.deps.label,
558
+ describeThrown(error));
559
+ return false;
560
+ }
561
+ }
562
+
563
+ /**
564
+ * NOTE: a probe's own reads can land blocks (a fetched block, a read-repair), which fires this
565
+ * feed and schedules one follow-up probe. Each follow-up means a block newly arrived, so they
566
+ * stop when nothing new lands; if gated launches ever show probe storms in the logs, ignore
567
+ * events while a probe is in flight.
568
+ */
569
+ private subscribeStorage(): (() => void) | undefined {
570
+ const subscribe = this.deps.subscribeStorageChanges;
571
+ if (!subscribe) {
572
+ log('[%s] no storage change feed on this node; probing every %dms only', this.deps.label, this.backstopMs);
573
+ return undefined;
574
+ }
575
+ return subscribe(() => this.onDataLanded());
576
+ }
577
+
578
+ /**
579
+ * Called synchronously by the store after each block lands, so it only arms a timer. A push
580
+ * lands its blocks one by one; only the first since the last probe started arms one, since
581
+ * that probe has not started yet and will read the rest.
582
+ */
583
+ private onDataLanded(): void {
584
+ if (this.landedSinceProbe) return;
585
+ this.landedSinceProbe = true;
586
+ this.probes?.trigger(TABLE_CHANGE_COALESCE_MS);
587
+ }
588
+
589
+ private async probe(): Promise<void> {
590
+ if (this.stopped || this.opened) return;
591
+ log('[%s] first-sync probe (%s)', this.deps.label, this.landedSinceProbe ? 'data landed' : 'backstop');
592
+ const held = await this.probeOnce();
593
+ // Re-check after the await: a release or a force-open may have landed mid-read.
594
+ if (this.stopped || this.opened || !held) return;
595
+ this.opened = true;
596
+ this.stop();
597
+ log('[%s] first-sync gate opened: Strand.Header, every Strand table and every App table read from a peer', this.deps.label);
598
+ this.deps.onHeaderHeld();
599
+ }
600
+ }