@loucompanion/forge-bridge 0.1.4-dev.9e8a5b93cbcb → 0.1.4-dev.bbb61d3d6127

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 (89) hide show
  1. package/README.md +2 -2
  2. package/dist/bridge/bridge.service.d.ts +14 -1
  3. package/dist/bridge/bridge.service.js +73 -8
  4. package/dist/bridge/bridge.types.d.ts +11 -0
  5. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  6. package/dist/bridge/dispatch-result-outbox.js +31 -6
  7. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  8. package/dist/bridge/runner-host-capabilities.js +4 -0
  9. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  10. package/dist/bridge/test-postgres-capability.js +120 -0
  11. package/dist/cli/cli.service.js +3 -1
  12. package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
  13. package/dist/runtime/attempt-process-supervisor.js +50 -0
  14. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  15. package/dist/runtime/host-database-capability-boundary.js +1 -0
  16. package/dist/runtime/host-facts.d.ts +35 -0
  17. package/dist/runtime/host-facts.js +95 -0
  18. package/dist/runtime/host-load-admission.d.ts +52 -0
  19. package/dist/runtime/host-load-admission.js +84 -0
  20. package/dist/runtime/host-load-forge-cgroups.d.ts +8 -0
  21. package/dist/runtime/host-load-forge-cgroups.js +51 -0
  22. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  23. package/dist/runtime/host-load-governor-config.js +46 -0
  24. package/dist/runtime/host-load-governor.d.ts +123 -0
  25. package/dist/runtime/host-load-governor.js +415 -0
  26. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  27. package/dist/runtime/host-load-ledger-lock.js +185 -0
  28. package/dist/runtime/host-load-sampler.d.ts +121 -0
  29. package/dist/runtime/host-load-sampler.js +224 -0
  30. package/dist/runtime/host-load-step-class.d.ts +33 -0
  31. package/dist/runtime/host-load-step-class.js +46 -0
  32. package/dist/runtime/host-load-token-ledger.d.ts +135 -0
  33. package/dist/runtime/host-load-token-ledger.js +345 -0
  34. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  35. package/dist/runtime/host-pressure-stall.js +168 -0
  36. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  37. package/dist/runtime/host-runtime-contract.js +6 -1
  38. package/dist/runtime/host-runtime-lease.d.ts +13 -2
  39. package/dist/runtime/host-runtime-lease.js +82 -11
  40. package/dist/runtime/host-runtime-promotion.js +12 -0
  41. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  42. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  43. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  44. package/dist/runtime/host-runtime-requirements.js +117 -0
  45. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  46. package/dist/runtime/managed-command-teardown.js +607 -0
  47. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  48. package/dist/runtime/playwright-browser-cache.js +227 -0
  49. package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
  50. package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
  51. package/dist/session/managed-attempt-tools.d.ts +25 -0
  52. package/dist/session/managed-attempt-tools.js +212 -15
  53. package/dist/session/managed-build-coordinator.d.ts +1 -1
  54. package/dist/session/managed-build-coordinator.js +4 -1
  55. package/dist/session/phase-completion.artifacts.js +4 -0
  56. package/dist/session/phase-completion.runtime.js +22 -17
  57. package/dist/session/pre-publication-host-load.d.ts +27 -0
  58. package/dist/session/pre-publication-host-load.js +96 -0
  59. package/dist/session/pre-publication-process.d.ts +20 -0
  60. package/dist/session/pre-publication-process.js +97 -0
  61. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  62. package/dist/session/pre-publication-skipped-tests.js +109 -0
  63. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  64. package/dist/session/pre-publication-step-execution.js +49 -0
  65. package/dist/session/pre-publication-validation.d.ts +9 -9
  66. package/dist/session/pre-publication-validation.js +44 -112
  67. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  68. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  69. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  70. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  71. package/dist/session/provider-cli/provider-cli.process.d.ts +35 -1
  72. package/dist/session/provider-cli/provider-cli.process.js +187 -17
  73. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  74. package/dist/session/provider-cli/provider-cli.prompts.js +15 -0
  75. package/dist/session/provider-cli/provider-cli.service.js +126 -26
  76. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  77. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  78. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  79. package/dist/session/provider-cli/provider-output-state.js +9 -0
  80. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  81. package/dist/session/publishable-worktree-changes.js +193 -0
  82. package/dist/session/session.base.d.ts +3 -0
  83. package/dist/session/session.service.d.ts +2 -0
  84. package/dist/session/session.service.js +5 -0
  85. package/dist/session/session.types.d.ts +3 -0
  86. package/dist/session/session.types.js +14 -2
  87. package/dist/version.d.ts +1 -1
  88. package/dist/version.js +1 -1
  89. package/package.json +1 -1
