@serfab/cadre-host 0.10.0 → 0.12.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 (158) hide show
  1. package/README.md +406 -296
  2. package/dist/bin/host.d.ts +11 -7
  3. package/dist/bin/host.js +40 -12
  4. package/dist/bin/host.js.map +1 -1
  5. package/dist/installer/config.d.ts +4 -4
  6. package/dist/installer/config.js +5 -39
  7. package/dist/installer/config.js.map +1 -1
  8. package/dist/installer/identity.d.ts +8 -1
  9. package/dist/installer/identity.js +8 -1
  10. package/dist/installer/identity.js.map +1 -1
  11. package/dist/orchestrator/host-process-orchestrator.d.ts +2 -2
  12. package/dist/orchestrator/host-process-orchestrator.js +9 -4
  13. package/dist/orchestrator/host-process-orchestrator.js.map +1 -1
  14. package/dist/server/settings-store.d.ts +1 -1
  15. package/dist/server/settings-store.js +5 -1
  16. package/dist/server/settings-store.js.map +1 -1
  17. package/dist/server/static.js +38 -38
  18. package/dist/ui/assets/index-C-iks41M.js.map +1 -1
  19. package/dist/ui/index.html +12 -12
  20. package/package.json +4 -4
  21. package/service/cadre-host.service.tmpl +16 -16
  22. package/service/com.serfab.cadre-host.plist.tmpl +35 -35
  23. package/service/install-service.ps1 +98 -98
  24. package/service/uninstall-service.ps1 +19 -19
  25. package/src/__tests__/build-targets.test.ts +26 -26
  26. package/src/__tests__/cli-invite.smoke.test.ts +192 -192
  27. package/src/__tests__/cli-nat.smoke.test.ts +212 -212
  28. package/src/__tests__/cli.smoke.test.ts +51 -46
  29. package/src/__tests__/global-setup.ts +56 -51
  30. package/src/__tests__/host-owner.smoke.test.ts +123 -123
  31. package/src/__tests__/orchestrator-env-scrub.test.ts +140 -140
  32. package/src/__tests__/orchestrator-node-identity.test.ts +5 -5
  33. package/src/__tests__/orchestrator-owner.test.ts +198 -198
  34. package/src/__tests__/orchestrator-pin-keys.test.ts +153 -153
  35. package/src/__tests__/orchestrator-push.test.ts +145 -145
  36. package/src/__tests__/orchestrator.test.ts +951 -951
  37. package/src/auth/__tests__/duration.test.ts +28 -28
  38. package/src/auth/__tests__/self-label.test.ts +85 -85
  39. package/src/auth/__tests__/trust-circle-store.test.ts +115 -115
  40. package/src/auth/__tests__/trust-circle.test.ts +445 -445
  41. package/src/auth/duration.ts +33 -33
  42. package/src/auth/index.ts +21 -21
  43. package/src/auth/self-label.ts +74 -74
  44. package/src/auth/trust-circle-store.ts +155 -155
  45. package/src/auth/types.ts +99 -99
  46. package/src/bin/__tests__/cli-reference.test.ts +167 -0
  47. package/src/bin/host.ts +1326 -1299
  48. package/src/donation/__tests__/donation-service.test.ts +1068 -1068
  49. package/src/donation/__tests__/donation-supervisor.test.ts +510 -510
  50. package/src/donation/__tests__/fake-orchestrator.test.ts +168 -168
  51. package/src/donation/__tests__/fake-orchestrator.ts +225 -225
  52. package/src/donation/__tests__/grant-service.test.ts +213 -213
  53. package/src/donation/__tests__/grant-store.test.ts +113 -113
  54. package/src/donation/donation-service.ts +962 -962
  55. package/src/donation/donation-store.ts +171 -171
  56. package/src/donation/donation-supervisor.ts +388 -388
  57. package/src/donation/grant-service.ts +200 -200
  58. package/src/donation/grant-store.ts +152 -152
  59. package/src/donation/index.ts +64 -64
  60. package/src/donation/types.ts +243 -243
  61. package/src/installer/__tests__/config.test.ts +134 -112
  62. package/src/installer/__tests__/identity.test.ts +34 -34
  63. package/src/installer/__tests__/paths.test.ts +47 -47
  64. package/src/installer/__tests__/service-host.test.ts +62 -62
  65. package/src/installer/__tests__/wizard.test.ts +64 -64
  66. package/src/installer/config.ts +5 -43
  67. package/src/installer/identity.ts +56 -49
  68. package/src/installer/paths.ts +109 -109
  69. package/src/installer/platform.ts +27 -27
  70. package/src/installer/service-host/index.ts +21 -21
  71. package/src/installer/service-host/template.ts +21 -21
  72. package/src/installer/wizard.ts +103 -103
  73. package/src/nat/__tests__/address-resolver.test.ts +82 -82
  74. package/src/nat/__tests__/ddns-duckdns.test.ts +83 -83
  75. package/src/nat/__tests__/ddns-updater.test.ts +253 -253
  76. package/src/nat/__tests__/external-ip.test.ts +124 -124
  77. package/src/nat/__tests__/nat-service.test.ts +18 -0
  78. package/src/nat/__tests__/nat-store.test.ts +93 -93
  79. package/src/nat/__tests__/port-mapper.test.ts +191 -191
  80. package/src/nat/__tests__/reachability.test.ts +24 -24
  81. package/src/nat/__tests__/secrets.test.ts +178 -178
  82. package/src/nat/address-resolver.ts +51 -51
  83. package/src/nat/ddns/duckdns.ts +76 -76
  84. package/src/nat/ddns/index.ts +55 -55
  85. package/src/nat/ddns/updater.ts +243 -243
  86. package/src/nat/external-ip.ts +154 -154
  87. package/src/nat/index.ts +71 -71
  88. package/src/nat/nat-service.ts +501 -501
  89. package/src/nat/nat-store.ts +154 -154
  90. package/src/nat/port-mapper.ts +329 -329
  91. package/src/nat/reachability.ts +34 -34
  92. package/src/nat/secrets/file-store.ts +130 -130
  93. package/src/nat/secrets/index.ts +112 -112
  94. package/src/nat/secrets/keytar-store.ts +67 -67
  95. package/src/nat/types.ts +159 -159
  96. package/src/orchestrator/__tests__/node-identity.test.ts +62 -62
  97. package/src/orchestrator/host-process-orchestrator.ts +9 -4
  98. package/src/orchestrator/index.ts +10 -10
  99. package/src/orchestrator/log-rotator.ts +53 -53
  100. package/src/orchestrator/node-identity.ts +40 -40
  101. package/src/orchestrator/pid-liveness.ts +24 -24
  102. package/src/orchestrator/port-allocator.ts +91 -91
  103. package/src/orchestrator/state-store.ts +90 -90
  104. package/src/orchestrator/types.ts +141 -141
  105. package/src/owner/__tests__/owner-node-client.test.ts +194 -194
  106. package/src/owner/index.ts +12 -12
  107. package/src/owner/owner-node-client.ts +259 -259
  108. package/src/push/__tests__/push.test.ts +90 -90
  109. package/src/push/index.ts +146 -146
  110. package/src/server/__tests__/bus.test.ts +38 -38
  111. package/src/server/__tests__/error-handler.test.ts +118 -118
  112. package/src/server/__tests__/grants-admin-route.test.ts +73 -73
  113. package/src/server/__tests__/grants-route.test.ts +263 -263
  114. package/src/server/__tests__/nodes-route.test.ts +259 -259
  115. package/src/server/__tests__/origin-guard.test.ts +72 -72
  116. package/src/server/__tests__/publishers.test.ts +216 -216
  117. package/src/server/__tests__/server.smoke.test.ts +253 -253
  118. package/src/server/__tests__/settings-route.test.ts +195 -194
  119. package/src/server/__tests__/sse-route.test.ts +119 -119
  120. package/src/server/__tests__/static.test.ts +145 -145
  121. package/src/server/__tests__/status-route.test.ts +134 -134
  122. package/src/server/__tests__/strands-route.test.ts +233 -233
  123. package/src/server/error-handler.ts +178 -178
  124. package/src/server/events/bus.ts +42 -42
  125. package/src/server/events/sse-route.ts +81 -81
  126. package/src/server/events/types.ts +23 -23
  127. package/src/server/index.ts +267 -267
  128. package/src/server/origin-guard.ts +84 -84
  129. package/src/server/routes/grants-admin.ts +41 -41
  130. package/src/server/routes/grants.ts +210 -210
  131. package/src/server/routes/nat.ts +63 -63
  132. package/src/server/routes/nodes.ts +170 -170
  133. package/src/server/routes/settings.ts +123 -123
  134. package/src/server/routes/status.ts +118 -118
  135. package/src/server/routes/strands.ts +54 -54
  136. package/src/server/routes/trust-circle.ts +49 -49
  137. package/src/server/routes/update.ts +43 -43
  138. package/src/server/server.ts +122 -122
  139. package/src/server/settings-store.ts +5 -1
  140. package/src/server/static.ts +207 -207
  141. package/src/strands/__tests__/strand-service.test.ts +165 -165
  142. package/src/strands/index.ts +14 -14
  143. package/src/strands/strand-service.ts +135 -135
  144. package/src/strands/types.ts +102 -102
  145. package/src/update/__tests__/apply.test.ts +158 -158
  146. package/src/update/__tests__/manifest.test.ts +128 -128
  147. package/src/update/__tests__/release-key.test.ts +42 -42
  148. package/src/update/__tests__/sign.test.ts +78 -78
  149. package/src/update/__tests__/store.test.ts +81 -81
  150. package/src/update/__tests__/update-service.integration.test.ts +256 -256
  151. package/src/update/__tests__/version.test.ts +31 -31
  152. package/src/update/apply.ts +190 -190
  153. package/src/update/index.ts +341 -341
  154. package/src/update/release-key.ts +71 -71
  155. package/src/update/sign.ts +74 -74
  156. package/src/update/store.ts +101 -101
  157. package/src/update/types.ts +109 -109
  158. package/src/update/version.ts +80 -80
