@effectstream/runtime 0.101.0 → 0.102.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.
package/LICENSE-APACHE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2024-2026 Midnight Foundation
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-2026 Midnight Foundation
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@effectstream/runtime",
3
- "version": "0.101.0",
4
- "license": "MIT",
3
+ "version": "0.102.0",
4
+ "license": "(MIT OR Apache-2.0)",
5
5
  "homepage": "https://effectstream.github.io/docs/",
6
6
  "repository": {
7
7
  "type": "git",
@@ -13,17 +13,17 @@
13
13
  },
14
14
  "exports": "./src/mod.ts",
15
15
  "dependencies": {
16
- "@effectstream/concise": "0.101.0",
17
- "@effectstream/config": "0.101.0",
18
- "@effectstream/coroutine": "0.101.0",
19
- "@effectstream/crypto": "0.101.0",
20
- "@effectstream/db": "0.101.0",
21
- "@effectstream/event-client": "0.101.0",
22
- "@effectstream/event-server": "0.101.0",
23
- "@effectstream/log": "0.101.0",
24
- "@effectstream/sm": "0.101.0",
25
- "@effectstream/sync": "0.101.0",
26
- "@effectstream/utils": "0.101.0",
16
+ "@effectstream/concise": "0.102.0",
17
+ "@effectstream/config": "0.102.0",
18
+ "@effectstream/coroutine": "0.102.0",
19
+ "@effectstream/crypto": "0.102.0",
20
+ "@effectstream/db": "0.102.0",
21
+ "@effectstream/event-client": "0.102.0",
22
+ "@effectstream/event-server": "0.102.0",
23
+ "@effectstream/log": "0.102.0",
24
+ "@effectstream/sm": "0.102.0",
25
+ "@effectstream/sync": "0.102.0",
26
+ "@effectstream/utils": "0.102.0",
27
27
  "@fastify/cors": "^11.0.1",
28
28
  "@metamask/json-rpc-engine": "^10.0.3",
29
29
  "pg": "8.21.0",
@@ -0,0 +1,235 @@
1
+ /**
2
+ * Sync liveness for `/health`.
3
+ *
4
+ * `/health` used to report database reachability only. That misses every
5
+ * failure this service actually suffers: a blackholed RPC, a producer whose
6
+ * stream ended, a chain that stopped advancing. All of them end the same way —
7
+ * the merge blocks on one chain's page and block production stops — while the
8
+ * database stays perfectly healthy. A node that has not applied a block in an
9
+ * hour would answer `200 {"status":"ok"}`.
10
+ *
11
+ * Two deliberate choices:
12
+ *
13
+ * 1. **Liveness is measured in wall-clock time since the last APPLIED block**,
14
+ * not in block-timestamp lag. A chain replaying history is legitimately
15
+ * hours behind in block time while being perfectly healthy; what matters is
16
+ * whether the pipeline is still moving.
17
+ *
18
+ * 2. **503 is reserved for "not doing its job"** — database unreachable, or no
19
+ * block applied within the threshold. A chain that is erroring or restarting
20
+ * its producer while blocks still flow reports `degraded` with a 200, so an
21
+ * orchestrator does not kill a node that is recovering on its own.
22
+ */
23
+ import type { AllSyncProtocols } from "@effectstream/sync";
24
+ import { poolErrors } from "@effectstream/db";
25
+ import { appliedBlockStatus } from "./apply-status.ts";
26
+ import { finalizedStreamStatus } from "./stream-status.ts";
27
+
28
+ /**
29
+ * Node-level rollup. `ok` and `degraded` answer 200; `starting`, `stalled` and
30
+ * `db-unreachable` answer 503 (not ready to serve).
31
+ */
32
+ export type HealthStatus =
33
+ | "ok"
34
+ | "degraded"
35
+ | "starting"
36
+ | "stalled"
37
+ | "db-unreachable";
38
+
39
+ /** Per-protocol rollup. `blockingMerge` is reported separately. */
40
+ export type ProtocolStatus = "ok" | "starting" | "erroring" | "wedged";
41
+
42
+ export type ProtocolHealth = {
43
+ name: string;
44
+ status: ProtocolStatus;
45
+ /** Highest block of this chain that has been merged into a produced block. */
46
+ ownBlockNumber: number | null;
47
+ /** ms since this chain's fetch loop last completed a pass; null if never. */
48
+ sinceLastPollMs: number | null;
49
+ /** ms since `readData` last returned successfully; null if never. */
50
+ sinceLastSuccessfulFetchMs: number | null;
51
+ consecutiveErrors: number;
52
+ /** Streaming producers only: restarts since boot. A climb means flapping. */
53
+ producerRestarts: number;
54
+ /** Producer failures, counted independently of `consecutiveErrors`. */
55
+ producerErrors: number;
56
+ /** ms since the last producer failure; null if there has never been one. */
57
+ sinceLastProducerErrorMs: number | null;
58
+ /**
59
+ * True when the merge is currently waiting for THIS chain's page to advance.
60
+ * When the node is stalled, this is the field that says where to look.
61
+ */
62
+ blockingMerge: boolean;
63
+ /** In-memory fetched-not-yet-merged data, and the backpressure cap. */
64
+ buffered: number;
65
+ bufferCap: number;
66
+ paused: boolean;
67
+ };
68
+
69
+ export type HealthReport = {
70
+ status: HealthStatus;
71
+ db: ReturnType<typeof poolErrors.state>;
72
+ apply: {
73
+ blockHeight: number | null;
74
+ /**
75
+ * ms since the node last applied ANY block — the liveness signal. Never
76
+ * null: before the first block it measures from process start instead.
77
+ */
78
+ sinceLastAppliedMs: number;
79
+ /** Block-time lag. Informational: large during legitimate catch-up. */
80
+ lagMs: number | null;
81
+ };
82
+ finalizedStream: {
83
+ produced: number;
84
+ consumed: number;
85
+ inFlight: number;
86
+ };
87
+ protocols: ProtocolHealth[];
88
+ };
89
+
90
+ /**
91
+ * A fetch loop is "wedged" once its heartbeat is this many polling intervals
92
+ * stale. Generous, because the cost of a false positive (a flapping 503) is
93
+ * worse than noticing a genuine hang a minute late — and a hung request is now
94
+ * bounded by `requestTimeoutMs` anyway, so a healthy loop always cycles.
95
+ */
96
+ const WEDGED_POLL_MULTIPLE = 20;
97
+ /** Floor for the above, so fast-polling chains don't trip on a single hiccup.
98
+ *
99
+ * Caveat worth knowing before alerting on `wedged`: one `readData` pass fetches
100
+ * a whole chunk, which can be many sequential RPCs, so during deep catch-up a
101
+ * legitimately-progressing chain can exceed this without returning to the top of
102
+ * the loop and briefly read as `wedged`. Node-level status stays 200 while
103
+ * blocks keep applying, so this is cosmetic — but alert on the node's `status`,
104
+ * not on a single protocol's. */
105
+ const WEDGED_MIN_MS = 60_000;
106
+
107
+ /**
108
+ * How long after a producer failure the chain still reports `erroring`. Twice
109
+ * the supervisor's max backoff, so a producer that recovers on its first or
110
+ * second restart clears the flag on its own.
111
+ */
112
+ const PRODUCER_FLAP_WINDOW_MS = 60_000;
113
+
114
+ function protocolHealth(
115
+ protocol: AllSyncProtocols,
116
+ now: number,
117
+ ): ProtocolHealth {
118
+ const sinceLastPollMs = protocol.lastPollAtMs > 0
119
+ ? now - protocol.lastPollAtMs
120
+ : null;
121
+ const sinceLastSuccessfulFetchMs = protocol.lastSuccessfulFetchMs > 0
122
+ ? now - protocol.lastSuccessfulFetchMs
123
+ : null;
124
+
125
+ // `pollingIntervalMs` is published by startSync, so this and the loop agree on
126
+ // one value. It is 0 until startSync stamps it; fall back until then.
127
+ const wedgedAfterMs = Math.max(
128
+ WEDGED_POLL_MULTIPLE * (protocol.pollingIntervalMs || 1_000),
129
+ WEDGED_MIN_MS,
130
+ );
131
+
132
+ const sinceLastProducerErrorMs = protocol.lastProducerErrorMs > 0
133
+ ? now - protocol.lastProducerErrorMs
134
+ : null;
135
+
136
+ let status: ProtocolStatus;
137
+ if (sinceLastPollMs != null && sinceLastPollMs > wedgedAfterMs) {
138
+ // The loop itself stopped cycling: stuck inside a call that never returned.
139
+ status = "wedged";
140
+ } else if (protocol.consecutiveErrors > 0) {
141
+ status = "erroring";
142
+ } else if (
143
+ sinceLastProducerErrorMs != null &&
144
+ sinceLastProducerErrorMs < PRODUCER_FLAP_WINDOW_MS
145
+ ) {
146
+ // A producer that failed recently but has been restarted. Reported so a
147
+ // flapping stream is visible, and time-bounded so a single old blip does
148
+ // not pin the chain to `erroring` forever (which is what sharing
149
+ // `consecutiveErrors` used to do for an idle streaming chain).
150
+ status = "erroring";
151
+ } else if (protocol.lastPage == null) {
152
+ status = "starting";
153
+ } else {
154
+ status = "ok";
155
+ }
156
+
157
+ return {
158
+ name: protocol.name,
159
+ status,
160
+ ownBlockNumber: protocol.lastPage?.ownBlockNumber ?? null,
161
+ sinceLastPollMs,
162
+ sinceLastSuccessfulFetchMs,
163
+ consecutiveErrors: protocol.consecutiveErrors,
164
+ producerRestarts: protocol.producerRestarts,
165
+ producerErrors: protocol.producerErrors,
166
+ sinceLastProducerErrorMs,
167
+ blockingMerge: protocol.mergeWaitingForPage,
168
+ buffered: protocol.bufferedData.size(),
169
+ bufferCap: protocol.bufferCap,
170
+ paused: protocol.pausedNow,
171
+ };
172
+ }
173
+
174
+ /**
175
+ * @param stallThresholdMs How long without applying a block counts as stalled.
176
+ * Callers pass the same value used for lag logging and coalescing (20× the
177
+ * main clock's block time, or `EFFECTSTREAM_LAG_THRESHOLD_MS`).
178
+ */
179
+ export function buildHealthReport(
180
+ syncProtocols: AllSyncProtocols[],
181
+ stallThresholdMs: number,
182
+ ): HealthReport {
183
+ const now = Date.now();
184
+ const db = poolErrors.state();
185
+ const protocols = syncProtocols.map((p) => protocolHealth(p, now));
186
+
187
+ const appliedAtMs = appliedBlockStatus.appliedAtMs;
188
+ // Before the first block, measure from process start instead — a node that
189
+ // boots and never applies anything is stalled too, and that is exactly what a
190
+ // chain wedged from its very first request looks like.
191
+ const sinceLastAppliedMs = appliedAtMs != null
192
+ ? now - appliedAtMs
193
+ : Math.round(process.uptime() * 1000);
194
+ const appliedTs = appliedBlockStatus.timestamp;
195
+ const neverApplied = appliedAtMs == null;
196
+
197
+ let status: HealthStatus;
198
+ if (db.sustained) {
199
+ status = "db-unreachable";
200
+ } else if (neverApplied && sinceLastAppliedMs <= stallThresholdMs) {
201
+ // Booting: migrations, genesis sync, first merge. Not ready to serve, but
202
+ // distinct from `stalled` so an operator can tell "still coming up" from
203
+ // "was up and stopped".
204
+ status = "starting";
205
+ } else if (sinceLastAppliedMs > stallThresholdMs) {
206
+ status = "stalled";
207
+ } else if (protocols.some((p) => p.status !== "ok" && p.status !== "starting")) {
208
+ // Something is unhealthy but blocks are still flowing: worth alerting on,
209
+ // not worth restarting the node over.
210
+ status = "degraded";
211
+ } else {
212
+ status = "ok";
213
+ }
214
+
215
+ return {
216
+ status,
217
+ db,
218
+ apply: {
219
+ blockHeight: appliedBlockStatus.blockNumber,
220
+ sinceLastAppliedMs,
221
+ lagMs: appliedTs != null ? now - appliedTs : null,
222
+ },
223
+ finalizedStream: {
224
+ produced: finalizedStreamStatus.produced,
225
+ consumed: finalizedStreamStatus.consumed,
226
+ inFlight: finalizedStreamStatus.produced - finalizedStreamStatus.consumed,
227
+ },
228
+ protocols,
229
+ };
230
+ }
231
+
232
+ /** 503 only when the node is not (yet) doing its job; see the note at the top. */
233
+ export function healthHttpStatus(status: HealthStatus): 200 | 503 {
234
+ return status === "ok" || status === "degraded" ? 200 : 503;
235
+ }
@@ -2,6 +2,7 @@ import fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest }
2
2
  import { evmRpcEngine } from "./rpc-evm/eip1193.ts";
