@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.
- package/README.md +2 -2
- package/dist/bridge/bridge.service.js +4 -3
- package/dist/cli/cli.service.js +3 -1
- package/dist/runtime/host-load-admission.d.ts +52 -0
- package/dist/runtime/host-load-admission.js +84 -0
- package/dist/runtime/host-load-forge-cgroups.d.ts +8 -0
- package/dist/runtime/host-load-forge-cgroups.js +51 -0
- package/dist/runtime/host-load-governor-config.d.ts +34 -0
- package/dist/runtime/host-load-governor-config.js +46 -0
- package/dist/runtime/host-load-governor.d.ts +123 -0
- package/dist/runtime/host-load-governor.js +415 -0
- package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
- package/dist/runtime/host-load-ledger-lock.js +185 -0
- package/dist/runtime/host-load-sampler.d.ts +38 -0
- package/dist/runtime/host-load-sampler.js +66 -6
- package/dist/runtime/host-load-step-class.d.ts +33 -0
- package/dist/runtime/host-load-step-class.js +46 -0
- package/dist/runtime/host-load-token-ledger.d.ts +135 -0
- package/dist/runtime/host-load-token-ledger.js +345 -0
- package/dist/runtime/host-pressure-stall.d.ts +21 -1
- package/dist/runtime/host-pressure-stall.js +48 -1
- package/dist/runtime/host-runtime-lease.d.ts +7 -1
- package/dist/runtime/host-runtime-lease.js +12 -2
- package/dist/session/pre-publication-host-load.d.ts +27 -0
- package/dist/session/pre-publication-host-load.js +96 -0
- package/dist/session/pre-publication-step-execution.d.ts +11 -0
- package/dist/session/pre-publication-step-execution.js +49 -0
- package/dist/session/pre-publication-validation.d.ts +9 -9
- package/dist/session/pre-publication-validation.js +17 -55
- package/dist/session/provider-cli/provider-cli.process.d.ts +7 -0
- package/dist/session/provider-cli/provider-cli.process.js +13 -5
- package/dist/session/provider-cli/provider-cli.service.js +28 -5
- package/dist/session/session.types.js +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { ForgeFailureError } from "../session/session.types.js";
|
|
5
|
+
import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
|
|
6
|
+
import { HostCapacityLedgerUnavailableError, HostLoadLedgerLock } from "./host-load-ledger-lock.js";
|
|
7
|
+
const processInstanceId = randomUUID();
|
|
8
|
+
const maximumLedgerBytes = 1024 * 1024;
|
|
9
|
+
export class HostCapacityTokenFencedError extends ForgeFailureError {
|
|
10
|
+
tokenId;
|
|
11
|
+
code = "host_capacity_token_fenced";
|
|
12
|
+
constructor(tokenId, action) {
|
|
13
|
+
super("host_capacity_token_fenced", action === "released_fenced"
|
|
14
|
+
? `host_capacity_token_fenced: host load token ${tokenId} was fenced after its lease lapsed; the step ran past its lease, and its reservation has now been returned.`
|
|
15
|
+
: `host_capacity_token_fenced: host load token ${tokenId} was fenced, reclaimed or superseded; the ${action} was rejected so it cannot affect another step's reservation.`, "bridge");
|
|
16
|
+
this.tokenId = tokenId;
|
|
17
|
+
this.name = "HostCapacityTokenFencedError";
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
let cachedCurrentOwner = null;
|
|
21
|
+
/**
|
|
22
|
+
* This process as a token owner, computed once. The birth marker is read only
|
|
23
|
+
* on Linux (a cheap /proc read); elsewhere it would mean a synchronous process
|
|
24
|
+
* spawn, so pid reuse there is covered by the lease and the instance id.
|
|
25
|
+
*/
|
|
26
|
+
export function currentHostLoadTokenOwner() {
|
|
27
|
+
cachedCurrentOwner ??= {
|
|
28
|
+
pid: process.pid,
|
|
29
|
+
processIdentity: linuxProcessIdentity(process.pid),
|
|
30
|
+
processInstanceId,
|
|
31
|
+
};
|
|
32
|
+
return cachedCurrentOwner;
|
|
33
|
+
}
|
|
34
|
+
/** Owner liveness from the OS: dead pid, or a pid reused by a different process, is gone. */
|
|
35
|
+
export const processHostLoadOwnerLiveness = {
|
|
36
|
+
isLive(owner) {
|
|
37
|
+
if (owner.pid === process.pid)
|
|
38
|
+
return owner.processInstanceId === processInstanceId;
|
|
39
|
+
try {
|
|
40
|
+
process.kill(owner.pid, 0);
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (error.code !== "EPERM")
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
if (!owner.processIdentity)
|
|
47
|
+
return true;
|
|
48
|
+
const current = linuxProcessIdentity(owner.pid);
|
|
49
|
+
return current === null || current === owner.processIdentity;
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
function linuxProcessIdentity(pid) {
|
|
53
|
+
return process.platform === "linux" ? captureHostProcessIdentity(pid, "linux") : null;
|
|
54
|
+
}
|
|
55
|
+
export class HostLoadTokenLedger {
|
|
56
|
+
options;
|
|
57
|
+
root;
|
|
58
|
+
ledgerPath;
|
|
59
|
+
now;
|
|
60
|
+
liveness;
|
|
61
|
+
resolvedOwner;
|
|
62
|
+
lock;
|
|
63
|
+
tail = Promise.resolve();
|
|
64
|
+
constructor(options) {
|
|
65
|
+
this.options = options;
|
|
66
|
+
this.root = path.join(options.stateRoot, "host-load-governor");
|
|
67
|
+
this.ledgerPath = path.join(this.root, "tokens.v1.json");
|
|
68
|
+
this.now = options.now ?? Date.now;
|
|
69
|
+
this.liveness = options.liveness ?? processHostLoadOwnerLiveness;
|
|
70
|
+
this.resolvedOwner = options.owner ?? null;
|
|
71
|
+
this.lock = new HostLoadLedgerLock({
|
|
72
|
+
lockPath: path.join(this.root, "tokens.lock"),
|
|
73
|
+
holder: () => this.owner,
|
|
74
|
+
isLive: holder => this.liveness.isLive(holder),
|
|
75
|
+
timeoutMs: options.lockTimeoutMs ?? 10_000,
|
|
76
|
+
beforeStaleBreak: options.beforeStaleLockBreak,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
get owner() {
|
|
80
|
+
this.resolvedOwner ??= currentHostLoadTokenOwner();
|
|
81
|
+
return this.resolvedOwner;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Runs `action` under the cross-process ledger lock against the live token
|
|
85
|
+
* set. Dead or expired tokens are reclaimed first, so every admission
|
|
86
|
+
* decision sees only real reservations.
|
|
87
|
+
*/
|
|
88
|
+
async transaction(action) {
|
|
89
|
+
const run = this.tail.then(() => this.lockedTransaction(action));
|
|
90
|
+
this.tail = run.catch(() => undefined);
|
|
91
|
+
return await run;
|
|
92
|
+
}
|
|
93
|
+
async reclaim() {
|
|
94
|
+
return (await this.transaction(() => undefined)).reclaimed;
|
|
95
|
+
}
|
|
96
|
+
async list() {
|
|
97
|
+
return (await this.transaction(transaction => transaction.tokens)).result;
|
|
98
|
+
}
|
|
99
|
+
/** Extends a token's lease. A fenced, reclaimed or superseded token is rejected. */
|
|
100
|
+
async renew(tokenId, fencingToken) {
|
|
101
|
+
const renewed = (await this.transaction(transaction => transaction.renew(tokenId, fencingToken))).result;
|
|
102
|
+
if (!renewed)
|
|
103
|
+
throw new HostCapacityTokenFencedError(tokenId, "renew");
|
|
104
|
+
return renewed;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Returns a token. A reclaimed or superseded token is rejected, never released
|
|
108
|
+
* twice. A fenced token is removed (its owner's step is over) but still
|
|
109
|
+
* reported as fenced.
|
|
110
|
+
*/
|
|
111
|
+
async release(tokenId, fencingToken) {
|
|
112
|
+
const outcome = (await this.transaction(transaction => {
|
|
113
|
+
const entry = transaction.tokens.find(token => token.tokenId === tokenId && token.fencingToken === fencingToken);
|
|
114
|
+
if (!entry || !transaction.remove(tokenId, fencingToken))
|
|
115
|
+
return "missing";
|
|
116
|
+
return entry.fencedAt ? "fenced" : "released";
|
|
117
|
+
})).result;
|
|
118
|
+
if (outcome === "missing")
|
|
119
|
+
throw new HostCapacityTokenFencedError(tokenId, "release");
|
|
120
|
+
if (outcome === "fenced")
|
|
121
|
+
throw new HostCapacityTokenFencedError(tokenId, "released_fenced");
|
|
122
|
+
}
|
|
123
|
+
async lockedTransaction(action) {
|
|
124
|
+
await fs.mkdir(this.root, { recursive: true, mode: 0o700 }).catch(error => {
|
|
125
|
+
throw new HostCapacityLedgerUnavailableError("the host load ledger directory could not be created.", { cause: error });
|
|
126
|
+
});
|
|
127
|
+
const lockToken = await this.lock.acquire();
|
|
128
|
+
try {
|
|
129
|
+
const { ledger, quarantined } = await this.read();
|
|
130
|
+
const nowMs = this.now();
|
|
131
|
+
const nowIso = new Date(nowMs).toISOString();
|
|
132
|
+
const expiresAt = () => new Date(this.now() + this.options.leaseMs).toISOString();
|
|
133
|
+
const recoveringUntil = ledger.recoveringUntil && Date.parse(ledger.recoveringUntil) > nowMs
|
|
134
|
+
? ledger.recoveringUntil
|
|
135
|
+
: null;
|
|
136
|
+
const key = (token) => `${token.tokenId}:${token.fencingToken}`;
|
|
137
|
+
// Running steps of this owner are renewed (or restored) before anything is reclaimed.
|
|
138
|
+
const held = this.options.heldTokens?.() ?? [];
|
|
139
|
+
const heldKeys = new Set(held.map(key));
|
|
140
|
+
const ledgerKeys = new Set(ledger.tokens.map(key));
|
|
141
|
+
// A held token missing from the ledger keeps its cost. While a quarantined
|
|
142
|
+
// ledger is recovering no step was admitted against the gap, so it is put
|
|
143
|
+
// back as is; otherwise capacity may have been reused, so it comes back fenced.
|
|
144
|
+
const restored = held
|
|
145
|
+
.filter(token => !ledgerKeys.has(key(token)))
|
|
146
|
+
.map(token => ({
|
|
147
|
+
...token,
|
|
148
|
+
expiresAt: expiresAt(),
|
|
149
|
+
fencedAt: token.fencedAt ?? (recoveringUntil ? null : nowIso),
|
|
150
|
+
}));
|
|
151
|
+
const current = [
|
|
152
|
+
...ledger.tokens.map(token => heldKeys.has(key(token)) && !token.fencedAt ? { ...token, expiresAt: expiresAt() } : token),
|
|
153
|
+
...restored,
|
|
154
|
+
];
|
|
155
|
+
// Only a provably gone owner frees capacity. A lapsed lease with a live owner
|
|
156
|
+
// fences the token and keeps its cost: its step may still be running.
|
|
157
|
+
const reclaimed = current.filter(token => !this.liveness.isLive(token.owner));
|
|
158
|
+
let fencedNow = 0;
|
|
159
|
+
let tokens = current
|
|
160
|
+
.filter(token => !reclaimed.includes(token))
|
|
161
|
+
.map(token => {
|
|
162
|
+
if (token.fencedAt || !leaseLapsed(token, nowMs))
|
|
163
|
+
return token;
|
|
164
|
+
fencedNow += 1;
|
|
165
|
+
return { ...token, fencedAt: nowIso };
|
|
166
|
+
});
|
|
167
|
+
let nextFencingToken = Math.max(ledger.nextFencingToken, ...restored.map(token => token.fencingToken + 1));
|
|
168
|
+
let changed = quarantined || reclaimed.length > 0 || fencedNow > 0 || held.length > 0
|
|
169
|
+
|| (ledger.recoveringUntil !== undefined && recoveringUntil === null);
|
|
170
|
+
const transaction = {
|
|
171
|
+
get tokens() { return tokens; },
|
|
172
|
+
recoveringUntil,
|
|
173
|
+
issue: request => {
|
|
174
|
+
const token = {
|
|
175
|
+
tokenId: randomUUID(),
|
|
176
|
+
fencingToken: nextFencingToken,
|
|
177
|
+
stepClass: request.stepClass,
|
|
178
|
+
label: request.label,
|
|
179
|
+
cost: { cpuCores: request.cost.cpuCores, memoryBytes: request.cost.memoryBytes },
|
|
180
|
+
dispatchAttemptId: request.dispatchAttemptId,
|
|
181
|
+
priority: request.priority,
|
|
182
|
+
owner: this.owner,
|
|
183
|
+
admittedAt: new Date(this.now()).toISOString(),
|
|
184
|
+
expiresAt: expiresAt(),
|
|
185
|
+
};
|
|
186
|
+
nextFencingToken += 1;
|
|
187
|
+
tokens = [...tokens, token];
|
|
188
|
+
changed = true;
|
|
189
|
+
return token;
|
|
190
|
+
},
|
|
191
|
+
renew: (tokenId, fencingToken) => {
|
|
192
|
+
const index = tokens.findIndex(token => token.tokenId === tokenId && token.fencingToken === fencingToken);
|
|
193
|
+
if (index < 0 || tokens[index].fencedAt)
|
|
194
|
+
return null;
|
|
195
|
+
const renewed = { ...tokens[index], expiresAt: expiresAt() };
|
|
196
|
+
tokens = tokens.map((token, position) => position === index ? renewed : token);
|
|
197
|
+
changed = true;
|
|
198
|
+
return renewed;
|
|
199
|
+
},
|
|
200
|
+
remove: (tokenId, fencingToken) => {
|
|
201
|
+
const before = tokens.length;
|
|
202
|
+
tokens = tokens.filter(token => !(token.tokenId === tokenId && token.fencingToken === fencingToken));
|
|
203
|
+
changed ||= tokens.length !== before;
|
|
204
|
+
return tokens.length !== before;
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
const result = await action(transaction);
|
|
208
|
+
if (changed) {
|
|
209
|
+
// A lock broken under us (a stalled holder taken for dead) must not commit.
|
|
210
|
+
if (!await this.lock.holds(lockToken)) {
|
|
211
|
+
throw new HostCapacityLedgerUnavailableError("the ledger lock was lost before the update could be written.");
|
|
212
|
+
}
|
|
213
|
+
await this.write({
|
|
214
|
+
schemaVersion: 1,
|
|
215
|
+
nextFencingToken,
|
|
216
|
+
tokens,
|
|
217
|
+
...recoveringUntil ? { recoveringUntil } : {},
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
if (held.length > 0) {
|
|
221
|
+
const heldNow = tokens.filter(token => heldKeys.has(key(token)));
|
|
222
|
+
this.options.onHeldTokens?.({
|
|
223
|
+
renewed: heldNow.filter(token => !token.fencedAt),
|
|
224
|
+
fenced: heldNow.filter(token => Boolean(token.fencedAt)),
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
return { result, reclaimed };
|
|
228
|
+
}
|
|
229
|
+
finally {
|
|
230
|
+
await this.lock.release(lockToken);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
async read() {
|
|
234
|
+
let content;
|
|
235
|
+
try {
|
|
236
|
+
const stat = await fs.lstat(this.ledgerPath);
|
|
237
|
+
if (!stat.isFile() || stat.size > maximumLedgerBytes)
|
|
238
|
+
return await this.quarantine(null);
|
|
239
|
+
content = await fs.readFile(this.ledgerPath, "utf8");
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
if (error.code === "ENOENT")
|
|
243
|
+
return { ledger: emptyLedger(), quarantined: false };
|
|
244
|
+
// EMFILE, EACCES and the like say nothing about the ledger's content: keep it.
|
|
245
|
+
throw new HostCapacityLedgerUnavailableError("the host load ledger could not be read.", { cause: error });
|
|
246
|
+
}
|
|
247
|
+
let parsed;
|
|
248
|
+
try {
|
|
249
|
+
parsed = JSON.parse(content);
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
return await this.quarantine(null);
|
|
253
|
+
}
|
|
254
|
+
const nextFencingToken = Number.isSafeInteger(parsed?.nextFencingToken) ? parsed.nextFencingToken : null;
|
|
255
|
+
// One malformed reservation makes the whole ledger untrustworthy: dropping just
|
|
256
|
+
// that token would turn a possibly running step's cost into free capacity.
|
|
257
|
+
if (parsed?.schemaVersion !== 1 || !Array.isArray(parsed.tokens) || nextFencingToken === null
|
|
258
|
+
|| !parsed.tokens.every(validToken)
|
|
259
|
+
|| !uniqueTokenIds(parsed.tokens)
|
|
260
|
+
|| (parsed.recoveringUntil !== undefined && !Number.isFinite(Date.parse(parsed.recoveringUntil)))) {
|
|
261
|
+
return await this.quarantine(nextFencingToken);
|
|
262
|
+
}
|
|
263
|
+
return {
|
|
264
|
+
ledger: {
|
|
265
|
+
schemaVersion: 1,
|
|
266
|
+
nextFencingToken,
|
|
267
|
+
tokens: parsed.tokens,
|
|
268
|
+
...parsed.recoveringUntil !== undefined ? { recoveringUntil: parsed.recoveringUntil } : {},
|
|
269
|
+
},
|
|
270
|
+
quarantined: false,
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* A corrupt ledger is kept aside for inspection and none of its tokens are
|
|
275
|
+
* trusted. Admissions pause for one lease while live owners, which renew
|
|
276
|
+
* several times per lease, put their running steps' reservations back.
|
|
277
|
+
*/
|
|
278
|
+
async quarantine(nextFencingToken) {
|
|
279
|
+
// A unique name: a second quarantine in the same millisecond must not replace the first copy.
|
|
280
|
+
await fs.rename(this.ledgerPath, `${this.ledgerPath}.corrupt-${this.now()}-${randomUUID()}`).catch(() => undefined);
|
|
281
|
+
return {
|
|
282
|
+
ledger: {
|
|
283
|
+
...emptyLedger(),
|
|
284
|
+
nextFencingToken: Math.max(1, nextFencingToken ?? 1),
|
|
285
|
+
recoveringUntil: new Date(this.now() + this.options.leaseMs).toISOString(),
|
|
286
|
+
},
|
|
287
|
+
quarantined: true,
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
async write(ledger) {
|
|
291
|
+
const temporary = `${this.ledgerPath}.${process.pid}.${randomUUID()}.tmp`;
|
|
292
|
+
try {
|
|
293
|
+
const handle = await fs.open(temporary, "wx", 0o600);
|
|
294
|
+
try {
|
|
295
|
+
await handle.writeFile(`${JSON.stringify(ledger)}\n`);
|
|
296
|
+
await handle.sync();
|
|
297
|
+
}
|
|
298
|
+
finally {
|
|
299
|
+
await handle.close();
|
|
300
|
+
}
|
|
301
|
+
await fs.rename(temporary, this.ledgerPath);
|
|
302
|
+
}
|
|
303
|
+
catch (error) {
|
|
304
|
+
await fs.rm(temporary, { force: true }).catch(() => undefined);
|
|
305
|
+
throw new HostCapacityLedgerUnavailableError("the host load ledger could not be written.", { cause: error });
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
function leaseLapsed(token, nowMs) {
|
|
310
|
+
const expiresAtMs = Date.parse(token.expiresAt);
|
|
311
|
+
return !Number.isFinite(expiresAtMs) || expiresAtMs <= nowMs;
|
|
312
|
+
}
|
|
313
|
+
function emptyLedger() {
|
|
314
|
+
return { schemaVersion: 1, nextFencingToken: 1, tokens: [] };
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Each reservation needs its own identity: with a duplicate tokenId the owner's
|
|
318
|
+
* held map would keep one copy, and one release would drop both reservations.
|
|
319
|
+
*/
|
|
320
|
+
function uniqueTokenIds(tokens) {
|
|
321
|
+
return new Set(tokens.map(token => token.tokenId)).size === tokens.length;
|
|
322
|
+
}
|
|
323
|
+
function validOwner(value) {
|
|
324
|
+
const owner = value;
|
|
325
|
+
return Boolean(owner)
|
|
326
|
+
&& Number.isSafeInteger(owner.pid) && owner.pid > 0
|
|
327
|
+
&& typeof owner.processInstanceId === "string"
|
|
328
|
+
&& (owner.processIdentity === null || typeof owner.processIdentity === "string");
|
|
329
|
+
}
|
|
330
|
+
function validToken(value) {
|
|
331
|
+
const token = value;
|
|
332
|
+
return Boolean(token)
|
|
333
|
+
&& typeof token.tokenId === "string"
|
|
334
|
+
&& Number.isSafeInteger(token.fencingToken)
|
|
335
|
+
&& typeof token.stepClass === "string"
|
|
336
|
+
&& typeof token.label === "string"
|
|
337
|
+
&& Number.isFinite(token.cost?.cpuCores) && token.cost.cpuCores >= 0
|
|
338
|
+
&& Number.isFinite(token.cost?.memoryBytes) && token.cost.memoryBytes >= 0
|
|
339
|
+
&& (token.dispatchAttemptId === null || typeof token.dispatchAttemptId === "string")
|
|
340
|
+
&& (token.priority === "foreground" || token.priority === "background")
|
|
341
|
+
&& validOwner(token.owner)
|
|
342
|
+
&& typeof token.admittedAt === "string"
|
|
343
|
+
&& typeof token.expiresAt === "string"
|
|
344
|
+
&& (token.fencedAt === undefined || token.fencedAt === null || typeof token.fencedAt === "string");
|
|
345
|
+
}
|
|
@@ -27,6 +27,13 @@ export declare function parseMemAvailableBytes(content: string): number | null;
|
|
|
27
27
|
* Returns null on pure cgroup v1 hosts (no `0::` entry) and for the root cgroup.
|
|
28
28
|
*/
|
|
29
29
|
export declare function parseUnifiedCgroupPath(content: string): string | null;
|
|
30
|
+
/**
|
|
31
|
+
* This process's cgroup v2 path from `/proc/self/cgroup`, including the root
|
|
32
|
+
* `/` (a container's own cgroup under a cgroup namespace); null for cgroup v1
|
|
33
|
+
* or a malformed entry. `parseUnifiedCgroupPath` excludes the root, because the
|
|
34
|
+
* root is never the bridge's own unit; memory limits apply there all the same.
|
|
35
|
+
*/
|
|
36
|
+
export declare function parseUnifiedCgroupMembership(content: string): string | null;
|
|
30
37
|
/** The leaf cgroup name, e.g. `forge-bridge.service`. */
|
|
31
38
|
export declare function cgroupLeafName(cgroupPath: string): string | null;
|
|
32
39
|
/**
|
|
@@ -36,6 +43,19 @@ export declare function cgroupLeafName(cgroupPath: string): string | null;
|
|
|
36
43
|
* FORGE_BRIDGE_CGROUP_UNIT. A `.scope` is rejected: a bridge started from a
|
|
37
44
|
* terminal, SSH session or desktop app shares `session-N.scope` /
|
|
38
45
|
* `app-*.scope` with unrelated work (possibly the owner's game).
|
|
39
|
-
* Container cgroups (e.g. `docker-<id>.scope`) are
|
|
46
|
+
* Container cgroups (e.g. `docker-<id>.scope`) are not treated as dedicated yet.
|
|
40
47
|
*/
|
|
41
48
|
export declare function isDedicatedBridgeUnit(unit: string, configuredUnit: string | null | undefined): boolean;
|
|
49
|
+
/** Aggregate host CPU time from /proc/stat, in clock ticks, plus the online CPU count. */
|
|
50
|
+
export interface ProcStatCpuTotals {
|
|
51
|
+
readonly busyTicks: number;
|
|
52
|
+
readonly totalTicks: number;
|
|
53
|
+
readonly cpuCount: number;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Reads the aggregate `cpu` line of /proc/stat. Busy time is user + nice +
|
|
57
|
+
* system + irq + softirq + steal (guest time is already inside user/nice);
|
|
58
|
+
* idle and iowait are not busy. Both counters are additive CPU time, so a
|
|
59
|
+
* cgroup's `cpu.stat` usage over the same window can be subtracted from them.
|
|
60
|
+
*/
|
|
61
|
+
export declare function parseProcStatCpuTotals(content: string): ProcStatCpuTotals | null;
|
|
@@ -97,6 +97,26 @@ export function parseUnifiedCgroupPath(content) {
|
|
|
97
97
|
}
|
|
98
98
|
return null;
|
|
99
99
|
}
|
|
100
|
+
/**
|
|
101
|
+
* This process's cgroup v2 path from `/proc/self/cgroup`, including the root
|
|
102
|
+
* `/` (a container's own cgroup under a cgroup namespace); null for cgroup v1
|
|
103
|
+
* or a malformed entry. `parseUnifiedCgroupPath` excludes the root, because the
|
|
104
|
+
* root is never the bridge's own unit; memory limits apply there all the same.
|
|
105
|
+
*/
|
|
106
|
+
export function parseUnifiedCgroupMembership(content) {
|
|
107
|
+
for (const rawLine of content.split(/\r?\n/u)) {
|
|
108
|
+
const line = rawLine.trim();
|
|
109
|
+
if (!line.startsWith("0::"))
|
|
110
|
+
continue;
|
|
111
|
+
const cgroupPath = line.slice(3).trim();
|
|
112
|
+
if (!cgroupPath.startsWith("/"))
|
|
113
|
+
return null;
|
|
114
|
+
if (cgroupPath.split("/").some(segment => segment === ".."))
|
|
115
|
+
return null;
|
|
116
|
+
return cgroupPath;
|
|
117
|
+
}
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
100
120
|
/** The leaf cgroup name, e.g. `forge-bridge.service`. */
|
|
101
121
|
export function cgroupLeafName(cgroupPath) {
|
|
102
122
|
return cgroupPath.split("/").filter(Boolean).at(-1) ?? null;
|
|
@@ -108,7 +128,7 @@ export function cgroupLeafName(cgroupPath) {
|
|
|
108
128
|
* FORGE_BRIDGE_CGROUP_UNIT. A `.scope` is rejected: a bridge started from a
|
|
109
129
|
* terminal, SSH session or desktop app shares `session-N.scope` /
|
|
110
130
|
* `app-*.scope` with unrelated work (possibly the owner's game).
|
|
111
|
-
* Container cgroups (e.g. `docker-<id>.scope`) are
|
|
131
|
+
* Container cgroups (e.g. `docker-<id>.scope`) are not treated as dedicated yet.
|
|
112
132
|
*/
|
|
113
133
|
export function isDedicatedBridgeUnit(unit, configuredUnit) {
|
|
114
134
|
const configured = configuredUnit?.trim();
|
|
@@ -119,3 +139,30 @@ export function isDedicatedBridgeUnit(unit, configuredUnit) {
|
|
|
119
139
|
&& !/^app-/u.test(unit)
|
|
120
140
|
&& !/^user@\d+\.service$/u.test(unit);
|
|
121
141
|
}
|
|
142
|
+
/**
|
|
143
|
+
* Reads the aggregate `cpu` line of /proc/stat. Busy time is user + nice +
|
|
144
|
+
* system + irq + softirq + steal (guest time is already inside user/nice);
|
|
145
|
+
* idle and iowait are not busy. Both counters are additive CPU time, so a
|
|
146
|
+
* cgroup's `cpu.stat` usage over the same window can be subtracted from them.
|
|
147
|
+
*/
|
|
148
|
+
export function parseProcStatCpuTotals(content) {
|
|
149
|
+
let aggregate = null;
|
|
150
|
+
let cpuCount = 0;
|
|
151
|
+
for (const rawLine of content.split(/\r?\n/u)) {
|
|
152
|
+
const fields = rawLine.trim().split(/\s+/u);
|
|
153
|
+
if (fields[0] === "cpu") {
|
|
154
|
+
const values = fields.slice(1, 9).map(Number);
|
|
155
|
+
if (values.length < 8 || values.some(value => !Number.isSafeInteger(value) || value < 0))
|
|
156
|
+
return null;
|
|
157
|
+
aggregate = values;
|
|
158
|
+
}
|
|
159
|
+
else if (/^cpu\d+$/u.test(fields[0] ?? "")) {
|
|
160
|
+
cpuCount += 1;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (!aggregate || cpuCount === 0)
|
|
164
|
+
return null;
|
|
165
|
+
const [user, nice, system, idle, iowait, irq, softirq, steal] = aggregate;
|
|
166
|
+
const busyTicks = user + nice + system + irq + softirq + steal;
|
|
167
|
+
return { busyTicks, totalTicks: busyTicks + idle + iowait, cpuCount };
|
|
168
|
+
}
|
|
@@ -12,6 +12,8 @@ import { type MemoryAdmissionDiagnostics } from "./memory-capacity.js";
|
|
|
12
12
|
import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
|
|
13
13
|
import { HostParallelPromotionStore } from "./host-runtime-promotion.js";
|
|
14
14
|
import { type HostProcessRecovery } from "../shared/process/host-process-recovery.js";
|
|
15
|
+
import { HostLoadGovernor } from "./host-load-governor.js";
|
|
16
|
+
import { type HostLoadGovernorSource } from "./host-load-sampler.js";
|
|
15
17
|
export interface HostRuntimeLeaseStart {
|
|
16
18
|
readonly lease: RuntimeIsolationLease;
|
|
17
19
|
readonly environment: Readonly<Record<string, string>>;
|
|
@@ -105,6 +107,7 @@ export interface HostRuntimeLeaseRuntime {
|
|
|
105
107
|
reap?(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport>;
|
|
106
108
|
snapshot?(): HostRuntimeCapacitySnapshot;
|
|
107
109
|
}
|
|
110
|
+
export type HostRuntimeAdmissionPriority = "foreground" | "background";
|
|
108
111
|
export interface HostCapacityResourceSample {
|
|
109
112
|
readonly totalMemoryBytes: number;
|
|
110
113
|
readonly availableMemoryBytes: number;
|
|
@@ -143,7 +146,9 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
|
|
|
143
146
|
private readonly capacityConfiguration;
|
|
144
147
|
private readonly memoryAvailability;
|
|
145
148
|
private readonly executionRoot;
|
|
146
|
-
|
|
149
|
+
/** Host-wide admission for heavy steps (decision 0013); inert unless FORGE_HOST_LOAD_GOVERNOR=on. */
|
|
150
|
+
readonly hostLoadGovernor: HostLoadGovernor;
|
|
151
|
+
constructor(stateRoot: string, portBroker?: HostPortBroker, nodeAdapter?: NodeHostRuntimeAdapter, processSupervisors?: AttemptProcessSupervisorRegistry, processRunner?: ProviderProcessRunner, listenerInspector?: HostListenerInspector, promotionStore?: HostParallelPromotionStore, playwrightAdapter?: PlaywrightHostRuntimeAdapter, processRecovery?: HostProcessRecovery, capacityResourceSample?: HostCapacityResourceSample | undefined, executionRoot?: string, databaseBroker?: AttemptDatabaseBroker | null, hostLoad?: HostLoadGovernorSource | null);
|
|
147
152
|
reap(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport>;
|
|
148
153
|
snapshot(): HostRuntimeCapacitySnapshot;
|
|
149
154
|
hasForegroundDemand(): boolean;
|
|
@@ -215,3 +220,4 @@ export declare class HostRuntimeCapacityRequestImpossibleError extends Error {
|
|
|
215
220
|
}
|
|
216
221
|
export declare function hostRuntimeEventResources(lease: RuntimeIsolationLease, runtimeContract?: LoadedHostRuntimeContract, executionClass?: HostRuntimeExecutionClass): Record<string, unknown>;
|
|
217
222
|
export declare function hostRuntimeSingletonKeys(dispatch: RunOnceDispatchPacket): readonly string[];
|
|
223
|
+
export declare function runtimeAdmissionPriority(dispatch: RunOnceDispatchPacket): HostRuntimeAdmissionPriority;
|
|
@@ -30,6 +30,8 @@ import { readCanonicalSourceFile } from "./canonical-source-file.js";
|
|
|
30
30
|
import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
|
|
31
31
|
import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
|
|
32
32
|
import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
|
|
33
|
+
import { HostLoadGovernor } from "./host-load-governor.js";
|
|
34
|
+
import { HostLoadSampler } from "./host-load-sampler.js";
|
|
33
35
|
const hostCapacityWaiterScanLimit = 64;
|
|
34
36
|
const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
|
|
35
37
|
export class HostRuntimeLeaseManager {
|
|
@@ -64,7 +66,9 @@ export class HostRuntimeLeaseManager {
|
|
|
64
66
|
capacityConfiguration;
|
|
65
67
|
memoryAvailability;
|
|
66
68
|
executionRoot;
|
|
67
|
-
|
|
69
|
+
/** Host-wide admission for heavy steps (decision 0013); inert unless FORGE_HOST_LOAD_GOVERNOR=on. */
|
|
70
|
+
hostLoadGovernor;
|
|
71
|
+
constructor(stateRoot, portBroker = new HostPortBroker(), nodeAdapter, processSupervisors = new AttemptProcessSupervisorRegistry(), processRunner = new StreamingProviderProcessRunner(), listenerInspector = new HostListenerInspector(), promotionStore = new HostParallelPromotionStore(stateRoot), playwrightAdapter = new PlaywrightHostRuntimeAdapter(), processRecovery = new ExactHostProcessRecovery(), capacityResourceSample, executionRoot, databaseBroker = null, hostLoad = null) {
|
|
68
72
|
this.stateRoot = stateRoot;
|
|
69
73
|
this.processSupervisors = processSupervisors;
|
|
70
74
|
this.processRunner = processRunner;
|
|
@@ -74,6 +78,7 @@ export class HostRuntimeLeaseManager {
|
|
|
74
78
|
this.processRecovery = processRecovery;
|
|
75
79
|
this.capacityResourceSample = capacityResourceSample;
|
|
76
80
|
this.databaseBroker = databaseBroker;
|
|
81
|
+
this.hostLoadGovernor = new HostLoadGovernor({ stateRoot, load: hostLoad ?? new HostLoadSampler() });
|
|
77
82
|
this.executionRoot = path.resolve(executionRoot ?? stateRoot);
|
|
78
83
|
if (executionRoot !== undefined)
|
|
79
84
|
assertHostExecutionRoot(this.executionRoot);
|
|
@@ -84,6 +89,8 @@ export class HostRuntimeLeaseManager {
|
|
|
84
89
|
this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
|
|
85
90
|
}
|
|
86
91
|
async reap(options) {
|
|
92
|
+
// Heavy-step tokens whose owner died or whose lease lapsed are returned first.
|
|
93
|
+
await this.hostLoadGovernor.reclaim().catch(() => undefined);
|
|
87
94
|
await this.refreshKnownPromotions();
|
|
88
95
|
const recoveredAttempts = [];
|
|
89
96
|
const report = {
|
|
@@ -1420,6 +1427,7 @@ export class HostRuntimeLeaseManager {
|
|
|
1420
1427
|
if (!preservePreparation)
|
|
1421
1428
|
this.pendingRenewals.delete(dispatchAttemptId);
|
|
1422
1429
|
if (!active) {
|
|
1430
|
+
await this.hostLoadGovernor.releaseAttempt(dispatchAttemptId).catch(() => undefined);
|
|
1423
1431
|
this.cancelAdmissionWaiters(dispatchAttemptId, fencingToken, "Managed host admission was released before acquisition.");
|
|
1424
1432
|
this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
|
|
1425
1433
|
this.releaseParallelProjects(dispatchAttemptId, fencingToken);
|
|
@@ -1429,6 +1437,8 @@ export class HostRuntimeLeaseManager {
|
|
|
1429
1437
|
if (active.lease.fencingToken !== fencingToken)
|
|
1430
1438
|
return null;
|
|
1431
1439
|
active.releasing = true;
|
|
1440
|
+
// Attempt teardown returns the attempt's heavy-step tokens and cancels its queued steps.
|
|
1441
|
+
await this.hostLoadGovernor.releaseAttempt(dispatchAttemptId).catch(() => undefined);
|
|
1432
1442
|
for (const pending of active.pendingAdapterLaunches.values()) {
|
|
1433
1443
|
pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
|
|
1434
1444
|
}
|
|
@@ -2207,7 +2217,7 @@ function runtimeExecutionClass(dispatch) {
|
|
|
2207
2217
|
? "analysis_only"
|
|
2208
2218
|
: "managed_runtime";
|
|
2209
2219
|
}
|
|
2210
|
-
function runtimeAdmissionPriority(dispatch) {
|
|
2220
|
+
export function runtimeAdmissionPriority(dispatch) {
|
|
2211
2221
|
return dispatch.execution.lane.trim().toLowerCase() === "runtime_readiness"
|
|
2212
2222
|
|| dispatch.cycleRun.phase.trim().toLowerCase() === "readiness_probe"
|
|
2213
2223
|
? "background"
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type HostLoadStepGate } from "../runtime/host-load-governor.js";
|
|
2
|
+
import { type HostLoadTokenPriority } from "../runtime/host-load-token-ledger.js";
|
|
3
|
+
import type { RunnerDispatchEvent } from "./session.types.js";
|
|
4
|
+
/** Which attempt a governed validation step belongs to, and its queue class. */
|
|
5
|
+
export interface PrePublicationHostLoadOwner {
|
|
6
|
+
readonly dispatchAttemptId: string | null;
|
|
7
|
+
readonly priority: HostLoadTokenPriority;
|
|
8
|
+
}
|
|
9
|
+
export interface GovernedValidationStep {
|
|
10
|
+
readonly checkId: string;
|
|
11
|
+
readonly command: string;
|
|
12
|
+
readonly args: readonly string[];
|
|
13
|
+
readonly owner?: PrePublicationHostLoadOwner;
|
|
14
|
+
readonly signal?: AbortSignal;
|
|
15
|
+
readonly emit?: (event: RunnerDispatchEvent) => Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Runs one pre-publication step behind the host load governor (decision 0013).
|
|
19
|
+
* With the governor off this is a direct call, so behavior is unchanged. With
|
|
20
|
+
* it on, the step waits for admission first; queue time is reported as
|
|
21
|
+
* `host_load_wait_ms` with status `waiting_for_host_capacity`, and the step's
|
|
22
|
+
* own clock (`elapsed_ms`) starts only once it is admitted. `run` gets the
|
|
23
|
+
* signal to launch with: it also aborts when the step's reservation is lost
|
|
24
|
+
* (token fenced, or not renewable for a lease), and the step then fails with
|
|
25
|
+
* that error instead of running on unaccounted.
|
|
26
|
+
*/
|
|
27
|
+
export declare function runHostGovernedValidationStep<T>(gate: HostLoadStepGate | undefined, step: GovernedValidationStep, run: (signal: AbortSignal | undefined) => Promise<T>): Promise<T>;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { monotonicNowMs } from "../shared/time/monotonic.js";
|
|
2
|
+
import { HostCapacityTimeoutError } from "../runtime/host-load-governor.js";
|
|
3
|
+
import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
|
|
4
|
+
import { classifyValidationStep } from "../runtime/host-load-step-class.js";
|
|
5
|
+
import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
|
|
6
|
+
/**
|
|
7
|
+
* Runs one pre-publication step behind the host load governor (decision 0013).
|
|
8
|
+
* With the governor off this is a direct call, so behavior is unchanged. With
|
|
9
|
+
* it on, the step waits for admission first; queue time is reported as
|
|
10
|
+
* `host_load_wait_ms` with status `waiting_for_host_capacity`, and the step's
|
|
11
|
+
* own clock (`elapsed_ms`) starts only once it is admitted. `run` gets the
|
|
12
|
+
* signal to launch with: it also aborts when the step's reservation is lost
|
|
13
|
+
* (token fenced, or not renewable for a lease), and the step then fails with
|
|
14
|
+
* that error instead of running on unaccounted.
|
|
15
|
+
*/
|
|
16
|
+
export async function runHostGovernedValidationStep(gate, step, run) {
|
|
17
|
+
if (!gate?.enabled)
|
|
18
|
+
return await run(step.signal);
|
|
19
|
+
const { stepClass, cost } = classifyValidationStep(step.checkId, step.command, step.args);
|
|
20
|
+
const base = { checkId: step.checkId, contractId: "forge-ci-parity-v1", stepClass };
|
|
21
|
+
const emit = async (eventType, content, data, kind = "checkpoint") => {
|
|
22
|
+
await step.emit?.({ role: "runner", kind, content, eventType, data: JSON.stringify({ ...base, ...data }) })
|
|
23
|
+
.catch(() => undefined);
|
|
24
|
+
};
|
|
25
|
+
let admission;
|
|
26
|
+
try {
|
|
27
|
+
admission = await gate.acquire({
|
|
28
|
+
stepClass,
|
|
29
|
+
label: step.checkId,
|
|
30
|
+
cost,
|
|
31
|
+
dispatchAttemptId: step.owner?.dispatchAttemptId ?? null,
|
|
32
|
+
priority: step.owner?.priority ?? "foreground",
|
|
33
|
+
}, {
|
|
34
|
+
signal: step.signal,
|
|
35
|
+
onWaiting: async (decision) => await emit("prepublication_host_capacity_waiting", `Pre-publication step '${step.checkId}' (${stepClass}) is waiting for host capacity: ${decision.detail}`, { status: "waiting_for_host_capacity", reason: decision.reason, cpuCores: cost.cpuCores, memoryBytes: cost.memoryBytes }),
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
if (error instanceof HostCapacityTimeoutError) {
|
|
40
|
+
await emit("prepublication_host_capacity_timeout", error.message, { status: "host_capacity_timeout", host_load_wait_ms: Math.round(error.waitMs) }, "error");
|
|
41
|
+
}
|
|
42
|
+
else if (error instanceof HostCapacityLedgerUnavailableError) {
|
|
43
|
+
await emit("prepublication_host_capacity_ledger_unavailable", error.message, { status: "host_capacity_ledger_unavailable" }, "error");
|
|
44
|
+
}
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
const waitMs = Math.round(admission.waitMs);
|
|
48
|
+
await emit("prepublication_host_capacity_admitted", `Pre-publication step '${step.checkId}' (${stepClass}) was admitted after ${waitMs}ms waiting for host capacity.`, { status: "running", reason: admission.decision.reason, host_load_wait_ms: waitMs });
|
|
49
|
+
// Step timers start here, after admission: a step can never time out because it waited.
|
|
50
|
+
const startedAtMs = monotonicNowMs();
|
|
51
|
+
const runSignal = step.signal ? AbortSignal.any([step.signal, admission.signal]) : admission.signal;
|
|
52
|
+
const reservationLost = async () => {
|
|
53
|
+
const reason = admission.signal.reason;
|
|
54
|
+
await emit("prepublication_host_capacity_lost", `Pre-publication step '${step.checkId}' (${stepClass}) was stopped because its host capacity reservation was lost: ${reason instanceof Error ? reason.message : String(reason)}`, { status: "host_capacity_lost" }, "error");
|
|
55
|
+
throw reason;
|
|
56
|
+
};
|
|
57
|
+
try {
|
|
58
|
+
let result;
|
|
59
|
+
try {
|
|
60
|
+
result = await run(runSignal);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
if (admission.signal.aborted)
|
|
64
|
+
return await reservationLost();
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
// A result produced after the reservation was lost is not trusted either.
|
|
68
|
+
if (admission.signal.aborted)
|
|
69
|
+
return await reservationLost();
|
|
70
|
+
return result;
|
|
71
|
+
}
|
|
72
|
+
finally {
|
|
73
|
+
const elapsedMs = Math.round(monotonicNowMs() - startedAtMs);
|
|
74
|
+
let failure = null;
|
|
75
|
+
try {
|
|
76
|
+
await admission.release();
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
failure = {
|
|
80
|
+
kind: error instanceof HostCapacityTokenFencedError ? "fenced" : "ledger_unavailable",
|
|
81
|
+
message: error instanceof Error ? error.message : String(error),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
await emit("prepublication_host_capacity_released", failure?.kind === "fenced"
|
|
85
|
+
? `Pre-publication step '${step.checkId}' finished, but its host capacity token had been reclaimed: ${failure.message}`
|
|
86
|
+
: failure
|
|
87
|
+
? `Pre-publication step '${step.checkId}' finished, but its host capacity token could not be returned yet (the governor keeps retrying): ${failure.message}`
|
|
88
|
+
: `Pre-publication step '${step.checkId}' (${stepClass}) ran ${elapsedMs}ms after waiting ${waitMs}ms for host capacity.`, {
|
|
89
|
+
status: "completed",
|
|
90
|
+
host_load_wait_ms: waitMs,
|
|
91
|
+
elapsed_ms: elapsedMs,
|
|
92
|
+
tokenFenced: failure?.kind === "fenced",
|
|
93
|
+
releaseFailed: failure?.kind === "ledger_unavailable",
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
}
|