@@ -1,510 +1,510 @@
1
- /**
2
- * DonationSupervisor unit tests — the component that notices a donated node is
3
- * no longer running and calls `DonationService.respawn`, backs off between
4
- * attempts, and eventually gives up.
5
- *
6
- * Exercised against the shared `FakeOrchestrator` (no real child processes), a
7
- * real on-disk `DonationStore`, and an injected clock — so backoff and the
8
- * healthy-reset window are asserted without any wall-clock waiting.
9
- *
10
- * What is NOT covered here: that a really-respawned child rejoins the borrower's
11
- * cadre. That needs the cross-package `cadre-host-node-donation` integration
12
- * scenario.
13
- */
14
-
15
- import { afterEach, beforeEach, describe, expect, it } from 'vitest';
16
- import { mkdtempSync, rmSync } from 'node:fs';
17
- import { tmpdir } from 'node:os';
18
- import { join } from 'node:path';
19
-
20
- import type { ManagedNodeInfo } from '../../orchestrator/types.js';
21
- import { DonationService } from '../donation-service.js';
22
- import { DonationStore } from '../donation-store.js';
23
- import {
24
- DonationSupervisor,
25
- DONATION_RESPAWN_HEALTHY_MS,
26
- DONATION_RESPAWN_MAX_ATTEMPTS,
27
- } from '../donation-supervisor.js';
28
- import { GrantService } from '../grant-service.js';
29
- import { GrantStore } from '../grant-store.js';
30
- import type { Donation, DonationView } from '../types.js';
31
- import { DonationError } from '../types.js';
32
- import { FakeOrchestrator } from './fake-orchestrator.js';
33
-
34
- let tmpRoot: string;
35
-
36
- /**
37
- * A well-formed 32-byte base64url owner key. `DonationService.provision`
38
- * shape-checks the pins at the boundary, so a placeholder string no longer stands
39
- * in for one.
40
- */
41
- const OWNER_KEY = Buffer.alloc(32, 7).toString('base64url');
42
-
43
- beforeEach(() => {
44
- tmpRoot = mkdtempSync(join(tmpdir(), 'cadre-host-donation-sup-'));
45
- });
46
-
47
- afterEach(() => {
48
- try { rmSync(tmpRoot, { recursive: true, force: true }); } catch { /* ignore */ }
49
- });
50
-
51
- /** Everything one test needs, sharing a single mutable clock. */
52
- interface Harness {
53
- orch: FakeOrchestrator;
54
- store: DonationStore;
55
- service: DonationService;
56
- supervisor: DonationSupervisor;
57
- /** Move the shared clock forward. */
58
- advance: (ms: number) => void;
59
- nowMs: () => number;
60
- /** Provision one donation. */
61
- provision: () => Promise<DonationView>;
62
- }
63
-
64
- const START_MS = Date.parse('2026-01-01T00:00:00.000Z');
65
-
66
- function makeHarness(): Harness {
67
- let nowMs = START_MS;
68
- const now = (): Date => new Date(nowMs);
69
-
70
- const orch = new FakeOrchestrator();
71
- const store = new DonationStore(join(tmpRoot, 'donations'));
72
- const grants = new GrantService({ store: new GrantStore(join(tmpRoot, 'grants')) });
73
- const token = grants.issue({ label: 'Alice', maxNodes: 10 }).token;
74
- const service = new DonationService({ orchestrator: orch, grants, store, now });
75
- const supervisor = new DonationSupervisor({ service, store, orchestrator: orch, now });
76
-
77
- return {
78
- orch,
79
- store,
80
- service,
81
- supervisor,
82
- advance: (ms) => { nowMs += ms; },
83
- nowMs: () => nowMs,
84
- provision: () => service.provision({
85
- grantToken: token,
86
- partyId: 'party-P',
87
- bootstrapNodes: ['/ip4/127.0.0.1/tcp/4001/p2p/12D3KooReq'],
88
- ownerKeys: [OWNER_KEY],
89
- }),
90
- };
91
- }
92
-
93
- /** Force a record's status without going through the (fetch-driven) seed path. */
94
- function setStatus(store: DonationStore, id: string, status: Donation['status']): void {
95
- store.put({ ...requireDonation(store, id), status });
96
- }
97
-
98
- function requireDonation(store: DonationStore, id: string): Donation {
99
- const donation = store.get(id);
100
- if (!donation) throw new Error(`no donation ${id}`);
101
- return donation;
102
- }
103
-
104
- function dockerIdOf(donation: { dockerId?: string }): string {
105
- if (!donation.dockerId) throw new Error('donation has no dockerId');
106
- return donation.dockerId;
107
- }
108
-
109
- /** Let queued fire-and-forget passes run. */
110
- function flush(): Promise<void> {
111
- return new Promise((res) => setTimeout(res, 5));
112
- }
113
-
114
- /** A store whose every read fails — a malformed `donations.json` on disk. */
115
- class UnreadableDonationStore extends DonationStore {
116
- override list(): Donation[] {
117
- throw new DonationError('storage_error', 'donations file is not valid JSON');
118
- }
119
- }
120
-
121
- describe('DonationSupervisor.reconcile', () => {
122
- it('respawns a seeded-but-stopped node, keeping its status and swapping its handle', async () => {
123
- const h = makeHarness();
124
- const view = await h.provision();
125
- setStatus(h.store, view.id, 'seeded');
126
- h.orch.crash(dockerIdOf(view));
127
-
128
- const respawned = await h.supervisor.reconcile();
129
-
130
- expect(respawned).toEqual([view.id]);
131
- const stored = requireDonation(h.store, view.id);
132
- expect(stored.dockerId).toBe('dock_2');
133
- expect(stored.dockerId).not.toBe(view.dockerId);
134
- // A seeded node needs no re-seeding — the loan is still live.
135
- expect(stored.status).toBe('seeded');
136
- // Fresh host↔node bearer for the new child.
137
- expect(stored.seedToken).toBe('seed-token-2');
138
- expect(h.orch.createCalls).toHaveLength(2);
139
- });
140
-
141
- it('leaves a running node alone', async () => {
142
- const h = makeHarness();
143
- const view = await h.provision();
144
- setStatus(h.store, view.id, 'seeded');
145
-
146
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
147
- expect(h.orch.createCalls).toHaveLength(1);
148
- });
149
-
150
- it('never respawns a terminated loan', async () => {
151
- const h = makeHarness();
152
- const view = await h.provision();
153
- setStatus(h.store, view.id, 'seeded');
154
- await h.service.terminate(view.id);
155
-
156
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
157
- expect(h.orch.createCalls).toHaveLength(1);
158
- expect(requireDonation(h.store, view.id).status).toBe('terminated');
159
- });
160
-
161
- it('respawns a stopped awaiting_seed node so the borrower can still seed it', async () => {
162
- const h = makeHarness();
163
- const view = await h.provision();
164
- h.orch.crash(dockerIdOf(view));
165
-
166
- await expect(h.supervisor.reconcile()).resolves.toEqual([view.id]);
167
- const stored = requireDonation(h.store, view.id);
168
- expect(stored.status).toBe('awaiting_seed');
169
- expect(stored.seedEndpoint).toContain('9002');
170
- });
171
-
172
- it('honours the backoff window, then attempts again once the clock passes it', async () => {
173
- const h = makeHarness();
174
- const view = await h.provision();
175
- setStatus(h.store, view.id, 'seeded');
176
- h.orch.crash(dockerIdOf(view));
177
- h.orch.failCreate = true;
178
-
179
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
180
- expect(h.orch.createCalls).toHaveLength(2);
181
- expect(requireDonation(h.store, view.id).respawn?.attempts).toBe(1);
182
-
183
- // attempts = 1 → base * 2^1 = 10s. One second later is still too soon.
184
- h.advance(1_000);
185
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
186
- expect(h.orch.createCalls).toHaveLength(2);
187
- expect(requireDonation(h.store, view.id).respawn?.attempts).toBe(1);
188
-
189
- h.advance(10_000);
190
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
191
- expect(h.orch.createCalls).toHaveLength(3);
192
- expect(requireDonation(h.store, view.id).respawn?.attempts).toBe(2);
193
- });
194
-
195
- it('gives up after the attempt cap: record → error, child stopped but not reclaimed', async () => {
196
- const h = makeHarness();
197
- const view = await h.provision();
198
- setStatus(h.store, view.id, 'seeded');
199
- h.orch.crash(dockerIdOf(view));
200
- h.orch.failCreate = true;
201
-
202
- for (let i = 0; i < DONATION_RESPAWN_MAX_ATTEMPTS; i++) {
203
- await h.supervisor.reconcile();
204
- // Well past the longest backoff, so every pass gets to attempt.
205
- h.advance(10 * 60_000);
206
- }
207
-
208
- const stored = requireDonation(h.store, view.id);
209
- expect(stored.status).toBe('error');
210
- expect(stored.respawn?.attempts).toBe(DONATION_RESPAWN_MAX_ATTEMPTS);
211
- expect(stored.error).toContain(`${DONATION_RESPAWN_MAX_ATTEMPTS} attempts`);
212
- expect(stored.error).toContain('spawn boom');
213
- // The workdir holds the identity key the borrower's cadre approved — the
214
- // give-up path stops the child but must never reclaim it.
215
- //
216
- // Doubles as the standing guard on `FakeOrchestrator`'s drop being
217
- // success-only (mirroring `restoreDroppedHandles`): every create here fails,
218
- // so a fake that dropped the prior handle regardless would leave `giveUp`
219
- // with nothing to stop, and this line fails with
220
- // `expected [] to include 'dock_1'`.
221
- expect(h.orch.stopped).toContain(view.dockerId);
222
- expect(h.orch.removed).toEqual([]);
223
-
224
- // `error` is terminal: no further attempts, and the grant's quota is freed.
225
- const createsAtGiveUp = h.orch.createCalls.length;
226
- h.advance(10 * 60_000);
227
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
228
- expect(h.orch.createCalls).toHaveLength(createsAtGiveUp);
229
- expect(h.store.liveNodeCount(stored.grantToken)).toBe(0);
230
- });
231
-
232
- it('refills the attempt budget once a respawned node has stayed up', async () => {
233
- const h = makeHarness();
234
- const view = await h.provision();
235
- const provisioned = requireDonation(h.store, view.id);
236
- h.store.put({
237
- ...provisioned,
238
- status: 'seeded',
239
- respawn: { attempts: 3, lastAttemptAt: new Date(h.nowMs()).toISOString() },
240
- });
241
-
242
- // Still inside the healthy window — the crash loop's count stands.
243
- h.advance(DONATION_RESPAWN_HEALTHY_MS - 1_000);
244
- await h.supervisor.reconcile();
245
- expect(requireDonation(h.store, view.id).respawn?.attempts).toBe(3);
246
-
247
- h.advance(2_000);
248
- await h.supervisor.reconcile();
249
- expect(requireDonation(h.store, view.id).respawn?.attempts).toBe(0);
250
- // A liveness observation is not borrower activity — the stale-awaiting_seed
251
- // reap's clock must not be pushed forward by it.
252
- expect(requireDonation(h.store, view.id).updatedAt).toBe(provisioned.updatedAt);
253
- });
254
-
255
- it('skips a record that predates persisted spawn inputs without ending the sweep', async () => {
256
- const h = makeHarness();
257
- // Written first, so a throw here would starve the respawnable record below.
258
- h.store.put({
259
- id: 'grn_legacy',
260
- grantToken: 'tok-legacy',
261
- partyId: 'party-old',
262
- profile: 'storage',
263
- status: 'seeded',
264
- dockerId: 'dock_gone',
265
- createdAt: new Date(START_MS).toISOString(),
266
- updatedAt: new Date(START_MS).toISOString(),
267
- });
268
-
269
- const view = await h.provision();
270
- setStatus(h.store, view.id, 'seeded');
271
- h.orch.crash(dockerIdOf(view));
272
-
273
- await expect(h.supervisor.reconcile()).resolves.toEqual([view.id]);
274
- const legacy = requireDonation(h.store, 'grn_legacy');
275
- expect(legacy.status).toBe('seeded');
276
- expect(legacy.respawn).toBeUndefined();
277
- });
278
-
279
- it('leaves a still-provisioning record alone — provision owns that child', async () => {
280
- const h = makeHarness();
281
- // A handle written by a provision that has not yet flipped to awaiting_seed.
282
- // Respawning it here would race that provision and strand the record.
283
- h.store.put({
284
- id: 'grn_inflight',
285
- grantToken: 'tok',
286
- partyId: 'party-P',
287
- bootstrapNodes: ['/ip4/127.0.0.1/tcp/4001/p2p/12D3KooReq'],
288
- ownerKeys: [OWNER_KEY],
289
- profile: 'storage',
290
- status: 'provisioning',
291
- dockerId: 'dock_inflight',
292
- createdAt: new Date(START_MS).toISOString(),
293
- updatedAt: new Date(START_MS).toISOString(),
294
- });
295
-
296
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
297
- expect(h.orch.createCalls).toEqual([]);
298
- expect(requireDonation(h.store, 'grn_inflight').status).toBe('provisioning');
299
- });
300
-
301
- it('skips a record that has no orchestrator handle yet', async () => {
302
- const h = makeHarness();
303
- h.store.put({
304
- id: 'grn_nohandle',
305
- grantToken: 'tok',
306
- partyId: 'party-P',
307
- bootstrapNodes: ['/ip4/127.0.0.1/tcp/4001/p2p/12D3KooReq'],
308
- ownerKeys: [OWNER_KEY],
309
- profile: 'storage',
310
- status: 'awaiting_seed',
311
- createdAt: new Date(START_MS).toISOString(),
312
- updatedAt: new Date(START_MS).toISOString(),
313
- });
314
-
315
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
316
- expect(h.orch.createCalls).toEqual([]);
317
- });
318
-
319
- it('does not undo a seed that lands while the pass is mid-flight', async () => {
320
- const h = makeHarness();
321
- const view = await h.provision();
322
- const provisioned = requireDonation(h.store, view.id);
323
- h.store.put({
324
- ...provisioned,
325
- respawn: { attempts: 3, lastAttemptAt: new Date(h.nowMs()).toISOString() },
326
- });
327
- h.advance(DONATION_RESPAWN_HEALTHY_MS + 1_000);
328
-
329
- // The borrower's seed lands between the pass's store snapshot and the
330
- // budget-refill write — the refill must merge, not replay a stale row.
331
- h.orch.onIsRunning = () => {
332
- h.orch.onIsRunning = undefined;
333
- h.store.put({
334
- ...requireDonation(h.store, view.id),
335
- status: 'seeded',
336
- updatedAt: new Date(h.nowMs()).toISOString(),
337
- });
338
- };
339
-
340
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
341
- const stored = requireDonation(h.store, view.id);
342
- expect(stored.status).toBe('seeded');
343
- expect(stored.respawn?.attempts).toBe(0);
344
- });
345
-
346
- it('leaves a record that went terminal mid-attempt alone instead of marking it error', async () => {
347
- const h = makeHarness();
348
- const view = await h.provision();
349
- h.store.put({
350
- ...requireDonation(h.store, view.id),
351
- status: 'seeded',
352
- // Already at the cap, and long past the longest backoff — so the next
353
- // failure lands straight in the give-up path.
354
- respawn: {
355
- attempts: DONATION_RESPAWN_MAX_ATTEMPTS,
356
- lastAttemptAt: new Date(h.nowMs() - 10 * 60_000).toISOString(),
357
- },
358
- });
359
- h.orch.crash(dockerIdOf(view));
360
- h.orch.failCreate = true;
361
- // The reap terminates the loan while the respawn's spawn is in flight.
362
- h.orch.onCreate = () => {
363
- h.store.put({ ...requireDonation(h.store, view.id), status: 'terminated' });
364
- };
365
-
366
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
367
-
368
- const stored = requireDonation(h.store, view.id);
369
- // The borrower ended this loan — a host give-up must not rewrite that.
370
- expect(stored.status).toBe('terminated');
371
- expect(stored.error).toBeUndefined();
372
- // The attempt counter is the one thing the failed attempt may still record.
373
- expect(stored.respawn?.attempts).toBe(DONATION_RESPAWN_MAX_ATTEMPTS + 1);
374
- expect(h.orch.stopped).toEqual([]);
375
- });
376
-
377
- it('does not count a respawn abandoned mid-spawn as a failed attempt', async () => {
378
- const h = makeHarness();
379
- const view = await h.provision();
380
- h.store.put({
381
- ...requireDonation(h.store, view.id),
382
- status: 'seeded',
383
- // Already at the cap and long past the longest backoff, so a *failed*
384
- // attempt here would land straight in the give-up path.
385
- respawn: {
386
- attempts: DONATION_RESPAWN_MAX_ATTEMPTS,
387
- lastAttemptAt: new Date(h.nowMs() - 10 * 60_000).toISOString(),
388
- },
389
- });
390
- h.orch.crash(dockerIdOf(view));
391
- // The borrower ends the loan while the respawn's spawn is in flight.
392
- h.orch.createDelayMs = 20;
393
- let terminated: Promise<void> | undefined;
394
- h.orch.onCreate = () => { terminated ??= h.service.terminate(view.id); };
395
-
396
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
397
- await terminated;
398
-
399
- const stored = requireDonation(h.store, view.id);
400
- // Nothing threw, so no attempt was persisted and give-up never ran.
401
- expect(stored.status).toBe('terminated');
402
- expect(stored.error).toBeUndefined();
403
- expect(stored.respawn?.attempts).toBe(DONATION_RESPAWN_MAX_ATTEMPTS);
404
- expect(stored.dockerId).toBe(view.dockerId);
405
- // The abandoned child is stopped and reclaimed, not left holding ports.
406
- expect(h.orch.stopped).toContain('dock_2');
407
- expect(h.orch.removed).toContain('dock_2');
408
- });
409
-
410
- it('survives a pass over a store it cannot read', async () => {
411
- const orch = new FakeOrchestrator();
412
- const store = new UnreadableDonationStore(join(tmpRoot, 'donations'));
413
- const grants = new GrantService({ store: new GrantStore(join(tmpRoot, 'grants')) });
414
- const service = new DonationService({ orchestrator: orch, grants, store });
415
- const supervisor = new DonationSupervisor({ service, store, orchestrator: orch });
416
-
417
- await expect(supervisor.reconcile()).resolves.toEqual([]);
418
- expect(orch.createCalls).toEqual([]);
419
- });
420
-
421
- it('serializes overlapping passes so one id is never double-spawned', async () => {
422
- const h = makeHarness();
423
- const view = await h.provision();
424
- setStatus(h.store, view.id, 'seeded');
425
- h.orch.crash(dockerIdOf(view));
426
- h.orch.createDelayMs = 20;
427
-
428
- const [first, second] = await Promise.all([
429
- h.supervisor.reconcile(),
430
- h.supervisor.reconcile(),
431
- ]);
432
-
433
- // Whichever pass wins the tail respawns; the other then finds it running.
434
- expect([...first, ...second]).toEqual([view.id]);
435
- // The original provision plus exactly one respawn.
436
- expect(h.orch.createCalls).toHaveLength(2);
437
- });
438
- });
439
-
440
- describe('DonationSupervisor start/stop', () => {
441
- it('sweeps at startup and again on a donated child exit', async () => {
442
- const h = makeHarness();
443
- const view = await h.provision();
444
- setStatus(h.store, view.id, 'seeded');
445
- h.orch.crash(dockerIdOf(view));
446
-
447
- h.supervisor.start();
448
- try {
449
- // Queued behind the startup pass, so awaiting it proves that pass ran.
450
- await h.supervisor.reconcile();
451
- expect(requireDonation(h.store, view.id).dockerId).toBe('dock_2');
452
-
453
- // Now the exit-event trigger, with no manual reconcile in between.
454
- h.advance(60_000);
455
- h.orch.crash('dock_2');
456
- await flush();
457
- expect(requireDonation(h.store, view.id).dockerId).toBe('dock_3');
458
- } finally {
459
- h.supervisor.stop();
460
- }
461
- });
462
-
463
- it('ignores owner-node exits — bin/host.ts owns re-spawning that one', async () => {
464
- const h = makeHarness();
465
- const view = await h.provision();
466
- setStatus(h.store, view.id, 'seeded');
467
-
468
- h.supervisor.start();
469
- try {
470
- await h.supervisor.reconcile(); // drain the startup pass (node is running)
471
- // Take the node down WITHOUT an exit event, so the only event in play is
472
- // the owner's.
473
- await h.orch.stopContainer(dockerIdOf(view));
474
-
475
- const ownerExit: ManagedNodeInfo = {
476
- id: 'owner',
477
- dockerId: 'dock_owner',
478
- partyId: 'host-party',
479
- profile: 'storage',
480
- status: 'stopped',
481
- spawnedAt: new Date(START_MS).toISOString(),
482
- workdir: '/fake/owner',
483
- ports: { health: 0, metrics: 0, p2p: 0, admin: 0 },
484
- owner: true,
485
- };
486
- h.orch.emit(ownerExit);
487
- await flush();
488
-
489
- expect(h.orch.createCalls).toHaveLength(1);
490
- expect(requireDonation(h.store, view.id).dockerId).toBe(view.dockerId);
491
- } finally {
492
- h.supervisor.stop();
493
- }
494
- });
495
-
496
- it('stops reacting to exits after stop()', async () => {
497
- const h = makeHarness();
498
- const view = await h.provision();
499
- setStatus(h.store, view.id, 'seeded');
500
-
501
- h.supervisor.start();
502
- await h.supervisor.reconcile();
503
- h.supervisor.stop();
504
-
505
- h.orch.crash(dockerIdOf(view));
506
- await flush();
507
- // The exit listener is gone, so the crash goes unnoticed until the next start.
508
- expect(requireDonation(h.store, view.id).dockerId).toBe(view.dockerId);
509
- });
510
- });
1
+ /**
2
+ * DonationSupervisor unit tests — the component that notices a donated node is
3
+ * no longer running and calls `DonationService.respawn`, backs off between
4
+ * attempts, and eventually gives up.
5
+ *
6
+ * Exercised against the shared `FakeOrchestrator` (no real child processes), a
7
+ * real on-disk `DonationStore`, and an injected clock — so backoff and the
8
+ * healthy-reset window are asserted without any wall-clock waiting.
9
+ *
10
+ * What is NOT covered here: that a really-respawned child rejoins the borrower's
11
+ * cadre. That needs the cross-package `cadre-host-node-donation` integration
12
+ * scenario.
13
+ */
14
+
15
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
16
+ import { mkdtempSync, rmSync } from 'node:fs';
17
+ import { tmpdir } from 'node:os';
18
+ import { join } from 'node:path';
19
+
20
+ import type { ManagedNodeInfo } from '../../orchestrator/types.js';
21
+ import { DonationService } from '../donation-service.js';
22
+ import { DonationStore } from '../donation-store.js';
23
+ import {
24
+ DonationSupervisor,
25
+ DONATION_RESPAWN_HEALTHY_MS,
26
+ DONATION_RESPAWN_MAX_ATTEMPTS,
27
+ } from '../donation-supervisor.js';
28
+ import { GrantService } from '../grant-service.js';
29
+ import { GrantStore } from '../grant-store.js';
30
+ import type { Donation, DonationView } from '../types.js';
31
+ import { DonationError } from '../types.js';
32
+ import { FakeOrchestrator } from './fake-orchestrator.js';
33
+
34
+ let tmpRoot: string;
35
+
36
+ /**
37
+ * A well-formed 32-byte base64url owner key. `DonationService.provision`
38
+ * shape-checks the pins at the boundary, so a placeholder string no longer stands
39
+ * in for one.
40
+ */
41
+ const OWNER_KEY = Buffer.alloc(32, 7).toString('base64url');
42
+
43
+ beforeEach(() => {
44
+ tmpRoot = mkdtempSync(join(tmpdir(), 'cadre-host-donation-sup-'));
45
+ });
46
+
47
+ afterEach(() => {
48
+ try { rmSync(tmpRoot, { recursive: true, force: true }); } catch { /* ignore */ }
49
+ });
50
+
51
+ /** Everything one test needs, sharing a single mutable clock. */
52
+ interface Harness {
53
+ orch: FakeOrchestrator;
54
+ store: DonationStore;
55
+ service: DonationService;
56
+ supervisor: DonationSupervisor;
57
+ /** Move the shared clock forward. */
58
+ advance: (ms: number) => void;
59
+ nowMs: () => number;
60
+ /** Provision one donation. */
61
+ provision: () => Promise<DonationView>;
62
+ }
63
+
64
+ const START_MS = Date.parse('2026-01-01T00:00:00.000Z');
65
+
66
+ function makeHarness(): Harness {
67
+ let nowMs = START_MS;
68
+ const now = (): Date => new Date(nowMs);
69
+
70
+ const orch = new FakeOrchestrator();
71
+ const store = new DonationStore(join(tmpRoot, 'donations'));
72
+ const grants = new GrantService({ store: new GrantStore(join(tmpRoot, 'grants')) });
73
+ const token = grants.issue({ label: 'Alice', maxNodes: 10 }).token;
74
+ const service = new DonationService({ orchestrator: orch, grants, store, now });
75
+ const supervisor = new DonationSupervisor({ service, store, orchestrator: orch, now });
76
+
77
+ return {
78
+ orch,
79
+ store,
80
+ service,
81
+ supervisor,
82
+ advance: (ms) => { nowMs += ms; },
83
+ nowMs: () => nowMs,
84
+ provision: () => service.provision({
85
+ grantToken: token,
86
+ partyId: 'party-P',
87
+ bootstrapNodes: ['/ip4/127.0.0.1/tcp/4001/p2p/12D3KooReq'],
88
+ ownerKeys: [OWNER_KEY],
89
+ }),
90
+ };
91
+ }
92
+
93
+ /** Force a record's status without going through the (fetch-driven) seed path. */
94
+ function setStatus(store: DonationStore, id: string, status: Donation['status']): void {
95
+ store.put({ ...requireDonation(store, id), status });
96
+ }
97
+
98
+ function requireDonation(store: DonationStore, id: string): Donation {
99
+ const donation = store.get(id);
100
+ if (!donation) throw new Error(`no donation ${id}`);
101
+ return donation;
102
+ }
103
+
104
+ function dockerIdOf(donation: { dockerId?: string }): string {
105
+ if (!donation.dockerId) throw new Error('donation has no dockerId');
106
+ return donation.dockerId;
107
+ }
108
+
109
+ /** Let queued fire-and-forget passes run. */
110
+ function flush(): Promise<void> {
111
+ return new Promise((res) => setTimeout(res, 5));
112
+ }
113
+
114
+ /** A store whose every read fails — a malformed `donations.json` on disk. */
115
+ class UnreadableDonationStore extends DonationStore {
116
+ override list(): Donation[] {
117
+ throw new DonationError('storage_error', 'donations file is not valid JSON');
118
+ }
119
+ }
120
+
121
+ describe('DonationSupervisor.reconcile', () => {
122
+ it('respawns a seeded-but-stopped node, keeping its status and swapping its handle', async () => {
123
+ const h = makeHarness();
124
+ const view = await h.provision();
125
+ setStatus(h.store, view.id, 'seeded');
126
+ h.orch.crash(dockerIdOf(view));
127
+
128
+ const respawned = await h.supervisor.reconcile();
129
+
130
+ expect(respawned).toEqual([view.id]);
131
+ const stored = requireDonation(h.store, view.id);
132
+ expect(stored.dockerId).toBe('dock_2');
133
+ expect(stored.dockerId).not.toBe(view.dockerId);
134
+ // A seeded node needs no re-seeding — the loan is still live.
135
+ expect(stored.status).toBe('seeded');
136
+ // Fresh host↔node bearer for the new child.
137
+ expect(stored.seedToken).toBe('seed-token-2');
138
+ expect(h.orch.createCalls).toHaveLength(2);
139
+ });
140
+
141
+ it('leaves a running node alone', async () => {
142
+ const h = makeHarness();
143
+ const view = await h.provision();
144
+ setStatus(h.store, view.id, 'seeded');
145
+
146
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
147
+ expect(h.orch.createCalls).toHaveLength(1);
148
+ });
149
+
150
+ it('never respawns a terminated loan', async () => {
151
+ const h = makeHarness();
152
+ const view = await h.provision();
153
+ setStatus(h.store, view.id, 'seeded');
154
+ await h.service.terminate(view.id);
155
+
156
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
157
+ expect(h.orch.createCalls).toHaveLength(1);
158
+ expect(requireDonation(h.store, view.id).status).toBe('terminated');
159
+ });
160
+
161
+ it('respawns a stopped awaiting_seed node so the borrower can still seed it', async () => {
162
+ const h = makeHarness();
163
+ const view = await h.provision();
164
+ h.orch.crash(dockerIdOf(view));
165
+
166
+ await expect(h.supervisor.reconcile()).resolves.toEqual([view.id]);
167
+ const stored = requireDonation(h.store, view.id);
168
+ expect(stored.status).toBe('awaiting_seed');
169
+ expect(stored.seedEndpoint).toContain('9002');
170
+ });
171
+
172
+ it('honours the backoff window, then attempts again once the clock passes it', async () => {
173
+ const h = makeHarness();
174
+ const view = await h.provision();
175
+ setStatus(h.store, view.id, 'seeded');
176
+ h.orch.crash(dockerIdOf(view));
177
+ h.orch.failCreate = true;
178
+
179
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
180
+ expect(h.orch.createCalls).toHaveLength(2);
181
+ expect(requireDonation(h.store, view.id).respawn?.attempts).toBe(1);
182
+
183
+ // attempts = 1 → base * 2^1 = 10s. One second later is still too soon.
184
+ h.advance(1_000);
185
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
186
+ expect(h.orch.createCalls).toHaveLength(2);
187
+ expect(requireDonation(h.store, view.id).respawn?.attempts).toBe(1);
188
+
189
+ h.advance(10_000);
190
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
191
+ expect(h.orch.createCalls).toHaveLength(3);
192
+ expect(requireDonation(h.store, view.id).respawn?.attempts).toBe(2);
193
+ });
194
+
195
+ it('gives up after the attempt cap: record → error, child stopped but not reclaimed', async () => {
196
+ const h = makeHarness();
197
+ const view = await h.provision();
198
+ setStatus(h.store, view.id, 'seeded');
199
+ h.orch.crash(dockerIdOf(view));
200
+ h.orch.failCreate = true;
201
+
202
+ for (let i = 0; i < DONATION_RESPAWN_MAX_ATTEMPTS; i++) {
203
+ await h.supervisor.reconcile();
204
+ // Well past the longest backoff, so every pass gets to attempt.
205
+ h.advance(10 * 60_000);
206
+ }
207
+
208
+ const stored = requireDonation(h.store, view.id);
209
+ expect(stored.status).toBe('error');
210
+ expect(stored.respawn?.attempts).toBe(DONATION_RESPAWN_MAX_ATTEMPTS);
211
+ expect(stored.error).toContain(`${DONATION_RESPAWN_MAX_ATTEMPTS} attempts`);
212
+ expect(stored.error).toContain('spawn boom');
213
+ // The workdir holds the identity key the borrower's cadre approved — the
214
+ // give-up path stops the child but must never reclaim it.
215
+ //
216
+ // Doubles as the standing guard on `FakeOrchestrator`'s drop being
217
+ // success-only (mirroring `restoreDroppedHandles`): every create here fails,
218
+ // so a fake that dropped the prior handle regardless would leave `giveUp`
219
+ // with nothing to stop, and this line fails with
220
+ // `expected [] to include 'dock_1'`.
221
+ expect(h.orch.stopped).toContain(view.dockerId);
222
+ expect(h.orch.removed).toEqual([]);
223
+
224
+ // `error` is terminal: no further attempts, and the grant's quota is freed.
225
+ const createsAtGiveUp = h.orch.createCalls.length;
226
+ h.advance(10 * 60_000);
227
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
228
+ expect(h.orch.createCalls).toHaveLength(createsAtGiveUp);
229
+ expect(h.store.liveNodeCount(stored.grantToken)).toBe(0);
230
+ });
231
+
232
+ it('refills the attempt budget once a respawned node has stayed up', async () => {
233
+ const h = makeHarness();
234
+ const view = await h.provision();
235
+ const provisioned = requireDonation(h.store, view.id);
236
+ h.store.put({
237
+ ...provisioned,
238
+ status: 'seeded',
239
+ respawn: { attempts: 3, lastAttemptAt: new Date(h.nowMs()).toISOString() },
240
+ });
241
+
242
+ // Still inside the healthy window — the crash loop's count stands.
243
+ h.advance(DONATION_RESPAWN_HEALTHY_MS - 1_000);
244
+ await h.supervisor.reconcile();
245
+ expect(requireDonation(h.store, view.id).respawn?.attempts).toBe(3);
246
+
247
+ h.advance(2_000);
248
+ await h.supervisor.reconcile();
249
+ expect(requireDonation(h.store, view.id).respawn?.attempts).toBe(0);
250
+ // A liveness observation is not borrower activity — the stale-awaiting_seed
251
+ // reap's clock must not be pushed forward by it.
252
+ expect(requireDonation(h.store, view.id).updatedAt).toBe(provisioned.updatedAt);
253
+ });
254
+
255
+ it('skips a record that predates persisted spawn inputs without ending the sweep', async () => {
256
+ const h = makeHarness();
257
+ // Written first, so a throw here would starve the respawnable record below.
258
+ h.store.put({
259
+ id: 'grn_legacy',
260
+ grantToken: 'tok-legacy',
261
+ partyId: 'party-old',
262
+ profile: 'storage',
263
+ status: 'seeded',
264
+ dockerId: 'dock_gone',
265
+ createdAt: new Date(START_MS).toISOString(),
266
+ updatedAt: new Date(START_MS).toISOString(),
267
+ });
268
+
269
+ const view = await h.provision();
270
+ setStatus(h.store, view.id, 'seeded');
271
+ h.orch.crash(dockerIdOf(view));
272
+
273
+ await expect(h.supervisor.reconcile()).resolves.toEqual([view.id]);
274
+ const legacy = requireDonation(h.store, 'grn_legacy');
275
+ expect(legacy.status).toBe('seeded');
276
+ expect(legacy.respawn).toBeUndefined();
277
+ });
278
+
279
+ it('leaves a still-provisioning record alone — provision owns that child', async () => {
280
+ const h = makeHarness();
281
+ // A handle written by a provision that has not yet flipped to awaiting_seed.
282
+ // Respawning it here would race that provision and strand the record.
283
+ h.store.put({
284
+ id: 'grn_inflight',
285
+ grantToken: 'tok',
286
+ partyId: 'party-P',
287
+ bootstrapNodes: ['/ip4/127.0.0.1/tcp/4001/p2p/12D3KooReq'],
288
+ ownerKeys: [OWNER_KEY],
289
+ profile: 'storage',
290
+ status: 'provisioning',
291
+ dockerId: 'dock_inflight',
292
+ createdAt: new Date(START_MS).toISOString(),
293
+ updatedAt: new Date(START_MS).toISOString(),
294
+ });
295
+
296
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
297
+ expect(h.orch.createCalls).toEqual([]);
298
+ expect(requireDonation(h.store, 'grn_inflight').status).toBe('provisioning');
299
+ });
300
+
301
+ it('skips a record that has no orchestrator handle yet', async () => {
302
+ const h = makeHarness();
303
+ h.store.put({
304
+ id: 'grn_nohandle',
305
+ grantToken: 'tok',
306
+ partyId: 'party-P',
307
+ bootstrapNodes: ['/ip4/127.0.0.1/tcp/4001/p2p/12D3KooReq'],
308
+ ownerKeys: [OWNER_KEY],
309
+ profile: 'storage',
310
+ status: 'awaiting_seed',
311
+ createdAt: new Date(START_MS).toISOString(),
312
+ updatedAt: new Date(START_MS).toISOString(),
313
+ });
314
+
315
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
316
+ expect(h.orch.createCalls).toEqual([]);
317
+ });
318
+
319
+ it('does not undo a seed that lands while the pass is mid-flight', async () => {
320
+ const h = makeHarness();
321
+ const view = await h.provision();
322
+ const provisioned = requireDonation(h.store, view.id);
323
+ h.store.put({
324
+ ...provisioned,
325
+ respawn: { attempts: 3, lastAttemptAt: new Date(h.nowMs()).toISOString() },
326
+ });
327
+ h.advance(DONATION_RESPAWN_HEALTHY_MS + 1_000);
328
+
329
+ // The borrower's seed lands between the pass's store snapshot and the
330
+ // budget-refill write — the refill must merge, not replay a stale row.
331
+ h.orch.onIsRunning = () => {
332
+ h.orch.onIsRunning = undefined;
333
+ h.store.put({
334
+ ...requireDonation(h.store, view.id),
335
+ status: 'seeded',
336
+ updatedAt: new Date(h.nowMs()).toISOString(),
337
+ });
338
+ };
339
+
340
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
341
+ const stored = requireDonation(h.store, view.id);
342
+ expect(stored.status).toBe('seeded');
343
+ expect(stored.respawn?.attempts).toBe(0);
344
+ });
345
+
346
+ it('leaves a record that went terminal mid-attempt alone instead of marking it error', async () => {
347
+ const h = makeHarness();
348
+ const view = await h.provision();
349
+ h.store.put({
350
+ ...requireDonation(h.store, view.id),
351
+ status: 'seeded',
352
+ // Already at the cap, and long past the longest backoff — so the next
353
+ // failure lands straight in the give-up path.
354
+ respawn: {
355
+ attempts: DONATION_RESPAWN_MAX_ATTEMPTS,
356
+ lastAttemptAt: new Date(h.nowMs() - 10 * 60_000).toISOString(),
357
+ },
358
+ });
359
+ h.orch.crash(dockerIdOf(view));
360
+ h.orch.failCreate = true;
361
+ // The reap terminates the loan while the respawn's spawn is in flight.
362
+ h.orch.onCreate = () => {
363
+ h.store.put({ ...requireDonation(h.store, view.id), status: 'terminated' });
364
+ };
365
+
366
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
367
+
368
+ const stored = requireDonation(h.store, view.id);
369
+ // The borrower ended this loan — a host give-up must not rewrite that.
370
+ expect(stored.status).toBe('terminated');
371
+ expect(stored.error).toBeUndefined();
372
+ // The attempt counter is the one thing the failed attempt may still record.
373
+ expect(stored.respawn?.attempts).toBe(DONATION_RESPAWN_MAX_ATTEMPTS + 1);
374
+ expect(h.orch.stopped).toEqual([]);
375
+ });
376
+
377
+ it('does not count a respawn abandoned mid-spawn as a failed attempt', async () => {
378
+ const h = makeHarness();
379
+ const view = await h.provision();
380
+ h.store.put({
381
+ ...requireDonation(h.store, view.id),
382
+ status: 'seeded',
383
+ // Already at the cap and long past the longest backoff, so a *failed*
384
+ // attempt here would land straight in the give-up path.
385
+ respawn: {
386
+ attempts: DONATION_RESPAWN_MAX_ATTEMPTS,
387
+ lastAttemptAt: new Date(h.nowMs() - 10 * 60_000).toISOString(),
388
+ },
389
+ });
390
+ h.orch.crash(dockerIdOf(view));
391
+ // The borrower ends the loan while the respawn's spawn is in flight.
392
+ h.orch.createDelayMs = 20;
393
+ let terminated: Promise<void> | undefined;
394
+ h.orch.onCreate = () => { terminated ??= h.service.terminate(view.id); };
395
+
396
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
397
+ await terminated;
398
+
399
+ const stored = requireDonation(h.store, view.id);
400
+ // Nothing threw, so no attempt was persisted and give-up never ran.
401
+ expect(stored.status).toBe('terminated');
402
+ expect(stored.error).toBeUndefined();
403
+ expect(stored.respawn?.attempts).toBe(DONATION_RESPAWN_MAX_ATTEMPTS);
404
+ expect(stored.dockerId).toBe(view.dockerId);
405
+ // The abandoned child is stopped and reclaimed, not left holding ports.
406
+ expect(h.orch.stopped).toContain('dock_2');
407
+ expect(h.orch.removed).toContain('dock_2');
408
+ });
409
+
410
+ it('survives a pass over a store it cannot read', async () => {
411
+ const orch = new FakeOrchestrator();
412
+ const store = new UnreadableDonationStore(join(tmpRoot, 'donations'));
413
+ const grants = new GrantService({ store: new GrantStore(join(tmpRoot, 'grants')) });
414
+ const service = new DonationService({ orchestrator: orch, grants, store });
415
+ const supervisor = new DonationSupervisor({ service, store, orchestrator: orch });
416
+
417
+ await expect(supervisor.reconcile()).resolves.toEqual([]);
418
+ expect(orch.createCalls).toEqual([]);
419
+ });
420
+
421
+ it('serializes overlapping passes so one id is never double-spawned', async () => {
422
+ const h = makeHarness();
423
+ const view = await h.provision();
424
+ setStatus(h.store, view.id, 'seeded');
425
+ h.orch.crash(dockerIdOf(view));
426
+ h.orch.createDelayMs = 20;
427
+
428
+ const [first, second] = await Promise.all([
429
+ h.supervisor.reconcile(),
430
+ h.supervisor.reconcile(),
431
+ ]);
432
+
433
+ // Whichever pass wins the tail respawns; the other then finds it running.
434
+ expect([...first, ...second]).toEqual([view.id]);
435
+ // The original provision plus exactly one respawn.
436
+ expect(h.orch.createCalls).toHaveLength(2);
437
+ });
438
+ });
439
+
440
+ describe('DonationSupervisor start/stop', () => {
441
+ it('sweeps at startup and again on a donated child exit', async () => {
442
+ const h = makeHarness();
443
+ const view = await h.provision();
444
+ setStatus(h.store, view.id, 'seeded');
445
+ h.orch.crash(dockerIdOf(view));
446
+
447
+ h.supervisor.start();
448
+ try {
449
+ // Queued behind the startup pass, so awaiting it proves that pass ran.
450
+ await h.supervisor.reconcile();
451
+ expect(requireDonation(h.store, view.id).dockerId).toBe('dock_2');
452
+
453
+ // Now the exit-event trigger, with no manual reconcile in between.
454
+ h.advance(60_000);
455
+ h.orch.crash('dock_2');
456
+ await flush();
457
+ expect(requireDonation(h.store, view.id).dockerId).toBe('dock_3');
458
+ } finally {
459
+ h.supervisor.stop();
460
+ }
461
+ });
462
+
463
+ it('ignores owner-node exits — bin/host.ts owns re-spawning that one', async () => {
464
+ const h = makeHarness();
465
+ const view = await h.provision();
466
+ setStatus(h.store, view.id, 'seeded');
467
+
468
+ h.supervisor.start();
469
+ try {
470
+ await h.supervisor.reconcile(); // drain the startup pass (node is running)
471
+ // Take the node down WITHOUT an exit event, so the only event in play is
472
+ // the owner's.
473
+ await h.orch.stopContainer(dockerIdOf(view));
474
+
475
+ const ownerExit: ManagedNodeInfo = {
476
+ id: 'owner',
477
+ dockerId: 'dock_owner',
478
+ partyId: 'host-party',
479
+ profile: 'storage',
480
+ status: 'stopped',
481
+ spawnedAt: new Date(START_MS).toISOString(),
482
+ workdir: '/fake/owner',
483
+ ports: { health: 0, metrics: 0, p2p: 0, admin: 0 },
484
+ owner: true,
485
+ };
486
+ h.orch.emit(ownerExit);
487
+ await flush();
488
+
489
+ expect(h.orch.createCalls).toHaveLength(1);
490
+ expect(requireDonation(h.store, view.id).dockerId).toBe(view.dockerId);
491
+ } finally {
492
+ h.supervisor.stop();
493
+ }
494
+ });
495
+
496
+ it('stops reacting to exits after stop()', async () => {
497
+ const h = makeHarness();
498
+ const view = await h.provision();
499
+ setStatus(h.store, view.id, 'seeded');
500
+
501
+ h.supervisor.start();
502
+ await h.supervisor.reconcile();
503
+ h.supervisor.stop();
504
+
505
+ h.orch.crash(dockerIdOf(view));
506
+ await flush();
507
+ // The exit listener is gone, so the crash goes unnoticed until the next start.
508
+ expect(requireDonation(h.store, view.id).dockerId).toBe(view.dockerId);
509
+ });
510
+ });