3
3
  import { appliedBlockStatus } from "./apply-status.ts";
4
4
  import { finalizedStreamStatus } from "./stream-status.ts";
5
+ import { buildHealthReport, healthHttpStatus } from "./health.ts";
5
6
  import type { Pool } from "pg";
6
7
  import cors from "@fastify/cors";
7
8
  import { run, until } from "effection";
@@ -159,6 +160,8 @@ function* registerOpenApiDocumentation(
159
160
  export const startHttpServer = function* (
160
161
  dbConn: Pool,
161
162
  syncProtocols: AllSyncProtocols[],
163
+ /** How long without applying a block counts as stalled on `/health`. */
164
+ stallThresholdMs: number,
162
165
  apiRouter?: StartConfigApiRouter,
163
166
  grammar?: GrammarDefinition,
164
167
  ) {
@@ -373,9 +376,35 @@ export const startHttpServer = function* (
373
376
  sustainedDurationMs: Type.Number(),
374
377
  sustained: Type.Boolean(),
375
378
  });
379
+ const HealthProtocolSchema = Type.Object({
380
+ name: Type.String(),
381
+ status: Type.String(),
382
+ ownBlockNumber: Type.Union([Type.Number(), Type.Null()]),
383
+ sinceLastPollMs: Type.Union([Type.Number(), Type.Null()]),
384
+ sinceLastSuccessfulFetchMs: Type.Union([Type.Number(), Type.Null()]),
385
+ consecutiveErrors: Type.Number(),
386
+ producerRestarts: Type.Number(),
387
+ producerErrors: Type.Number(),
388
+ sinceLastProducerErrorMs: Type.Union([Type.Number(), Type.Null()]),
389
+ blockingMerge: Type.Boolean(),
390
+ buffered: Type.Number(),
391
+ bufferCap: Type.Number(),
392
+ paused: Type.Boolean(),
393
+ });
376
394
  const HealthResponseSchema = Type.Object({
377
395
  status: Type.String(),
378
396
  db: HealthDbSchema,
397
+ apply: Type.Object({
398
+ blockHeight: Type.Union([Type.Number(), Type.Null()]),
399
+ sinceLastAppliedMs: Type.Number(),
400
+ lagMs: Type.Union([Type.Number(), Type.Null()]),
401
+ }),
402
+ finalizedStream: Type.Object({
403
+ produced: Type.Number(),
404
+ consumed: Type.Number(),
405
+ inFlight: Type.Number(),
406
+ }),
407
+ protocols: Type.Array(HealthProtocolSchema),
379
408
  });
380
409
  server.get("/health", {
381
410
  schema: {
@@ -386,10 +415,10 @@ export const startHttpServer = function* (
386
415
  },
387
416
  },
388
417
  }, (_req, reply) => {
389
- const db = poolErrors.state();
390
- return reply
391
- .status(db.sustained ? 503 : 200)
392
- .send({ status: db.sustained ? "db-unreachable" : "ok", db });
418
+ // Reports sync liveness, not just database reachability — a stalled merge
419
+ // leaves the database perfectly healthy. See ./health.ts.
420
+ const report = buildHealthReport(syncProtocols, stallThresholdMs);
421
+ return reply.status(healthHttpStatus(report.status)).send(report);
393
422
  });
394
423
 
395
424
  server.get("/addresses", {
@@ -20,7 +20,7 @@ import { getEnv } from "@effectstream/utils/runtime";
20
20
  * Cardano CARP → syncProtocol.startSlot
21
21
  * Cardano UTXOrpc → syncProtocol.startChainPoint
22
22
  * EVM, Mina, Avail, Midnight,
23
- * Bitcoin, Celestia → syncProtocol.startBlockHeight
23
+ * Bitcoin, Celestia, NEAR, Solana → syncProtocol.startBlockHeight
24
24
  */
25
25
  function extractImmutableConfig(protocol: SyncProtocolWithNetwork): Record<string, unknown> {
26
26
  // NTP and the synthetic TEST chain both derive blocks arithmetically from
@@ -49,7 +49,7 @@ function extractImmutableConfig(protocol: SyncProtocolWithNetwork): Record<strin
49
49
  return { startChainPoint: sp.startChainPoint };
50
50
  }
51
51
 
52
- // EVM, Mina, Avail, Midnight, Bitcoin, Celestia
52
+ // EVM, Mina, Avail, Midnight, Bitcoin, Celestia, NEAR, Solana
53
53
  const knownBlockHeightProtocols: string[] = [
54
54
  ConfigSyncProtocolType.EVM_RPC_PARALLEL,
55
55
  ConfigSyncProtocolType.MINA_PARALLEL,
@@ -58,6 +58,7 @@ function extractImmutableConfig(protocol: SyncProtocolWithNetwork): Record<strin
58
58
  ConfigSyncProtocolType.BITCOIN_RPC_PARALLEL,
59
59
  ConfigSyncProtocolType.CELESTIA_PARALLEL,
60
60
  ConfigSyncProtocolType.NEAR_RPC_PARALLEL,
61
+ ConfigSyncProtocolType.SOLANA_RPC_PARALLEL,
61
62
  ];
62
63
  if (!knownBlockHeightProtocols.includes(protocol.syncProtocolType)) {
63
64
  throw new Error(
package/src/main.ts CHANGED
@@ -90,18 +90,11 @@ export function* start(config: StartConfig): Operation<void> {
90
90
  new EventBroker("effectstream-engine").createServer();
91
91
  }
92
92
 
93
- yield* spawn(function* () {
94
- yield* startHttpServer(
95
- dbConn,
96
- syncProtocols,
97
- config.apiRouter,
98
- config.grammar,
99
- );
100
- });
101
-
102
93
  // 20× main clock block time (NTP if present, else protocol 0).
103
94
  // Falls back to 60 s so coalescing is not silently disabled for chains that
104
95
  // don't expose a blockTimeMS on their network config (e.g. Midnight-as-main).
96
+ // Computed before the HTTP server starts because /health uses the same
97
+ // threshold to decide whether the node counts as stalled.
105
98
  const ntpConfig = syncInfo.find(s => s.networkType === ConfigNetworkType.NTP);
106
99
  const clockBlockTimeMS =
107
100
  (ntpConfig?.network as { blockTimeMS?: number } | undefined)?.blockTimeMS ??
@@ -109,6 +102,16 @@ export function* start(config: StartConfig): Operation<void> {
109
102
  const lagThresholdMs = ENV.EFFECTSTREAM_LAG_THRESHOLD_MS ??
110
103
  (clockBlockTimeMS != null ? clockBlockTimeMS * 20 : 60_000);
111
104
 
105
+ yield* spawn(function* () {
106
+ yield* startHttpServer(
107
+ dbConn,
108
+ syncProtocols,
109
+ lagThresholdMs,
110
+ config.apiRouter,
111
+ config.grammar,
112
+ );
113
+ });
114
+
112
115
  // Bounded hand-off queue between the merge and the apply loop. Backpressure caps
113
116
  // the in-memory queue so deep catch-up can't grow it toward the whole backlog
114
117
  // (see finalized-stream.ts / sync/CLAUDE.md Finding #1).
@@ -0,0 +1,207 @@
1
+ /**
2
+ * Timing must not change state.
3
+ *
4
+ * The whole pipeline rests on one property: two nodes syncing the same chains
5
+ * reach byte-identical state, regardless of how fast they got there. Block `n`
6
+ * always holds the same data on every machine, so the block-hash chain — and
7
+ * everything downstream of it — agrees.
8
+ *
9
+ * That property is easy to break by accident, and three changes in this branch
10
+ * touch the fetch path: per-request timeouts, unconditional loop pacing, and
11
+ * producer supervision. All three alter *when* a fetch happens, so this test
12
+ * varies exactly those knobs and asserts the resulting databases are identical.
13
+ *
14
+ * Why it holds, and what would break it:
15
+ *
16
+ * - Pacing changes only how often the loop asks. A block's content is a pure
17
+ * function of its height (the main clock derives timestamps arithmetically;
18
+ * parallel data merges into the first root block whose timestamp is >= its
19
+ * own), so polling faster only reaches the same answer sooner.
20
+ *
21
+ * - A timeout makes `readData` throw, and `lastPage` only advances on a
22
+ * COMPLETE `DataFetched` — so a timeout re-fetches the same range rather
23
+ * than skipping it. A slower machine that times out where a faster one does
24
+ * not therefore converges on the same data. It would NOT be safe if a
25
+ * partial result were ever committed, which is why the fetchers build their
26
+ * whole page-range before returning.
27
+ *
28
+ * The synthetic chain is deterministic by construction, so any difference here
29
+ * comes from the engine rather than from the chain.
30
+ */
31
+ import { afterEach, beforeEach, expect, test } from "bun:test";
32
+ import {
33
+ ConfigBuilder,
34
+ ConfigNetworkType,
35
+ ConfigSyncProtocolType,
36
+ } from "@effectstream/config";
37
+ import { TestChainControl } from "@effectstream/sync";
38
+ import {
39
+ compareConsistencySnapshots,
40
+ type ConsistencySnapshot,
41
+ dumpConsistencySnapshot,
42
+ SYNC_BOOKKEEPING_TABLES,
43
+ } from "./consistency-snapshot.ts";
44
+ import { type Harness, setupHarness, TEST_PRIMITIVE_TYPE } from "./harness.ts";
45
+
46
+ const START_TIME = 1_700_000_000_000;
47
+ const BLOCK_TIME_MS = 1000;
48
+ const TARGET = 60;
49
+ /**
50
+ * The parallel chain is deliberately fetched further than the main clock. The
51
+ * merge only folds a parallel chain's data into root timestamp T once that
52
+ * chain's page is STRICTLY past T, so a parallel tip equal to the main tip
53
+ * stalls production one block short of the target (see the merge-boundary note
54
+ * in sync/CLAUDE.md).
55
+ */
56
+ const PARALLEL_TIP = TARGET + 40;
57
+
58
+ const MAIN = "detMain";
59
+ const PAR = "detParallel";
60
+
61
+ /** Events spread across the range so several blocks carry state. */
62
+ const EVENTS = [
63
+ { atBlock: 12, payload: { v: "a" } },
64
+ { atBlock: 25, payload: { v: "b" } },
65
+ { atBlock: 44, payload: { v: "c" } },
66
+ ];
67
+
68
+ type Timing = {
69
+ pollingInterval: number;
70
+ stepSize: number;
71
+ requestTimeoutMs: number;
72
+ };
73
+
74
+ function buildConfig(timing: Timing) {
75
+ return new ConfigBuilder()
76
+ .setNamespace((b) => b.setSecurityNamespace("sync-determinism"))
77
+ .buildNetworks((b) =>
78
+ b
79
+ .addNetwork({
80
+ name: "clock",
81
+ type: ConfigNetworkType.TEST,
82
+ startTime: START_TIME,
83
+ blockTimeMS: BLOCK_TIME_MS,
84
+ })
85
+ .addNetwork({
86
+ name: "chainP",
87
+ type: ConfigNetworkType.TEST,
88
+ startTime: START_TIME,
89
+ blockTimeMS: BLOCK_TIME_MS,
90
+ })
91
+ )
92
+ .buildDeployments((b) => b)
93
+ .buildSyncProtocols((b) =>
94
+ b
95
+ .addMain(
96
+ (n) => n.clock,
97
+ () => ({
98
+ name: MAIN,
99
+ type: ConfigSyncProtocolType.TEST_MAIN,
100
+ startBlockHeight: 1,
101
+ pollingInterval: timing.pollingInterval,
102
+ stepSize: timing.stepSize,
103
+ requestTimeoutMs: timing.requestTimeoutMs,
104
+ }),
105
+ )
106
+ .addParallel(
107
+ (n) => (n as any).chainP,
108
+ () => ({
109
+ name: PAR,
110
+ type: ConfigSyncProtocolType.TEST_PARALLEL,
111
+ startBlockHeight: 1,
112
+ pollingInterval: timing.pollingInterval,
113
+ stepSize: timing.stepSize,
114
+ requestTimeoutMs: timing.requestTimeoutMs,
115
+ delayMs: 0,
116
+ events: EVENTS,
117
+ }),
118
+ )
119
+ )
120
+ .buildPrimitives((b) =>
121
+ b.addPrimitive(
122
+ (sp) => (sp as any)[PAR],
123
+ () => ({ name: "detEvt", type: TEST_PRIMITIVE_TYPE, startBlockHeight: 1 }),
124
+ )
125
+ )
126
+ .build();
127
+ }
128
+
129
+ /** Sync a fresh database to TARGET under the given timing, then fingerprint it. */
130
+ async function syncUnder(
131
+ timing: Timing,
132
+ apiPort: number,
133
+ ): Promise<ConsistencySnapshot> {
134
+ const h: Harness = await setupHarness();
135
+ try {
136
+ TestChainControl.clear();
137
+ TestChainControl.setTip(MAIN, TARGET);
138
+ TestChainControl.setTip(PAR, PARALLEL_TIP);
139
+
140
+ await h.runToHeight({
141
+ events: [],
142
+ // Keyed by THIS config's protocol names; a mismatch would leave the
143
+ // synthetic chain on its wall-clock fallback tip and sync to "now".
144
+ tips: { [MAIN]: TARGET, [PAR]: PARALLEL_TIP },
145
+ target: TARGET,
146
+ apiPort,
147
+ config: buildConfig(timing),
148
+ });
149
+
150
+ // Bookkeeping tables legitimately differ by path (the page queue records
151
+ // where a run happened to be), so compare observable state.
152
+ return await dumpConsistencySnapshot(h.pool, {
153
+ excludeTables: SYNC_BOOKKEEPING_TABLES,
154
+ });
155
+ } finally {
156
+ await h.teardown();
157
+ }
158
+ }
159
+
160
+ beforeEach(() => {
161
+ TestChainControl.clear();
162
+ });
163
+ afterEach(() => {
164
+ TestChainControl.clear();
165
+ });
166
+
167
+ test("state is identical regardless of polling speed, chunk size and timeouts", async () => {
168
+ // Fast + fine-grained: many small fetches, tight deadline.
169
+ const fast = await syncUnder(
170
+ { pollingInterval: 5, stepSize: 5, requestTimeoutMs: 1_000 },
171
+ 19201,
172
+ );
173
+
174
+ // Slow + coarse: fewer, larger fetches, generous deadline. A different
175
+ // machine under different load is somewhere between these two.
176
+ const slow = await syncUnder(
177
+ { pollingInterval: 60, stepSize: 100, requestTimeoutMs: 30_000 },
178
+ 19202,
179
+ );
180
+
181
+ const { diffs } = compareConsistencySnapshots(fast, slow);
182
+ expect(diffs).toEqual([]);
183
+
184
+ // Guard against the assertion passing vacuously on two empty databases.
185
+ const rows = [...fast.values()].reduce((sum, f) => sum + f.rowCount, 0);
186
+ expect(rows).toBeGreaterThan(0);
187
+ }, 180_000);
188
+
189
+ test("the block hash chain is identical across timings", async () => {
190
+ const a = await syncUnder(
191
+ { pollingInterval: 5, stepSize: 5, requestTimeoutMs: 1_000 },
192
+ 19203,
193
+ );
194
+ const b = await syncUnder(
195
+ { pollingInterval: 60, stepSize: 100, requestTimeoutMs: 30_000 },
196
+ 19204,
197
+ );
198
+
199
+ // effectstream_blocks carries block_height + effectstream_block_hash, so an
200
+ // identical fingerprint here means every block hashed the same on both runs —
201
+ // the property consensus actually depends on. Called out separately from the
202
+ // whole-database check so a failure points straight at the hash chain.
203
+ const key = "effectstream.effectstream_blocks";
204
+ expect(a.get(key)).toBeDefined();
205
+ expect(a.get(key)!.rowCount).toBeGreaterThan(0);
206
+ expect(b.get(key)?.fingerprint).toBe(a.get(key)!.fingerprint);
207
+ }, 180_000);
@@ -317,6 +317,16 @@ export type RunToHeightOpts = {
317
317
  securityNamespace?: string;
318
318
  /** Enable/disable empty-block coalescing. */
319
319
  coalesce?: boolean;
320
+ /**
321
+ * Full ConfigBuilder output, for tests that need protocols the default
322
+ * scenario doesn't provide. When omitted the node-runner builds the standard
323
+ * two-protocol scenario from `events`/`parallelStepSize`.
324
+ *
325
+ * NOTE: `tips` must then be keyed by THIS config's protocol names — a
326
+ * mismatch leaves the synthetic chain on its wall-clock fallback tip, which
327
+ * silently syncs to "now" instead of the intended height.
328
+ */
329
+ config?: any;
320
330
  };
321
331
 
322
332
  const RUNNER = join(import.meta.dir, "node-runner.ts");
@@ -342,6 +352,9 @@ function makeRunToHeight(
342
352
  apiPort: opts.apiPort,
343
353
  waitPages: opts.waitPages,
344
354
  coalesce: opts.coalesce,
355
+ // Forwarded so a caller can supply its own protocols; node-runner already
356
+ // prefers `spec.config` over the default scenario.
357
+ config: opts.config,
345
358
  };
346
359
  return new Promise<void>((resolve, reject) => {
347
360
  const child = spawn("bun", [RUNNER, JSON.stringify(spec)], {
@@ -458,8 +471,14 @@ function makeRunNode(
458
471
  }
459
472
  })();
460
473
 
474
+ // Readiness here means "the HTTP server is listening", not "the node is
475
+ // healthy": /health answers 503 while the node is still `starting` (no
476
+ // block applied yet) or `stalled`, and several tests deliberately boot a
477
+ // node into exactly those states.
461
478
  const up = await pollUntil(
462
- () => fetch(`http://127.0.0.1:${opts.apiPort}/health`).then((r) => r.ok),
479
+ () =>
480
+ fetch(`http://127.0.0.1:${opts.apiPort}/health`)
481
+ .then((r) => r.status === 200 || r.status === 503),
463
482
  10_000,
464
483
  );
465
484
  if (!up) {
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Sync liveness on `/health` (sync/CLAUDE.md Finding #6).
3
+ *
4
+ * `/health` used to report only `poolErrors.state()` — database reachability.
5
+ * Every failure mode found in this investigation is invisible to that check:
6
+ * a blackholed RPC, a producer whose stream ended, or simply one chain that
7
+ * stopped advancing all end the same way — the merge blocks on that chain's
8
+ * page and block production stops — while the database stays perfectly
9
+ * healthy and `/health` keeps answering `200 {"status":"ok"}`.
10
+ *
11
+ * This test stalls the merge deterministically (a parallel chain pinned far
12
+ * behind the main clock, the head-of-line case from `buffering.test.ts` 1b) and
13
+ * asserts that `/health` now:
14
+ * - reports 503 with `status: "stalled"`,
15
+ * - names the protocol the merge is waiting on (`blockingMerge`),
16
+ * - and still reports the healthy chain as `ok`.
17
+ *
18
+ * The apply-lag threshold is driven by EFFECTSTREAM_LAG_THRESHOLD_MS so this
19
+ * runs in seconds rather than the 20× block-time default.
20
+ */
21
+ import { afterEach, beforeEach, expect, test } from "bun:test";
22
+ import {
23
+ ConfigBuilder,
24
+ ConfigNetworkType,
25
+ ConfigSyncProtocolType,
26
+ } from "@effectstream/config";
27
+ import { TestChainControl } from "@effectstream/sync";
28
+ import {
29
+ type Harness,
30
+ type RunningNode,
31
+ setupHarness,
32
+ sleep,
33
+ TEST_PRIMITIVE_TYPE,
34
+ } from "./harness.ts";
35
+
36
+ const START_TIME = 1_700_000_000_000;
37
+ const BLOCK_TIME_MS = 1000;
38
+ const STEP_SIZE = 1000;
39
+
40
+ const MAIN = "healthMain";
41
+ const PAR_OK = "healthParallelOk";
42
+ const PAR_STALLED = "healthParallelStalled";
43
+
44
+ /** Main clock runs far ahead; the stalled chain is pinned just above genesis. */
45
+ const MAIN_TIP = 5_000;
46
+ const OK_TIP = 5_000;
47
+ const STALLED_TIP = 5;
48
+
49
+ /** Well below the time this test spends waiting, so "stalled" latches quickly. */
50
+ const LAG_THRESHOLD_MS = 2_000;
51
+
52
+ function buildConfig() {
53
+ return new ConfigBuilder()
54
+ .setNamespace((b) => b.setSecurityNamespace("sync-health"))
55
+ .buildNetworks((b) =>
56
+ b
57
+ .addNetwork({
58
+ name: "clock",
59
+ type: ConfigNetworkType.TEST,
60
+ startTime: START_TIME,
61
+ blockTimeMS: BLOCK_TIME_MS,
62
+ })
63
+ .addNetwork({
64
+ name: "chainOk",
65
+ type: ConfigNetworkType.TEST,
66
+ startTime: START_TIME,
67
+ blockTimeMS: BLOCK_TIME_MS,
68
+ })
69
+ .addNetwork({
70
+ name: "chainStalled",
71
+ type: ConfigNetworkType.TEST,
72
+ startTime: START_TIME,
73
+ blockTimeMS: BLOCK_TIME_MS,
74
+ })
75
+ )
76
+ .buildDeployments((b) => b)
77
+ .buildSyncProtocols((b) =>
78
+ b
79
+ .addMain(
80
+ (n) => n.clock,
81
+ () => ({
82
+ name: MAIN,
83
+ type: ConfigSyncProtocolType.TEST_MAIN,
84
+ startBlockHeight: 1,
85
+ pollingInterval: 30,
86
+ stepSize: STEP_SIZE,
87
+ }),
88
+ )
89
+ .addParallel(
90
+ (n) => (n as any).chainOk,
91
+ () => ({
92
+ name: PAR_OK,
93
+ type: ConfigSyncProtocolType.TEST_PARALLEL,
94
+ startBlockHeight: 1,
95
+ pollingInterval: 30,
96
+ stepSize: STEP_SIZE,
97
+ delayMs: 0,
98
+ events: [],
99
+ }),
100
+ )
101
+ .addParallel(
102
+ (n) => (n as any).chainStalled,
103
+ () => ({
104
+ name: PAR_STALLED,
105
+ type: ConfigSyncProtocolType.TEST_PARALLEL,
106
+ startBlockHeight: 1,
107
+ pollingInterval: 30,
108
+ stepSize: STEP_SIZE,
109
+ delayMs: 0,
110
+ events: [],
111
+ }),
112
+ )
113
+ )
114
+ .buildPrimitives((b) =>
115
+ b.addPrimitive(
116
+ (sp) => (sp as any)[PAR_OK],
117
+ () => ({ name: "noEvtHealth", type: TEST_PRIMITIVE_TYPE, startBlockHeight: 1 }),
118
+ )
119
+ )
120
+ .build();
121
+ }
122
+
123
+ type HealthProtocol = {
124
+ name: string;
125
+ status: string;
126
+ blockingMerge: boolean;
127
+ ownBlockNumber: number | null;
128
+ consecutiveErrors: number;
129
+ producerRestarts: number;
130
+ };
131
+ type HealthBody = {
132
+ status: string;
133
+ db: { sustained: boolean };
134
+ apply: {
135
+ blockHeight: number | null;
136
+ sinceLastAppliedMs: number | null;
137
+ lagMs: number | null;
138
+ };
139
+ protocols: HealthProtocol[];
140
+ };
141
+
142
+ async function getHealth(
143
+ port: number,
144
+ ): Promise<{ httpStatus: number; body: HealthBody }> {
145
+ const res = await fetch(`http://127.0.0.1:${port}/health`);
146
+ return { httpStatus: res.status, body: (await res.json()) as HealthBody };
147
+ }
148
+
149
+ let h: Harness;
150
+ let node: RunningNode | undefined;
151
+
152
+ beforeEach(async () => {
153
+ TestChainControl.clear();
154
+ process.env.EFFECTSTREAM_LAG_THRESHOLD_MS = String(LAG_THRESHOLD_MS);
155
+ h = await setupHarness();
156
+ });
157
+ afterEach(async () => {
158
+ await node?.stop();
159
+ node = undefined;
160
+ delete process.env.EFFECTSTREAM_LAG_THRESHOLD_MS;
161
+ await h?.teardown();
162
+ });
163
+
164
+ test("/health reports a stalled merge instead of a bare 'ok'", async () => {
165
+ TestChainControl.setTip(MAIN, MAIN_TIP);
166
+ TestChainControl.setTip(PAR_OK, OK_TIP);
167
+ // Pinned far behind: once the root timestamp passes this chain's tip, the
168
+ // merge blocks on its page and block production stops for good.
169
+ TestChainControl.setTip(PAR_STALLED, STALLED_TIP);
170
+
171
+ node = await h.runNode({ config: buildConfig(), apiPort: 19171 });
172
+
173
+ // Let the node apply what it can, then sit past the lag threshold.
174
+ await sleep(LAG_THRESHOLD_MS * 3);
175
+
176
+ const { httpStatus, body } = await getHealth(node.apiPort);
177
+
178
+ // The database is fine — this is exactly why the old db-only check passed.
179
+ expect(body.db.sustained).toBe(false);
180
+
181
+ // ...but the node has not applied a block in a long time. Measured in
182
+ // wall-clock time since the last apply, not block-timestamp lag: the
183
+ // synthetic chain's blocks are dated 2023, and a node replaying history is
184
+ // legitimately far behind in block time while being perfectly healthy.
185
+ expect(body.status).toBe("stalled");
186
+ expect(httpStatus).toBe(503);
187
+ expect(body.apply.sinceLastAppliedMs).toBeGreaterThan(LAG_THRESHOLD_MS);
188
+
189
+ // The report must name WHICH chain is holding up the merge, otherwise an
190
+ // operator has a stalled node and no idea where to look.
191
+ const stalled = body.protocols.find((p) => p.name === PAR_STALLED);
192
+ expect(stalled).toBeDefined();
193
+ expect(stalled!.blockingMerge).toBe(true);
194
+
195
+ // The healthy chains are still reported healthy — "stalled" is a property of
196
+ // the pipeline, not of every protocol in it.
197
+ const ok = body.protocols.find((p) => p.name === PAR_OK);
198
+ expect(ok).toBeDefined();
199
+ expect(ok!.blockingMerge).toBe(false);
200
+ expect(ok!.consecutiveErrors).toBe(0);
201
+ }, 120_000);
202
+
203
+ test("/health reports ok while blocks are flowing", async () => {
204
+ // All chains advancing: the merge is never gated, blocks keep applying.
205
+ TestChainControl.setTip(MAIN, MAIN_TIP);
206
+ TestChainControl.setTip(PAR_OK, OK_TIP);
207
+ TestChainControl.setTip(PAR_STALLED, OK_TIP);
208
+
209
+ node = await h.runNode({ config: buildConfig(), apiPort: 19172 });
210
+
211
+ // Poll: the node needs a moment to apply its first block, and once it does
212
+ // the status must be ok (not merely "not stalled").
213
+ let body: HealthBody | undefined;
214
+ let httpStatus = 0;
215
+ const deadline = Date.now() + 30_000;
216
+ while (Date.now() < deadline) {
217
+ ({ httpStatus, body } = await getHealth(node.apiPort));
218
+ if (body.status === "ok") break;
219
+ await sleep(100);
220
+ }
221
+
222
+ expect(body!.status).toBe("ok");
223
+ expect(httpStatus).toBe(200);
224
+ expect(body!.apply.blockHeight).toBeGreaterThan(0);
225
+ for (const p of body!.protocols) {
226
+ expect(p.consecutiveErrors).toBe(0);
227
+ expect(p.producerRestarts).toBe(0);
228
+ }
229
+ }, 120_000);