@loucompanion/forge-bridge 0.1.4-dev.d2d83bc81b6a → 0.1.4-dev.e1b4f55fb18d

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 (128) hide show
  1. package/README.md +2 -2
  2. package/dist/bridge/bridge.service.d.ts +5 -1
  3. package/dist/bridge/bridge.service.js +40 -6
  4. package/dist/bridge/bridge.types.d.ts +11 -0
  5. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  6. package/dist/bridge/runner-host-capabilities.js +4 -0
  7. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  8. package/dist/bridge/test-postgres-capability.js +120 -0
  9. package/dist/cleanup/cleanup.service.d.ts +9 -0
  10. package/dist/cleanup/cleanup.service.js +57 -100
  11. package/dist/cleanup/cleanup.types.d.ts +4 -0
  12. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  13. package/dist/cleanup/host-runtime-ledger.js +109 -0
  14. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  15. package/dist/cleanup/managed-branch-sweep.js +111 -0
  16. package/dist/cli/cli.service.js +10 -2
  17. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  18. package/dist/runtime/host-database-capability-boundary.js +1 -0
  19. package/dist/runtime/host-facts.d.ts +35 -0
  20. package/dist/runtime/host-facts.js +95 -0
  21. package/dist/runtime/host-load-admission.d.ts +52 -0
  22. package/dist/runtime/host-load-admission.js +84 -0
  23. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  24. package/dist/runtime/host-load-child-environment.js +65 -0
  25. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  26. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  27. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  28. package/dist/runtime/host-load-governor-config.js +46 -0
  29. package/dist/runtime/host-load-governor.d.ts +172 -0
  30. package/dist/runtime/host-load-governor.js +519 -0
  31. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  32. package/dist/runtime/host-load-ledger-lock.js +185 -0
  33. package/dist/runtime/host-load-sampler.d.ts +126 -0
  34. package/dist/runtime/host-load-sampler.js +232 -0
  35. package/dist/runtime/host-load-step-class.d.ts +68 -0
  36. package/dist/runtime/host-load-step-class.js +106 -0
  37. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  38. package/dist/runtime/host-load-step-reaper.js +95 -0
  39. package/dist/runtime/host-load-step-run.d.ts +73 -0
  40. package/dist/runtime/host-load-step-run.js +102 -0
  41. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  42. package/dist/runtime/host-load-token-ledger.js +421 -0
  43. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  44. package/dist/runtime/host-pressure-stall.js +168 -0
  45. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  46. package/dist/runtime/host-runtime-contract.js +6 -1
  47. package/dist/runtime/host-runtime-lease.d.ts +17 -3
  48. package/dist/runtime/host-runtime-lease.js +83 -4
  49. package/dist/runtime/host-runtime-promotion.js +12 -0
  50. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  51. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  52. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  53. package/dist/runtime/host-runtime-requirements.js +117 -0
  54. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  55. package/dist/sandbox/host-capacity-broker.js +315 -0
  56. package/dist/sandbox/runtime.d.ts +10 -1
  57. package/dist/sandbox/runtime.js +45 -2
  58. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  59. package/dist/sandbox/sandbox-cgroups.js +42 -0
  60. package/dist/session/managed-attempt-tools.d.ts +2 -0
  61. package/dist/session/managed-attempt-tools.js +156 -37
  62. package/dist/session/managed-command-host-load.d.ts +45 -0
  63. package/dist/session/managed-command-host-load.js +82 -0
  64. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  65. package/dist/session/mcp-argument-coercion.js +121 -0
  66. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  67. package/dist/session/phase-completion.artifacts.js +98 -25
  68. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  69. package/dist/session/phase-completion.command-validation.js +77 -0
  70. package/dist/session/phase-completion.d.ts +4 -0
  71. package/dist/session/phase-completion.helpers.js +13 -12
  72. package/dist/session/phase-completion.js +4 -0
  73. package/dist/session/phase-completion.prompts.js +6 -1
  74. package/dist/session/phase-completion.runtime.d.ts +5 -3
  75. package/dist/session/phase-completion.runtime.js +49 -19
  76. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  77. package/dist/session/phase-completion.schema-parts.js +188 -0
  78. package/dist/session/phase-completion.schemas.d.ts +3 -3
  79. package/dist/session/phase-completion.schemas.js +184 -209
  80. package/dist/session/phase-completion.validation.d.ts +2 -3
  81. package/dist/session/phase-completion.validation.js +46 -92
  82. package/dist/session/pre-publication-host-load.d.ts +27 -0
  83. package/dist/session/pre-publication-host-load.js +111 -0
  84. package/dist/session/pre-publication-process.d.ts +3 -0
  85. package/dist/session/pre-publication-process.js +25 -12
  86. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  87. package/dist/session/pre-publication-skipped-tests.js +109 -0
  88. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  89. package/dist/session/pre-publication-step-execution.js +49 -0
  90. package/dist/session/pre-publication-validation.d.ts +9 -9
  91. package/dist/session/pre-publication-validation.js +44 -59
  92. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  93. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  94. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  95. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  96. package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
  97. package/dist/session/provider-cli/provider-cli.process.js +122 -30
  98. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  99. package/dist/session/provider-cli/provider-cli.prompts.js +16 -1
  100. package/dist/session/provider-cli/provider-cli.service.js +134 -30
  101. package/dist/session/provider-cli/provider-cli.types.d.ts +4 -0
  102. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  103. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  104. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  105. package/dist/session/provider-cli/provider-output-state.js +9 -0
  106. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  107. package/dist/session/publishable-worktree-changes.js +193 -0
  108. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  109. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  110. package/dist/session/session.base.d.ts +3 -0
  111. package/dist/session/session.service.d.ts +2 -0
  112. package/dist/session/session.service.js +21 -4
  113. package/dist/session/session.types.d.ts +3 -0
  114. package/dist/session/session.types.js +14 -2
  115. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  116. package/dist/shared/process/host-process-supervisor.js +1 -1
  117. package/dist/shared/process/process-tree.d.ts +52 -0
  118. package/dist/shared/process/process-tree.js +144 -0
  119. package/dist/shared/process/process.d.ts +67 -0
  120. package/dist/shared/process/process.js +213 -11
  121. package/dist/version.d.ts +1 -1
  122. package/dist/version.js +1 -1
  123. package/dist/worktree/dependency-warmer.d.ts +25 -0
  124. package/dist/worktree/dependency-warmer.js +46 -10
  125. package/dist/worktree/worktree.service.d.ts +10 -1
  126. package/dist/worktree/worktree.service.js +42 -2
  127. package/dist/worktree/worktree.types.d.ts +7 -0
  128. package/package.json +1 -1