@@ -0,0 +1,123 @@
1
+ import { ForgeFailureError } from "../session/session.types.js";
2
+ import { type HostLoadAdmissionDecision } from "./host-load-admission.js";
3
+ import { type HostLoadGovernorConfig } from "./host-load-governor-config.js";
4
+ import type { HostLoadGovernorSource } from "./host-load-sampler.js";
5
+ import type { HostLoadStepCost } from "./host-load-step-class.js";
6
+ import { type HostLoadOwnerLiveness, type HostLoadToken, type HostLoadTokenOwner, type HostLoadTokenPriority } from "./host-load-token-ledger.js";
7
+ export interface HostLoadStepRequest {
8
+ readonly stepClass: string;
9
+ /** What the step is, for diagnostics (for example the validation check id). */
10
+ readonly label: string;
11
+ readonly cost: HostLoadStepCost;
12
+ readonly dispatchAttemptId: string | null;
13
+ readonly priority: HostLoadTokenPriority;
14
+ }
15
+ export interface HostLoadAcquireOptions {
16
+ readonly signal?: AbortSignal;
17
+ /** Called once, when the first admission decision says the step must wait. */
18
+ readonly onWaiting?: (decision: HostLoadAdmissionDecision) => void | Promise<void>;
19
+ }
20
+ export interface HostLoadAdmission {
21
+ readonly tokenId: string;
22
+ readonly fencingToken: number;
23
+ readonly stepClass: string;
24
+ /** Time spent queued; never counted as step execution time. */
25
+ readonly waitMs: number;
26
+ readonly decision: HostLoadAdmissionDecision;
27
+ /**
28
+ * Aborted when the reservation is lost while the step runs: the token was
29
+ * fenced (its lease lapsed and another process saw it), or the ledger could
30
+ * not renew it for a whole lease. The reason is the failure; the step must stop.
31
+ */
32
+ readonly signal: AbortSignal;
33
+ /** Returns the token. Rejects with host_capacity_token_fenced if it was fenced or reclaimed. */
34
+ release(): Promise<void>;
35
+ }
36
+ /** The gate heavy steps call before launching. */
37
+ export interface HostLoadStepGate {
38
+ readonly enabled: boolean;
39
+ acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
40
+ }
41
+ export declare class HostCapacityTimeoutError extends ForgeFailureError {
42
+ readonly stepClass: string;
43
+ readonly label: string;
44
+ readonly waitMs: number;
45
+ readonly code = "host_capacity_timeout";
46
+ constructor(stepClass: string, label: string, waitMs: number, detail: string);
47
+ }
48
+ export interface HostLoadGovernorOptions {
49
+ readonly stateRoot: string;
50
+ readonly load: HostLoadGovernorSource;
51
+ readonly config?: HostLoadGovernorConfig;
52
+ readonly liveness?: HostLoadOwnerLiveness;
53
+ /** Owner recorded on tokens (tests model separate processes); defaults to this process. */
54
+ readonly owner?: HostLoadTokenOwner;
55
+ readonly now?: () => number;
56
+ }
57
+ /**
58
+ * Host-wide admission for heavy steps (decision 0013). Waiters queue
59
+ * foreground before background and FIFO within a class; a waiter that fits may
60
+ * overtake an unfit head until the head has waited past the anti-starvation
61
+ * window. Running steps are never preempted. Reserved cost comes from the
62
+ * shared token ledger, so other processes' steps count against the same budget.
63
+ */
64
+ export declare class HostLoadGovernor implements HostLoadStepGate {
65
+ private readonly options;
66
+ readonly enabled: boolean;
67
+ private readonly config;
68
+ private readonly ledger;
69
+ private readonly waiters;
70
+ private readonly held;
71
+ private recheckTimer;
72
+ private renewTimer;
73
+ private draining;
74
+ private drainAgain;
75
+ /** Own cgroup anonymous memory with no heavy step running: the bridge's baseline. */
76
+ private idleOwnMemoryBytes;
77
+ constructor(options: HostLoadGovernorOptions);
78
+ acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
79
+ /** Reclaims tokens whose owner is gone or whose lease expired (bridge startup). */
80
+ reclaim(): Promise<readonly HostLoadToken[]>;
81
+ /** Attempt teardown: cancels the attempt's waiters and returns every token it holds. */
82
+ releaseAttempt(dispatchAttemptId: string): Promise<void>;
83
+ /** Waiting and admitted steps of this process, for diagnostics. */
84
+ snapshot(): {
85
+ readonly waiting: number;
86
+ readonly held: readonly HostLoadToken[];
87
+ };
88
+ private drain;
89
+ private drainOnce;
90
+ private readSignals;
91
+ /**
92
+ * Consecutive pressured samples ending with the latest one, read from the
93
+ * sampler's history so samples taken while nothing waited still count. A gap
94
+ * in sampling (sampler stopped, host suspended) breaks the streak.
95
+ */
96
+ private pressureStreak;
97
+ /**
98
+ * Memory the running steps already use, which MemAvailable already reflects,
99
+ * so the budget does not count it twice. Measured from the dedicated cgroup
100
+ * above its idle baseline; without one, a step admitted longer than the ramp
101
+ * window ago is assumed to hold its reservation. Never above the reservations.
102
+ */
103
+ private runningStepsMemoryBytes;
104
+ private logicalCpus;
105
+ private settle;
106
+ /**
107
+ * Returns a step's token. It stays held (and renewed) until the ledger takes
108
+ * it back, so a ledger outage cannot leave it to lapse into a fenced
109
+ * reservation; the renewal timer retries the release.
110
+ */
111
+ private releaseHeld;
112
+ private forget;
113
+ /** The step must stop: its reservation is no longer guaranteed. */
114
+ private lose;
115
+ private onHeldTokens;
116
+ /** Ledger failures reach every queued step instead of leaving it to time out. */
117
+ private failWaiters;
118
+ private armRecheck;
119
+ private disarmRecheck;
120
+ private armRenewal;
121
+ private disarmRenewal;
122
+ private renewHeld;
123
+ }
@@ -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
+ }