@loucompanion/forge-bridge 0.1.4-dev.028808a841c8 → 0.1.4-dev.19e5db286f12

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 (36) hide show
  1. package/README.md +2 -2
  2. package/dist/bridge/bridge.service.js +4 -3
  3. package/dist/cli/cli.service.js +3 -1
  4. package/dist/runtime/host-load-admission.d.ts +52 -0
  5. package/dist/runtime/host-load-admission.js +84 -0
  6. package/dist/runtime/host-load-forge-cgroups.d.ts +8 -0
  7. package/dist/runtime/host-load-forge-cgroups.js +51 -0
  8. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  9. package/dist/runtime/host-load-governor-config.js +46 -0
  10. package/dist/runtime/host-load-governor.d.ts +123 -0
  11. package/dist/runtime/host-load-governor.js +415 -0
  12. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  13. package/dist/runtime/host-load-ledger-lock.js +185 -0
  14. package/dist/runtime/host-load-sampler.d.ts +38 -0
  15. package/dist/runtime/host-load-sampler.js +66 -6
  16. package/dist/runtime/host-load-step-class.d.ts +33 -0
  17. package/dist/runtime/host-load-step-class.js +46 -0
  18. package/dist/runtime/host-load-token-ledger.d.ts +135 -0
  19. package/dist/runtime/host-load-token-ledger.js +345 -0
  20. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  21. package/dist/runtime/host-pressure-stall.js +48 -1
  22. package/dist/runtime/host-runtime-lease.d.ts +7 -1
  23. package/dist/runtime/host-runtime-lease.js +12 -2
  24. package/dist/session/pre-publication-host-load.d.ts +27 -0
  25. package/dist/session/pre-publication-host-load.js +96 -0
  26. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  27. package/dist/session/pre-publication-step-execution.js +49 -0
  28. package/dist/session/pre-publication-validation.d.ts +9 -9
  29. package/dist/session/pre-publication-validation.js +17 -55
  30. package/dist/session/provider-cli/provider-cli.process.d.ts +7 -0
  31. package/dist/session/provider-cli/provider-cli.process.js +13 -5
  32. package/dist/session/provider-cli/provider-cli.service.js +28 -5
  33. package/dist/session/session.types.js +1 -1
  34. package/dist/version.d.ts +1 -1
  35. package/dist/version.js +1 -1
  36. package/package.json +1 -1