@@ -0,0 +1,519 @@
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 { terminateHostLoadStepProcess } from "./host-load-step-reaper.js";
8
+ import { HostCapacityTokenFencedError, HostLoadTokenLedger, } from "./host-load-token-ledger.js";
9
+ export class HostCapacityTimeoutError extends ForgeFailureError {
10
+ stepClass;
11
+ label;
12
+ waitMs;
13
+ code = "host_capacity_timeout";
14
+ constructor(stepClass, label, waitMs, detail) {
15
+ 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");
16
+ this.stepClass = stepClass;
17
+ this.label = label;
18
+ this.waitMs = waitMs;
19
+ this.name = "HostCapacityTimeoutError";
20
+ }
21
+ }
22
+ /**
23
+ * Host-wide admission for heavy steps (decision 0013). Waiters queue
24
+ * foreground before background and FIFO within a class; a waiter that fits may
25
+ * overtake an unfit head until the head has waited past the anti-starvation
26
+ * window. Running steps are never preempted. Reserved cost comes from the
27
+ * shared token ledger, so other processes' steps count against the same budget.
28
+ */
29
+ export class HostLoadGovernor {
30
+ options;
31
+ enabled;
32
+ config;
33
+ ledger;
34
+ waiters = [];
35
+ held = new Map();
36
+ recheckTimer = null;
37
+ renewTimer = null;
38
+ draining = null;
39
+ drainAgain = false;
40
+ /** Own cgroup anonymous memory with no heavy step running: the bridge's baseline. */
41
+ idleOwnMemoryBytes = null;
42
+ constructor(options) {
43
+ this.options = options;
44
+ this.config = options.config ?? loadHostLoadGovernorConfig();
45
+ this.enabled = this.config.mode === "on";
46
+ this.ledger = new HostLoadTokenLedger({
47
+ stateRoot: options.stateRoot,
48
+ leaseMs: this.config.leaseMs,
49
+ now: options.now,
50
+ liveness: options.liveness,
51
+ owner: options.owner,
52
+ terminateStep: options.terminateStep,
53
+ suspendedMs: options.suspendedMs,
54
+ // Every ledger transaction renews the steps this governor is running.
55
+ heldTokens: () => [...this.held.values()].map(entry => entry.token),
56
+ });
57
+ }
58
+ get maxWaitMs() {
59
+ return this.config.maxWaitMs;
60
+ }
61
+ async acquire(request, options = {}) {
62
+ if (!this.enabled)
63
+ throw new Error("host_load_governor_disabled: acquire() requires FORGE_HOST_LOAD_GOVERNOR=on.");
64
+ const { signal } = options;
65
+ if (signal?.aborted)
66
+ throw abortError(signal);
67
+ await this.options.load.start().catch(() => undefined);
68
+ if (signal?.aborted)
69
+ throw abortError(signal);
70
+ return await new Promise((resolve, reject) => {
71
+ const waiter = {
72
+ request,
73
+ enqueuedAtMs: monotonicNowMs(),
74
+ signal,
75
+ onWaiting: options.onWaiting,
76
+ resolve,
77
+ reject,
78
+ abort: () => this.settle(waiter, () => reject(abortError(signal))),
79
+ deadline: null,
80
+ lastDecision: null,
81
+ settled: false,
82
+ };
83
+ 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);
84
+ waiter.deadline.unref?.();
85
+ signal?.addEventListener("abort", waiter.abort, { once: true });
86
+ // Foreground goes ahead of background, except background that has already
87
+ // waited past the anti-starvation window: steady foreground load cannot starve it.
88
+ const backgroundIndex = request.priority === "foreground"
89
+ ? this.waiters.findIndex(candidate => candidate.request.priority === "background"
90
+ && waiter.enqueuedAtMs - candidate.enqueuedAtMs < this.config.antiStarvationMs)
91
+ : -1;
92
+ if (backgroundIndex < 0)
93
+ this.waiters.push(waiter);
94
+ else
95
+ this.waiters.splice(backgroundIndex, 0, waiter);
96
+ this.armRecheck();
97
+ void this.drain();
98
+ });
99
+ }
100
+ /** Reclaims tokens whose owner is gone or whose lease expired (bridge startup). */
101
+ async reclaim() {
102
+ if (!this.enabled)
103
+ return [];
104
+ const outcome = await this.ledger.transaction(() => undefined);
105
+ this.applyHeldOutcome(outcome);
106
+ if (outcome.reclaimed.length > 0)
107
+ void this.drain();
108
+ return outcome.reclaimed;
109
+ }
110
+ /** Returns dead owners' unrecorded tokens the caller proved stopped (see the ledger). */
111
+ async releaseOrphaned(belongs) {
112
+ if (!this.enabled)
113
+ return [];
114
+ const released = await this.ledger.releaseOrphaned(belongs);
115
+ if (released.length > 0)
116
+ void this.drain();
117
+ return released;
118
+ }
119
+ /**
120
+ * Attempt teardown: cancels the attempt's queued steps and stops its running
121
+ * ones (their `fenced` signal aborts with dispatch_cancelled). A running step
122
+ * keeps its token, and its cost, until the step itself returns it once its
123
+ * processes are gone, so the capacity is never reused while it still runs.
124
+ */
125
+ stopAttempt(dispatchAttemptId) {
126
+ if (!this.enabled)
127
+ return;
128
+ this.cancelAttemptWaiters(dispatchAttemptId);
129
+ for (const entry of this.held.values()) {
130
+ if (entry.token.dispatchAttemptId !== dispatchAttemptId)
131
+ continue;
132
+ this.lose(entry, new ForgeFailureError("dispatch_cancelled", "dispatch_cancelled: the attempt was torn down while this step ran; it was stopped before its host capacity was returned.", "bridge"));
133
+ }
134
+ }
135
+ /**
136
+ * Cancels the attempt's queued steps and returns every token it holds at
137
+ * once. Only for callers that know the attempt's steps are no longer running;
138
+ * attempt teardown uses stopAttempt.
139
+ */
140
+ async releaseAttempt(dispatchAttemptId) {
141
+ if (!this.enabled)
142
+ return;
143
+ this.cancelAttemptWaiters(dispatchAttemptId);
144
+ const owned = [...this.held.values()].filter(entry => entry.token.dispatchAttemptId === dispatchAttemptId);
145
+ await Promise.allSettled(owned.map(entry => this.releaseHeld(entry)));
146
+ }
147
+ cancelAttemptWaiters(dispatchAttemptId) {
148
+ for (const waiter of [...this.waiters]) {
149
+ if (waiter.request.dispatchAttemptId !== dispatchAttemptId)
150
+ continue;
151
+ this.settle(waiter, () => waiter.reject(new ForgeFailureError("dispatch_cancelled", "dispatch_cancelled: the attempt was torn down while its step waited for host capacity.", "bridge")));
152
+ }
153
+ }
154
+ /** Waiting and admitted steps of this process, for diagnostics. */
155
+ snapshot() {
156
+ return { waiting: this.waiters.length, held: [...this.held.values()].map(entry => entry.token) };
157
+ }
158
+ async drain() {
159
+ if (this.draining) {
160
+ this.drainAgain = true;
161
+ return await this.draining;
162
+ }
163
+ this.draining = (async () => {
164
+ do {
165
+ this.drainAgain = false;
166
+ await this.drainOnce().catch(error => this.failWaiters(error));
167
+ } while (this.drainAgain && this.waiters.length > 0);
168
+ })().finally(() => {
169
+ this.draining = null;
170
+ });
171
+ return await this.draining;
172
+ }
173
+ async drainOnce() {
174
+ if (this.waiters.length === 0)
175
+ return;
176
+ const signals = this.readSignals();
177
+ const logicalCpus = this.logicalCpus();
178
+ const nowMs = monotonicNowMs();
179
+ const outcomes = [];
180
+ const outcome = await this.ledger.transaction(transaction => {
181
+ const runningMemoryBytes = this.runningStepsMemoryBytes(transaction.tokens);
182
+ const head = this.waiters[0];
183
+ const headStarving = head !== undefined && nowMs - head.enqueuedAtMs >= this.config.antiStarvationMs;
184
+ for (const waiter of this.waiters) {
185
+ if (waiter.settled)
186
+ continue;
187
+ const computed = decideHostLoadAdmission({
188
+ request: waiter.request.cost,
189
+ running: transaction.tokens.map(token => token.cost),
190
+ runningMemoryBytes,
191
+ logicalCpus,
192
+ signals,
193
+ config: this.config,
194
+ });
195
+ const decision = transaction.recoveringUntil
196
+ ? {
197
+ ...computed,
198
+ admitted: false,
199
+ reason: "ledger_recovering",
200
+ detail: `The host load ledger was corrupt and was quarantined; admissions resume at ${transaction.recoveringUntil}, once running steps have restored their reservations.`,
201
+ }
202
+ : computed;
203
+ outcomes.push({ waiter, decision, token: decision.admitted ? transaction.issue(waiter.request) : null });
204
+ // A starving head blocks the queue so running steps drain and it can start.
205
+ if (waiter === head && headStarving && !decision.admitted)
206
+ break;
207
+ }
208
+ });
209
+ this.applyHeldOutcome(outcome);
210
+ for (const { waiter, token, decision } of outcomes) {
211
+ if (!token) {
212
+ const first = waiter.lastDecision === null;
213
+ waiter.lastDecision = decision;
214
+ if (first && !waiter.settled)
215
+ void Promise.resolve(waiter.onWaiting?.(decision)).catch(() => undefined);
216
+ continue;
217
+ }
218
+ const entry = {
219
+ token,
220
+ fencedController: new AbortController(),
221
+ fencedError: null,
222
+ renewedAtMs: monotonicNowMs(),
223
+ releasing: false,
224
+ releaseInFlight: null,
225
+ gone: false,
226
+ retainedUntil: null,
227
+ retainCheck: null,
228
+ };
229
+ this.held.set(token.tokenId, entry);
230
+ this.armRenewal();
231
+ if (waiter.settled) {
232
+ // Cancelled or timed out while the decision was being made.
233
+ void this.releaseHeld(entry).catch(() => undefined);
234
+ continue;
235
+ }
236
+ const waitMs = Math.max(0, monotonicNowMs() - waiter.enqueuedAtMs);
237
+ this.settle(waiter, () => waiter.resolve({
238
+ tokenId: token.tokenId,
239
+ fencingToken: token.fencingToken,
240
+ stepClass: token.stepClass,
241
+ waitMs,
242
+ decision,
243
+ fenced: entry.fencedController.signal,
244
+ attachProcess: stepProcess => this.attachProcess(entry, stepProcess),
245
+ release: () => this.releaseHeld(entry),
246
+ retainUntilStopped: (stillGone, reason) => this.retainUntilStopped(entry, stillGone, reason),
247
+ }));
248
+ }
249
+ }
250
+ readSignals() {
251
+ const snapshot = this.options.load.current();
252
+ const cpu = snapshot?.systemPressure?.cpu?.some;
253
+ const sampledAtMs = snapshot ? Date.parse(snapshot.sampledAt) : Number.NaN;
254
+ const now = this.options.now?.() ?? Date.now();
255
+ if (!snapshot?.psiAvailable || !cpu || !Number.isFinite(sampledAtMs) || now - sampledAtMs > this.config.sampleStaleMs) {
256
+ return null;
257
+ }
258
+ // Own-cgroup numbers are trusted only for a dedicated cgroup (step 1's ownCgroupDedicated).
259
+ const attribution = snapshot.ownCgroupDedicated ? this.options.load.cpuAttribution?.() ?? null : null;
260
+ return {
261
+ cpuSomeAvg10: cpu.avg10,
262
+ cpuPressuredSamples: this.pressureStreak(sampledAtMs, cpu.avg10),
263
+ memoryFullAvg10: snapshot.systemPressure?.memory?.full?.avg10 ?? null,
264
+ memoryAvailableBytes: tighterMemory(snapshot.memoryAvailableBytes, this.options.load.cgroupMemoryHeadroomBytes?.() ?? null),
265
+ externalCpuCores: attribution?.sampledAt === snapshot.sampledAt ? attribution.externalCoresInUse : null,
266
+ };
267
+ }
268
+ /**
269
+ * Consecutive pressured samples ending with the latest one, read from the
270
+ * sampler's history so samples taken while nothing waited still count. A gap
271
+ * in sampling (sampler stopped, host suspended) breaks the streak.
272
+ */
273
+ pressureStreak(latestAtMs, latestAvg10) {
274
+ if (latestAvg10 < this.config.cpuPressureThreshold)
275
+ return 0;
276
+ let streak = 1;
277
+ let laterAtMs = latestAtMs;
278
+ const history = this.options.load.recent();
279
+ for (let index = history.length - 1; index >= 0 && streak < this.config.backpressureSamples; index -= 1) {
280
+ const sample = history[index];
281
+ const atMs = Date.parse(sample.sampledAt);
282
+ if (!Number.isFinite(atMs) || atMs >= laterAtMs)
283
+ continue;
284
+ if (laterAtMs - atMs > this.config.sampleIntervalMs * 1.5)
285
+ break;
286
+ const avg10 = sample.psiAvailable ? sample.systemPressure?.cpu?.some?.avg10 : undefined;
287
+ if (avg10 === undefined || avg10 < this.config.cpuPressureThreshold)
288
+ break;
289
+ streak += 1;
290
+ laterAtMs = atMs;
291
+ }
292
+ return streak;
293
+ }
294
+ /**
295
+ * Memory the running steps already use, which MemAvailable already reflects,
296
+ * so the budget does not count it twice. Measured from the dedicated cgroup
297
+ * above its idle baseline; without one, a step admitted longer than the ramp
298
+ * window ago is assumed to hold its reservation. Never above the reservations.
299
+ */
300
+ runningStepsMemoryBytes(tokens) {
301
+ const snapshot = this.options.load.current();
302
+ const ownMemory = snapshot?.ownCgroupDedicated ? snapshot.ownCgroup?.memoryAnonBytes ?? null : null;
303
+ if (tokens.length === 0) {
304
+ if (ownMemory !== null)
305
+ this.idleOwnMemoryBytes = ownMemory;
306
+ return 0;
307
+ }
308
+ const reserved = tokens.reduce((sum, token) => sum + token.cost.memoryBytes, 0);
309
+ if (ownMemory !== null && this.idleOwnMemoryBytes !== null) {
310
+ return Math.min(reserved, Math.max(0, ownMemory - this.idleOwnMemoryBytes));
311
+ }
312
+ const now = this.options.now?.() ?? Date.now();
313
+ return tokens
314
+ .filter(token => now - Date.parse(token.admittedAt) >= this.config.memoryRampMs)
315
+ .reduce((sum, token) => sum + token.cost.memoryBytes, 0);
316
+ }
317
+ logicalCpus() {
318
+ const reported = this.options.load.facts()?.logicalThreads;
319
+ if (reported && reported > 0)
320
+ return reported;
321
+ return Math.max(1, typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length);
322
+ }
323
+ settle(waiter, complete) {
324
+ if (waiter.settled)
325
+ return;
326
+ waiter.settled = true;
327
+ if (waiter.deadline)
328
+ clearTimeout(waiter.deadline);
329
+ waiter.signal?.removeEventListener("abort", waiter.abort);
330
+ const index = this.waiters.indexOf(waiter);
331
+ if (index >= 0)
332
+ this.waiters.splice(index, 1);
333
+ if (this.waiters.length === 0)
334
+ this.disarmRecheck();
335
+ complete();
336
+ }
337
+ /** Renewed tokens reset their lease clock; fenced ones stop their steps (they keep their cost until released). */
338
+ applyHeldOutcome(outcome) {
339
+ const nowMs = monotonicNowMs();
340
+ for (const token of outcome.renewed) {
341
+ const entry = this.held.get(token.tokenId);
342
+ if (entry?.token.fencingToken === token.fencingToken)
343
+ entry.renewedAtMs = nowMs;
344
+ }
345
+ for (const token of outcome.fenced) {
346
+ const entry = this.held.get(token.tokenId);
347
+ if (!entry || entry.token.fencingToken !== token.fencingToken)
348
+ continue;
349
+ entry.fencedError ??= new HostCapacityTokenFencedError(token.tokenId, "renew");
350
+ this.lose(entry, entry.fencedError);
351
+ }
352
+ }
353
+ /** The step must stop: its reservation is no longer guaranteed. */
354
+ lose(entry, reason) {
355
+ if (entry.gone || entry.releasing || entry.fencedController.signal.aborted)
356
+ return;
357
+ entry.fencedController.abort(reason);
358
+ }
359
+ /** Ledger failures reach every queued step instead of leaving it to time out. */
360
+ failWaiters(error) {
361
+ const failure = error instanceof HostCapacityLedgerUnavailableError
362
+ ? error
363
+ : new HostCapacityLedgerUnavailableError(`the admission decision failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
364
+ for (const waiter of [...this.waiters])
365
+ this.settle(waiter, () => waiter.reject(failure));
366
+ }
367
+ async attachProcess(entry, stepProcess) {
368
+ if (entry.fencedError)
369
+ throw entry.fencedError;
370
+ if (entry.gone || entry.releasing)
371
+ return;
372
+ const outcome = await this.ledger.transaction(transaction => transaction.attach(entry.token.tokenId, entry.token.fencingToken, stepProcess));
373
+ this.applyHeldOutcome(outcome);
374
+ if (outcome.result)
375
+ entry.token = outcome.result;
376
+ else
377
+ throw entry.fencedError ?? new HostCapacityTokenFencedError(entry.token.tokenId, "renew");
378
+ }
379
+ /**
380
+ * Returns a step's token. It stays held (and renewed) until the ledger takes
381
+ * it back, so a ledger outage cannot leave it to lapse into a fenced
382
+ * reservation; the renewal timer retries the release. A fenced token is
383
+ * removed too (its step is over) and the release reports the fence.
384
+ */
385
+ async releaseHeld(entry) {
386
+ if (entry.gone)
387
+ return;
388
+ entry.releasing = true;
389
+ entry.releaseInFlight ??= (async () => {
390
+ try {
391
+ await this.ledger.release(entry.token.tokenId, entry.token.fencingToken);
392
+ this.forget(entry);
393
+ }
394
+ catch (error) {
395
+ if (error instanceof HostCapacityTokenFencedError)
396
+ this.forget(entry);
397
+ throw error;
398
+ }
399
+ finally {
400
+ entry.releaseInFlight = null;
401
+ void this.drain();
402
+ }
403
+ })();
404
+ return await entry.releaseInFlight;
405
+ }
406
+ forget(entry) {
407
+ entry.gone = true;
408
+ this.held.delete(entry.token.tokenId);
409
+ if (this.held.size === 0)
410
+ this.disarmRenewal();
411
+ }
412
+ armRecheck() {
413
+ if (this.recheckTimer)
414
+ return;
415
+ // Capacity can return without a local release: another process's token, a
416
+ // new pressure sample, or external load ending.
417
+ this.recheckTimer = setInterval(() => void this.drain(), this.config.recheckIntervalMs);
418
+ this.recheckTimer.unref?.();
419
+ }
420
+ disarmRecheck() {
421
+ if (this.recheckTimer)
422
+ clearInterval(this.recheckTimer);
423
+ this.recheckTimer = null;
424
+ }
425
+ armRenewal() {
426
+ if (this.renewTimer)
427
+ return;
428
+ this.renewTimer = setInterval(() => void this.renewHeld(), Math.max(10, Math.floor(this.config.leaseMs / 4)));
429
+ this.renewTimer.unref?.();
430
+ }
431
+ disarmRenewal() {
432
+ if (this.renewTimer)
433
+ clearInterval(this.renewTimer);
434
+ this.renewTimer = null;
435
+ }
436
+ /**
437
+ * The step ended but part of its process tree may still run: its token stays
438
+ * held and renewed, with its cost, and the step's own termination check is
439
+ * retried on every renewal tick until it proves the tree gone.
440
+ */
441
+ retainUntilStopped(entry, stillGone, reason) {
442
+ if (entry.gone || entry.releasing)
443
+ return;
444
+ this.lose(entry, reason);
445
+ const terminate = this.options.terminateStep ?? terminateHostLoadStepProcess;
446
+ entry.retainedUntil = stillGone
447
+ // The tree recorded on the token (supervised builds, installs) is stopped and checked.
448
+ ?? (entry.token.stepProcess ? async () => await terminate(entry.token.stepProcess) : "attempt_teardown");
449
+ this.armRenewal();
450
+ }
451
+ /**
452
+ * Attempt teardown stopped the attempt's processes (its process supervisor
453
+ * proved them gone): tokens kept for a tree nothing else can check are returned.
454
+ */
455
+ async releaseRetainedAfterTeardown(dispatchAttemptId) {
456
+ if (!this.enabled)
457
+ return;
458
+ const settled = [...this.held.values()].filter(entry => entry.token.dispatchAttemptId === dispatchAttemptId && entry.retainedUntil === "attempt_teardown");
459
+ for (const entry of settled)
460
+ entry.retainedUntil = null;
461
+ await Promise.allSettled(settled.map(entry => this.releaseHeld(entry)));
462
+ }
463
+ checkRetained(entry) {
464
+ if (!entry.retainedUntil || entry.retainedUntil === "attempt_teardown" || entry.retainCheck)
465
+ return;
466
+ const stillGone = entry.retainedUntil;
467
+ entry.retainCheck = (async () => {
468
+ try {
469
+ if (await stillGone().catch(() => false)) {
470
+ entry.retainedUntil = null;
471
+ await this.releaseHeld(entry).catch(() => undefined);
472
+ }
473
+ }
474
+ finally {
475
+ entry.retainCheck = null;
476
+ }
477
+ })();
478
+ }
479
+ async renewHeld() {
480
+ if (this.held.size === 0)
481
+ return;
482
+ for (const entry of this.held.values()) {
483
+ // A release the ledger could not take is retried until it lands.
484
+ if (entry.releasing && !entry.releaseInFlight)
485
+ void this.releaseHeld(entry).catch(() => undefined);
486
+ this.checkRetained(entry);
487
+ }
488
+ try {
489
+ // The ledger renews every held token at the start of each transaction and
490
+ // reports the fenced ones.
491
+ this.applyHeldOutcome(await this.ledger.transaction(() => undefined));
492
+ }
493
+ catch (error) {
494
+ // A brief outage is retried on the next tick. Once a whole lease passes
495
+ // without a renewal, another process may already have fenced the token.
496
+ const nowMs = monotonicNowMs();
497
+ for (const entry of this.held.values()) {
498
+ if (nowMs - entry.renewedAtMs < this.config.leaseMs)
499
+ continue;
500
+ this.lose(entry, error instanceof HostCapacityLedgerUnavailableError
501
+ ? error
502
+ : new HostCapacityLedgerUnavailableError("the host load token could not be renewed.", { cause: error }));
503
+ }
504
+ }
505
+ }
506
+ }
507
+ /** The cgroup limit's headroom when one is set, never above host MemAvailable. */
508
+ function tighterMemory(hostAvailable, cgroupHeadroom) {
509
+ if (cgroupHeadroom === null)
510
+ return hostAvailable;
511
+ return hostAvailable === null ? cgroupHeadroom : Math.min(hostAvailable, cgroupHeadroom);
512
+ }
513
+ function abortError(signal) {
514
+ if (signal.reason instanceof Error)
515
+ return signal.reason;
516
+ const error = new Error(typeof signal.reason === "string" ? signal.reason : "The host capacity wait was cancelled.");
517
+ error.name = "AbortError";
518
+ return error;
519
+ }
@@ -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
+ }