@@ -0,0 +1,415 @@
1
+ import os from "node:os";
2
+ import { ForgeFailureError } from "../session/session.types.js";
3
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
4
+ import { decideHostLoadAdmission, } from "./host-load-admission.js";
5
+ import { loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
6
+ import { HostCapacityLedgerUnavailableError } from "./host-load-ledger-lock.js";
7
+ import { HostCapacityTokenFencedError, HostLoadTokenLedger, } from "./host-load-token-ledger.js";
8
+ export class HostCapacityTimeoutError extends ForgeFailureError {
9
+ stepClass;
10
+ label;
11
+ waitMs;
12
+ code = "host_capacity_timeout";
13
+ constructor(stepClass, label, waitMs, detail) {
14
+ super("host_capacity_timeout", `host_capacity_timeout: ${label} (${stepClass}) waited ${Math.round(waitMs / 1000)}s for host capacity without being admitted: ${detail} This is a retryable host-load condition, not a test failure.`, "bridge");
15
+ this.stepClass = stepClass;
16
+ this.label = label;
17
+ this.waitMs = waitMs;
18
+ this.name = "HostCapacityTimeoutError";
19
+ }
20
+ }
21
+ /**
22
+ * Host-wide admission for heavy steps (decision 0013). Waiters queue
23
+ * foreground before background and FIFO within a class; a waiter that fits may
24
+ * overtake an unfit head until the head has waited past the anti-starvation
25
+ * window. Running steps are never preempted. Reserved cost comes from the
26
+ * shared token ledger, so other processes' steps count against the same budget.
27
+ */
28
+ export class HostLoadGovernor {
29
+ options;
30
+ enabled;
31
+ config;
32
+ ledger;
33
+ waiters = [];
34
+ held = new Map();
35
+ recheckTimer = null;
36
+ renewTimer = null;
37
+ draining = null;
38
+ drainAgain = false;
39
+ /** Own cgroup anonymous memory with no heavy step running: the bridge's baseline. */
40
+ idleOwnMemoryBytes = null;
41
+ constructor(options) {
42
+ this.options = options;
43
+ this.config = options.config ?? loadHostLoadGovernorConfig();
44
+ this.enabled = this.config.mode === "on";
45
+ this.ledger = new HostLoadTokenLedger({
46
+ stateRoot: options.stateRoot,
47
+ leaseMs: this.config.leaseMs,
48
+ now: options.now,
49
+ liveness: options.liveness,
50
+ owner: options.owner,
51
+ // Every ledger transaction renews (or restores) the steps this governor is running.
52
+ heldTokens: () => [...this.held.values()].map(entry => entry.token),
53
+ onHeldTokens: outcome => this.onHeldTokens(outcome),
54
+ });
55
+ }
56
+ async acquire(request, options = {}) {
57
+ if (!this.enabled)
58
+ throw new Error("host_load_governor_disabled: acquire() requires FORGE_HOST_LOAD_GOVERNOR=on.");
59
+ const { signal } = options;
60
+ if (signal?.aborted)
61
+ throw abortError(signal);
62
+ await this.options.load.start().catch(() => undefined);
63
+ if (signal?.aborted)
64
+ throw abortError(signal);
65
+ return await new Promise((resolve, reject) => {
66
+ const waiter = {
67
+ request,
68
+ enqueuedAtMs: monotonicNowMs(),
69
+ signal,
70
+ onWaiting: options.onWaiting,
71
+ resolve,
72
+ reject,
73
+ abort: () => this.settle(waiter, () => reject(abortError(signal))),
74
+ deadline: null,
75
+ lastDecision: null,
76
+ settled: false,
77
+ };
78
+ waiter.deadline = setTimeout(() => this.settle(waiter, () => reject(new HostCapacityTimeoutError(request.stepClass, request.label, monotonicNowMs() - waiter.enqueuedAtMs, waiter.lastDecision?.detail ?? "the host stayed at capacity."))), this.config.maxWaitMs);
79
+ waiter.deadline.unref?.();
80
+ signal?.addEventListener("abort", waiter.abort, { once: true });
81
+ // Foreground goes ahead of background, except background that has already
82
+ // waited past the anti-starvation window: steady foreground load cannot starve it.
83
+ const backgroundIndex = request.priority === "foreground"
84
+ ? this.waiters.findIndex(candidate => candidate.request.priority === "background"
85
+ && waiter.enqueuedAtMs - candidate.enqueuedAtMs < this.config.antiStarvationMs)
86
+ : -1;
87
+ if (backgroundIndex < 0)
88
+ this.waiters.push(waiter);
89
+ else
90
+ this.waiters.splice(backgroundIndex, 0, waiter);
91
+ this.armRecheck();
92
+ void this.drain();
93
+ });
94
+ }
95
+ /** Reclaims tokens whose owner is gone or whose lease expired (bridge startup). */
96
+ async reclaim() {
97
+ if (!this.enabled)
98
+ return [];
99
+ const reclaimed = await this.ledger.reclaim();
100
+ if (reclaimed.length > 0)
101
+ void this.drain();
102
+ return reclaimed;
103
+ }
104
+ /** Attempt teardown: cancels the attempt's waiters and returns every token it holds. */
105
+ async releaseAttempt(dispatchAttemptId) {
106
+ if (!this.enabled)
107
+ return;
108
+ for (const waiter of [...this.waiters]) {
109
+ if (waiter.request.dispatchAttemptId !== dispatchAttemptId)
110
+ continue;
111
+ this.settle(waiter, () => waiter.reject(new ForgeFailureError("dispatch_cancelled", "dispatch_cancelled: the attempt was torn down while its step waited for host capacity.", "bridge")));
112
+ }
113
+ const owned = [...this.held.values()].filter(entry => entry.token.dispatchAttemptId === dispatchAttemptId);
114
+ await Promise.allSettled(owned.map(entry => this.releaseHeld(entry)));
115
+ }
116
+ /** Waiting and admitted steps of this process, for diagnostics. */
117
+ snapshot() {
118
+ return { waiting: this.waiters.length, held: [...this.held.values()].map(entry => entry.token) };
119
+ }
120
+ async drain() {
121
+ if (this.draining) {
122
+ this.drainAgain = true;
123
+ return await this.draining;
124
+ }
125
+ this.draining = (async () => {
126
+ do {
127
+ this.drainAgain = false;
128
+ await this.drainOnce().catch(error => this.failWaiters(error));
129
+ } while (this.drainAgain && this.waiters.length > 0);
130
+ })().finally(() => {
131
+ this.draining = null;
132
+ });
133
+ return await this.draining;
134
+ }
135
+ async drainOnce() {
136
+ if (this.waiters.length === 0)
137
+ return;
138
+ const signals = this.readSignals();
139
+ const logicalCpus = this.logicalCpus();
140
+ const nowMs = monotonicNowMs();
141
+ const outcomes = [];
142
+ await this.ledger.transaction(transaction => {
143
+ const runningMemoryBytes = this.runningStepsMemoryBytes(transaction.tokens);
144
+ const head = this.waiters[0];
145
+ const headStarving = head !== undefined && nowMs - head.enqueuedAtMs >= this.config.antiStarvationMs;
146
+ for (const waiter of this.waiters) {
147
+ if (waiter.settled)
148
+ continue;
149
+ const computed = decideHostLoadAdmission({
150
+ request: waiter.request.cost,
151
+ running: transaction.tokens.map(token => token.cost),
152
+ runningMemoryBytes,
153
+ logicalCpus,
154
+ signals,
155
+ config: this.config,
156
+ });
157
+ const decision = transaction.recoveringUntil
158
+ ? {
159
+ ...computed,
160
+ admitted: false,
161
+ reason: "ledger_recovering",
162
+ detail: `The host load ledger was corrupt and was quarantined; admissions resume at ${transaction.recoveringUntil}, once running steps have restored their reservations.`,
163
+ }
164
+ : computed;
165
+ outcomes.push({ waiter, decision, token: decision.admitted ? transaction.issue(waiter.request) : null });
166
+ // A starving head blocks the queue so running steps drain and it can start.
167
+ if (waiter === head && headStarving && !decision.admitted)
168
+ break;
169
+ }
170
+ });
171
+ for (const { waiter, token, decision } of outcomes) {
172
+ if (!token) {
173
+ const first = waiter.lastDecision === null;
174
+ waiter.lastDecision = decision;
175
+ if (first && !waiter.settled)
176
+ void Promise.resolve(waiter.onWaiting?.(decision)).catch(() => undefined);
177
+ continue;
178
+ }
179
+ const entry = {
180
+ token,
181
+ lost: new AbortController(),
182
+ renewedAtMs: monotonicNowMs(),
183
+ releasing: false,
184
+ releaseInFlight: null,
185
+ gone: false,
186
+ };
187
+ this.held.set(token.tokenId, entry);
188
+ this.armRenewal();
189
+ if (waiter.settled) {
190
+ // Cancelled or timed out while the decision was being made.
191
+ void this.releaseHeld(entry).catch(() => undefined);
192
+ continue;
193
+ }
194
+ const waitMs = Math.max(0, monotonicNowMs() - waiter.enqueuedAtMs);
195
+ this.settle(waiter, () => waiter.resolve({
196
+ tokenId: token.tokenId,
197
+ fencingToken: token.fencingToken,
198
+ stepClass: token.stepClass,
199
+ waitMs,
200
+ decision,
201
+ signal: entry.lost.signal,
202
+ release: () => this.releaseHeld(entry),
203
+ }));
204
+ }
205
+ }
206
+ readSignals() {
207
+ const snapshot = this.options.load.current();
208
+ const cpu = snapshot?.systemPressure?.cpu?.some;
209
+ const sampledAtMs = snapshot ? Date.parse(snapshot.sampledAt) : Number.NaN;
210
+ const now = this.options.now?.() ?? Date.now();
211
+ if (!snapshot?.psiAvailable || !cpu || !Number.isFinite(sampledAtMs) || now - sampledAtMs > this.config.sampleStaleMs) {
212
+ return null;
213
+ }
214
+ // Own-cgroup numbers are trusted only for a dedicated cgroup (step 1's ownCgroupDedicated).
215
+ const attribution = snapshot.ownCgroupDedicated ? this.options.load.cpuAttribution?.() ?? null : null;
216
+ return {
217
+ cpuSomeAvg10: cpu.avg10,
218
+ cpuPressuredSamples: this.pressureStreak(sampledAtMs, cpu.avg10),
219
+ memoryFullAvg10: snapshot.systemPressure?.memory?.full?.avg10 ?? null,
220
+ memoryAvailableBytes: tighterMemory(snapshot.memoryAvailableBytes, this.options.load.cgroupMemoryHeadroomBytes?.() ?? null),
221
+ externalCpuCores: attribution?.sampledAt === snapshot.sampledAt ? attribution.externalCoresInUse : null,
222
+ };
223
+ }
224
+ /**
225
+ * Consecutive pressured samples ending with the latest one, read from the
226
+ * sampler's history so samples taken while nothing waited still count. A gap
227
+ * in sampling (sampler stopped, host suspended) breaks the streak.
228
+ */
229
+ pressureStreak(latestAtMs, latestAvg10) {
230
+ if (latestAvg10 < this.config.cpuPressureThreshold)
231
+ return 0;
232
+ let streak = 1;
233
+ let laterAtMs = latestAtMs;
234
+ const history = this.options.load.recent();
235
+ for (let index = history.length - 1; index >= 0 && streak < this.config.backpressureSamples; index -= 1) {
236
+ const sample = history[index];
237
+ const atMs = Date.parse(sample.sampledAt);
238
+ if (!Number.isFinite(atMs) || atMs >= laterAtMs)
239
+ continue;
240
+ if (laterAtMs - atMs > this.config.sampleIntervalMs * 1.5)
241
+ break;
242
+ const avg10 = sample.psiAvailable ? sample.systemPressure?.cpu?.some?.avg10 : undefined;
243
+ if (avg10 === undefined || avg10 < this.config.cpuPressureThreshold)
244
+ break;
245
+ streak += 1;
246
+ laterAtMs = atMs;
247
+ }
248
+ return streak;
249
+ }
250
+ /**
251
+ * Memory the running steps already use, which MemAvailable already reflects,
252
+ * so the budget does not count it twice. Measured from the dedicated cgroup
253
+ * above its idle baseline; without one, a step admitted longer than the ramp
254
+ * window ago is assumed to hold its reservation. Never above the reservations.
255
+ */
256
+ runningStepsMemoryBytes(tokens) {
257
+ const snapshot = this.options.load.current();
258
+ const ownMemory = snapshot?.ownCgroupDedicated ? snapshot.ownCgroup?.memoryAnonBytes ?? null : null;
259
+ if (tokens.length === 0) {
260
+ if (ownMemory !== null)
261
+ this.idleOwnMemoryBytes = ownMemory;
262
+ return 0;
263
+ }
264
+ const reserved = tokens.reduce((sum, token) => sum + token.cost.memoryBytes, 0);
265
+ if (ownMemory !== null && this.idleOwnMemoryBytes !== null) {
266
+ return Math.min(reserved, Math.max(0, ownMemory - this.idleOwnMemoryBytes));
267
+ }
268
+ const now = this.options.now?.() ?? Date.now();
269
+ return tokens
270
+ .filter(token => now - Date.parse(token.admittedAt) >= this.config.memoryRampMs)
271
+ .reduce((sum, token) => sum + token.cost.memoryBytes, 0);
272
+ }
273
+ logicalCpus() {
274
+ const reported = this.options.load.facts()?.logicalThreads;
275
+ if (reported && reported > 0)
276
+ return reported;
277
+ return Math.max(1, typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length);
278
+ }
279
+ settle(waiter, complete) {
280
+ if (waiter.settled)
281
+ return;
282
+ waiter.settled = true;
283
+ if (waiter.deadline)
284
+ clearTimeout(waiter.deadline);
285
+ waiter.signal?.removeEventListener("abort", waiter.abort);
286
+ const index = this.waiters.indexOf(waiter);
287
+ if (index >= 0)
288
+ this.waiters.splice(index, 1);
289
+ if (this.waiters.length === 0)
290
+ this.disarmRecheck();
291
+ complete();
292
+ }
293
+ /**
294
+ * Returns a step's token. It stays held (and renewed) until the ledger takes
295
+ * it back, so a ledger outage cannot leave it to lapse into a fenced
296
+ * reservation; the renewal timer retries the release.
297
+ */
298
+ async releaseHeld(entry) {
299
+ if (entry.gone)
300
+ return;
301
+ entry.releasing = true;
302
+ entry.releaseInFlight ??= (async () => {
303
+ try {
304
+ await this.ledger.release(entry.token.tokenId, entry.token.fencingToken);
305
+ this.forget(entry);
306
+ }
307
+ catch (error) {
308
+ if (error instanceof HostCapacityTokenFencedError)
309
+ this.forget(entry);
310
+ throw error;
311
+ }
312
+ finally {
313
+ entry.releaseInFlight = null;
314
+ void this.drain();
315
+ }
316
+ })();
317
+ return await entry.releaseInFlight;
318
+ }
319
+ forget(entry) {
320
+ entry.gone = true;
321
+ this.held.delete(entry.token.tokenId);
322
+ if (this.held.size === 0)
323
+ this.disarmRenewal();
324
+ }
325
+ /** The step must stop: its reservation is no longer guaranteed. */
326
+ lose(entry, reason) {
327
+ if (entry.gone || entry.releasing || entry.lost.signal.aborted)
328
+ return;
329
+ entry.lost.abort(reason);
330
+ }
331
+ onHeldTokens(outcome) {
332
+ const nowMs = monotonicNowMs();
333
+ for (const token of outcome.renewed) {
334
+ const entry = this.held.get(token.tokenId);
335
+ if (entry?.token.fencingToken === token.fencingToken)
336
+ entry.renewedAtMs = nowMs;
337
+ }
338
+ for (const token of outcome.fenced) {
339
+ const entry = this.held.get(token.tokenId);
340
+ if (entry?.token.fencingToken === token.fencingToken)
341
+ this.lose(entry, new HostCapacityTokenFencedError(token.tokenId, "renew"));
342
+ }
343
+ }
344
+ /** Ledger failures reach every queued step instead of leaving it to time out. */
345
+ failWaiters(error) {
346
+ const failure = error instanceof HostCapacityLedgerUnavailableError
347
+ ? error
348
+ : new HostCapacityLedgerUnavailableError(`the admission decision failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
349
+ for (const waiter of [...this.waiters])
350
+ this.settle(waiter, () => waiter.reject(failure));
351
+ }
352
+ armRecheck() {
353
+ if (this.recheckTimer)
354
+ return;
355
+ // Capacity can return without a local release: another process's token, a
356
+ // new pressure sample, or external load ending.
357
+ this.recheckTimer = setInterval(() => void this.drain(), this.config.recheckIntervalMs);
358
+ this.recheckTimer.unref?.();
359
+ }
360
+ disarmRecheck() {
361
+ if (this.recheckTimer)
362
+ clearInterval(this.recheckTimer);
363
+ this.recheckTimer = null;
364
+ }
365
+ armRenewal() {
366
+ if (this.renewTimer)
367
+ return;
368
+ this.renewTimer = setInterval(() => void this.renewHeld(), Math.max(10, Math.floor(this.config.leaseMs / 4)));
369
+ this.renewTimer.unref?.();
370
+ }
371
+ disarmRenewal() {
372
+ if (this.renewTimer)
373
+ clearInterval(this.renewTimer);
374
+ this.renewTimer = null;
375
+ }
376
+ async renewHeld() {
377
+ if (this.held.size === 0)
378
+ return;
379
+ for (const entry of this.held.values()) {
380
+ // A release the ledger could not take is retried until it lands.
381
+ if (entry.releasing && !entry.releaseInFlight)
382
+ void this.releaseHeld(entry).catch(() => undefined);
383
+ }
384
+ try {
385
+ // The ledger renews every held token at the start of each transaction and
386
+ // reports the fenced ones through onHeldTokens.
387
+ await this.ledger.transaction(() => undefined);
388
+ }
389
+ catch (error) {
390
+ // A brief outage is retried on the next tick. Once a whole lease passes
391
+ // without a renewal, another process may already have fenced the token.
392
+ const nowMs = monotonicNowMs();
393
+ for (const entry of this.held.values()) {
394
+ if (nowMs - entry.renewedAtMs < this.config.leaseMs)
395
+ continue;
396
+ this.lose(entry, error instanceof HostCapacityLedgerUnavailableError
397
+ ? error
398
+ : new HostCapacityLedgerUnavailableError("the host load token could not be renewed.", { cause: error }));
399
+ }
400
+ }
401
+ }
402
+ }
403
+ /** The cgroup limit's headroom when one is set, never above host MemAvailable. */
404
+ function tighterMemory(hostAvailable, cgroupHeadroom) {
405
+ if (cgroupHeadroom === null)
406
+ return hostAvailable;
407
+ return hostAvailable === null ? cgroupHeadroom : Math.min(hostAvailable, cgroupHeadroom);
408
+ }
409
+ function abortError(signal) {
410
+ if (signal.reason instanceof Error)
411
+ return signal.reason;
412
+ const error = new Error(typeof signal.reason === "string" ? signal.reason : "The host capacity wait was cancelled.");
413
+ error.name = "AbortError";
414
+ return error;
415
+ }
@@ -0,0 +1,69 @@
1
+ import { ForgeFailureError } from "../session/session.types.js";
2
+ /** Who holds the ledger lock; liveness is judged by the ledger's owner rules. */
3
+ export interface HostLoadLockHolder {
4
+ readonly pid: number;
5
+ readonly processInstanceId: string;
6
+ readonly processIdentity: string | null;
7
+ }
8
+ export interface HostLoadLedgerLockOptions {
9
+ readonly lockPath: string;
10
+ readonly holder: () => HostLoadLockHolder;
11
+ readonly isLive: (holder: HostLoadLockHolder) => boolean;
12
+ readonly timeoutMs: number;
13
+ /** A lock with no readable holder is broken only after this age. */
14
+ readonly unreadableStaleAfterMs?: number;
15
+ /** Test seam: runs after a lock was judged stale and before it is broken. */
16
+ readonly beforeStaleBreak?: () => Promise<void>;
17
+ }
18
+ export declare class HostCapacityLedgerUnavailableError extends ForgeFailureError {
19
+ readonly code = "host_capacity_ledger_unavailable";
20
+ constructor(detail: string, options?: ErrorOptions);
21
+ }
22
+ /**
23
+ * Cross-process exclusive lock file for the host load ledger.
24
+ *
25
+ * Every lock file, and every break lock, is claimed with a complete
26
+ * `{ token, holder }` record: written to a private temporary file and
27
+ * hard-linked into place, which fails if the path exists. No path is ever
28
+ * renamed or replaced, so nothing anyone holds can be moved out from under them.
29
+ *
30
+ * A lock is broken only when its holder is provably dead (or it has no readable
31
+ * holder and is old). Breakers of one stale lock serialize on a chain of break
32
+ * locks named after that lock's identity: `<lock>.break-<identity>.1`, `.2`, …
33
+ * A breaker claims the first link it can; it moves on to the next only when the
34
+ * holder of the current one is dead, and never removes it. Under its link it
35
+ * re-judges the lock and unlinks it only if the path still holds that same stale
36
+ * lock. Identities never repeat, so the stale lock cannot reappear, and while
37
+ * it exists nobody can create a new lock; so at most one live breaker can ever
38
+ * act on it, and the unlink can never touch a lock someone acquired meanwhile.
39
+ */
40
+ export declare class HostLoadLedgerLock {
41
+ private readonly options;
42
+ constructor(options: HostLoadLedgerLockOptions);
43
+ acquire(): Promise<string>;
44
+ /**
45
+ * Creates `target` holding a complete `{ token, holder }` record, or fails with
46
+ * EEXIST. `link` never replaces an existing path, and the record is fully
47
+ * written before the path appears.
48
+ */
49
+ private claim;
50
+ /** True while `token` still owns the lock file. */
51
+ holds(token: string): Promise<boolean>;
52
+ release(token: string): Promise<void>;
53
+ private breakIfStale;
54
+ /**
55
+ * The lock at `lockPath` if it is stale (with an identity that never repeats:
56
+ * its token, or for an unreadable file its inode and timestamps), "absent" if
57
+ * there is none, or null if it is live or too young to judge.
58
+ */
59
+ private judgeStale;
60
+ /**
61
+ * Claims the next free link of the stale lock's break chain, held only for the
62
+ * few milliseconds the lock is re-judged and unlinked. A link whose holder is
63
+ * live means another breaker is on it; a dead holder's link is skipped, never
64
+ * removed or replaced.
65
+ */
66
+ private acquireBreaker;
67
+ /** Removes `link` if `token` holds it, or unconditionally (null) once the stale lock it guarded is gone. */
68
+ private releaseOwn;
69
+ }
@@ -0,0 +1,185 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import { ForgeFailureError } from "../session/session.types.js";
4
+ export class HostCapacityLedgerUnavailableError extends ForgeFailureError {
5
+ code = "host_capacity_ledger_unavailable";
6
+ constructor(detail, options) {
7
+ super("host_capacity_ledger_unavailable", `host_capacity_ledger_unavailable: ${detail}`, "bridge", options);
8
+ this.name = "HostCapacityLedgerUnavailableError";
9
+ }
10
+ }
11
+ /**
12
+ * Cross-process exclusive lock file for the host load ledger.
13
+ *
14
+ * Every lock file, and every break lock, is claimed with a complete
15
+ * `{ token, holder }` record: written to a private temporary file and
16
+ * hard-linked into place, which fails if the path exists. No path is ever
17
+ * renamed or replaced, so nothing anyone holds can be moved out from under them.
18
+ *
19
+ * A lock is broken only when its holder is provably dead (or it has no readable
20
+ * holder and is old). Breakers of one stale lock serialize on a chain of break
21
+ * locks named after that lock's identity: `<lock>.break-<identity>.1`, `.2`, …
22
+ * A breaker claims the first link it can; it moves on to the next only when the
23
+ * holder of the current one is dead, and never removes it. Under its link it
24
+ * re-judges the lock and unlinks it only if the path still holds that same stale
25
+ * lock. Identities never repeat, so the stale lock cannot reappear, and while
26
+ * it exists nobody can create a new lock; so at most one live breaker can ever
27
+ * act on it, and the unlink can never touch a lock someone acquired meanwhile.
28
+ */
29
+ export class HostLoadLedgerLock {
30
+ options;
31
+ constructor(options) {
32
+ this.options = options;
33
+ }
34
+ async acquire() {
35
+ const token = randomUUID();
36
+ const started = Date.now();
37
+ for (;;) {
38
+ try {
39
+ await this.claim(this.options.lockPath, token);
40
+ return token;
41
+ }
42
+ catch (error) {
43
+ if (error.code !== "EEXIST")
44
+ throw error;
45
+ if (await this.breakIfStale())
46
+ continue;
47
+ if (Date.now() - started >= this.options.timeoutMs) {
48
+ throw new HostCapacityLedgerUnavailableError("the host load ledger lock could not be acquired.", { cause: error });
49
+ }
50
+ await new Promise(resolve => setTimeout(resolve, 10));
51
+ }
52
+ }
53
+ }
54
+ /**
55
+ * Creates `target` holding a complete `{ token, holder }` record, or fails with
56
+ * EEXIST. `link` never replaces an existing path, and the record is fully
57
+ * written before the path appears.
58
+ */
59
+ async claim(target, token) {
60
+ const temporary = `${target}.${randomUUID()}.claim`;
61
+ try {
62
+ const handle = await fs.open(temporary, "wx", 0o600);
63
+ try {
64
+ await handle.writeFile(JSON.stringify({ token, holder: this.options.holder() }));
65
+ }
66
+ finally {
67
+ await handle.close();
68
+ }
69
+ await fs.link(temporary, target);
70
+ }
71
+ finally {
72
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
73
+ }
74
+ }
75
+ /** True while `token` still owns the lock file. */
76
+ async holds(token) {
77
+ return (await readLock(this.options.lockPath))?.token === token;
78
+ }
79
+ async release(token) {
80
+ // Only a breaker removes a lock it did not take, and only a stale one: a live
81
+ // holder's file cannot change between this check and the removal.
82
+ if (await this.holds(token))
83
+ await fs.rm(this.options.lockPath, { force: true });
84
+ }
85
+ async breakIfStale() {
86
+ const observed = await this.judgeStale(this.options.lockPath);
87
+ if (observed === "absent")
88
+ return true;
89
+ if (!observed)
90
+ return false;
91
+ await this.options.beforeStaleBreak?.();
92
+ const breaker = await this.acquireBreaker(observed.identity);
93
+ if (!breaker)
94
+ return false;
95
+ let broken = false;
96
+ try {
97
+ // Re-judged under the break lock: the path must still hold the same stale lock.
98
+ const current = await this.judgeStale(this.options.lockPath);
99
+ if (current === "absent")
100
+ return true;
101
+ if (!current || current.identity !== observed.identity)
102
+ return false;
103
+ await fs.unlink(this.options.lockPath).catch(error => {
104
+ if (error.code !== "ENOENT")
105
+ throw error;
106
+ });
107
+ broken = true;
108
+ return true;
109
+ }
110
+ finally {
111
+ // Once the stale lock is gone its chain is never needed again: dead breakers'
112
+ // links are cleared too. Otherwise only this breaker's own link is returned.
113
+ const links = broken ? breaker.chain : [breaker.path];
114
+ await Promise.all(links.map(link => this.releaseOwn(link, broken ? null : breaker.token)));
115
+ }
116
+ }
117
+ /**
118
+ * The lock at `lockPath` if it is stale (with an identity that never repeats:
119
+ * its token, or for an unreadable file its inode and timestamps), "absent" if
120
+ * there is none, or null if it is live or too young to judge.
121
+ */
122
+ async judgeStale(lockPath) {
123
+ const stat = await fs.lstat(lockPath).catch(() => null);
124
+ if (!stat)
125
+ return "absent";
126
+ const observed = stat.isFile() && stat.size <= 16 * 1024 ? await readLock(lockPath) : null;
127
+ if (observed?.holder && validHolder(observed.holder) && typeof observed.token === "string") {
128
+ // A live holder keeps its lock however old it is.
129
+ if (this.options.isLive(observed.holder))
130
+ return null;
131
+ return { identity: `t-${observed.token}` };
132
+ }
133
+ // Unreadable (claims are atomic, so this is corruption): give it until the stale age.
134
+ if (Date.now() - stat.mtimeMs < (this.options.unreadableStaleAfterMs ?? 30_000))
135
+ return null;
136
+ return { identity: `i-${stat.dev}-${stat.ino}-${Math.trunc(stat.mtimeMs)}-${stat.size}` };
137
+ }
138
+ /**
139
+ * Claims the next free link of the stale lock's break chain, held only for the
140
+ * few milliseconds the lock is re-judged and unlinked. A link whose holder is
141
+ * live means another breaker is on it; a dead holder's link is skipped, never
142
+ * removed or replaced.
143
+ */
144
+ async acquireBreaker(identity) {
145
+ const base = `${this.options.lockPath}.break-${identity.replace(/[^A-Za-z0-9-]/gu, "_")}`;
146
+ const token = randomUUID();
147
+ const chain = [];
148
+ for (let generation = 1; generation <= maximumBreakGenerations; generation += 1) {
149
+ const link = `${base}.${generation}`;
150
+ chain.push(link);
151
+ try {
152
+ await this.claim(link, token);
153
+ return { path: link, token, chain };
154
+ }
155
+ catch (error) {
156
+ if (error.code !== "EEXIST")
157
+ throw error;
158
+ }
159
+ const holder = await this.judgeStale(link);
160
+ // Live (or just written): another breaker is on it. Gone: retry from the start later.
161
+ if (holder === null || holder === "absent")
162
+ return null;
163
+ }
164
+ return null;
165
+ }
166
+ /** Removes `link` if `token` holds it, or unconditionally (null) once the stale lock it guarded is gone. */
167
+ async releaseOwn(link, token) {
168
+ if (token === null || (await readLock(link))?.token === token)
169
+ await fs.rm(link, { force: true }).catch(() => undefined);
170
+ }
171
+ }
172
+ /** A chain longer than this means breakers keep dying; the acquire times out instead. */
173
+ const maximumBreakGenerations = 16;
174
+ async function readLock(lockPath) {
175
+ return await fs.readFile(lockPath, "utf8")
176
+ .then(value => JSON.parse(value))
177
+ .catch(() => null);
178
+ }
179
+ function validHolder(value) {
180
+ const holder = value;
181
+ return Boolean(holder)
182
+ && Number.isSafeInteger(holder.pid) && holder.pid > 0
183
+ && typeof holder.processInstanceId === "string"
184
+ && (holder.processIdentity === null || typeof holder.processIdentity === "string");
185
+ }