@loucompanion/forge-bridge 0.1.4-dev.04a1e5b9e484 → 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 +3 -3
- package/dist/bridge/bridge.service.d.ts +12 -1
- package/dist/bridge/bridge.service.js +55 -8
- package/dist/bridge/bridge.types.d.ts +6 -0
- package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
- package/dist/bridge/dispatch-result-outbox.js +31 -6
- package/dist/cli/cli.help.js +2 -2
- package/dist/cli/cli.service.js +3 -1
- package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
- package/dist/runtime/attempt-process-supervisor.js +50 -0
- package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
- package/dist/runtime/host-database-capability-boundary.js +1 -0
- package/dist/runtime/host-facts.d.ts +35 -0
- package/dist/runtime/host-facts.js +95 -0
- 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 +121 -0
- package/dist/runtime/host-load-sampler.js +224 -0
- 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 +61 -0
- package/dist/runtime/host-pressure-stall.js +168 -0
- package/dist/runtime/host-runtime-contract.d.ts +1 -0
- package/dist/runtime/host-runtime-contract.js +2 -0
- package/dist/runtime/host-runtime-lease.d.ts +7 -1
- package/dist/runtime/host-runtime-lease.js +67 -11
- package/dist/runtime/managed-command-teardown.d.ts +62 -0
- package/dist/runtime/managed-command-teardown.js +607 -0
- package/dist/runtime/playwright-browser-cache.d.ts +39 -0
- package/dist/runtime/playwright-browser-cache.js +227 -0
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
- package/dist/session/managed-attempt-tools.d.ts +25 -0
- package/dist/session/managed-attempt-tools.js +212 -15
- package/dist/session/managed-build-coordinator.d.ts +1 -1
- package/dist/session/managed-build-coordinator.js +4 -1
- package/dist/session/phase-completion.artifacts.js +4 -0
- package/dist/session/phase-completion.runtime.js +22 -17
- 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-process.d.ts +20 -0
- package/dist/session/pre-publication-process.js +97 -0
- package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
- package/dist/session/pre-publication-skipped-tests.js +109 -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 +44 -112
- package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
- package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
- package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +37 -1
- package/dist/session/provider-cli/provider-cli.process.js +297 -23
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +15 -0
- package/dist/session/provider-cli/provider-cli.service.js +126 -26
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
- package/dist/session/provider-cli/provider-output-state.js +9 -0
- package/dist/session/provider-cli/provider-usage.d.ts +2 -1
- package/dist/session/publishable-worktree-changes.d.ts +54 -0
- package/dist/session/publishable-worktree-changes.js +193 -0
- package/dist/session/session.types.js +13 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/dependency-warmer.js +74 -0
- package/package.json +1 -1
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { parsePressureStall } from "./host-pressure-stall.js";
|
|
5
|
+
export function defaultHostEnvironment(overrides = {}) {
|
|
6
|
+
return {
|
|
7
|
+
platform: process.platform,
|
|
8
|
+
procRoot: "/proc",
|
|
9
|
+
etcRoot: "/etc",
|
|
10
|
+
cgroupRoot: "/sys/fs/cgroup",
|
|
11
|
+
readFile: filePath => fs.readFile(filePath, "utf8"),
|
|
12
|
+
cpus: () => os.cpus(),
|
|
13
|
+
totalMemoryBytes: () => os.totalmem(),
|
|
14
|
+
freeMemoryBytes: () => os.freemem(),
|
|
15
|
+
architecture: () => os.arch(),
|
|
16
|
+
kernelRelease: () => os.release(),
|
|
17
|
+
osType: () => os.type(),
|
|
18
|
+
osVersion: () => os.version(),
|
|
19
|
+
...overrides,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
export async function detectHostFacts(environment = defaultHostEnvironment()) {
|
|
23
|
+
const cpus = safe(() => environment.cpus(), []);
|
|
24
|
+
const linux = environment.platform === "linux";
|
|
25
|
+
const [cpuinfo, osRelease, psiAvailable] = linux
|
|
26
|
+
? await Promise.all([
|
|
27
|
+
readOptional(environment, path.posix.join(environment.procRoot, "cpuinfo")),
|
|
28
|
+
readOptional(environment, path.posix.join(environment.etcRoot, "os-release")),
|
|
29
|
+
probePsi(environment),
|
|
30
|
+
])
|
|
31
|
+
: [null, null, false];
|
|
32
|
+
return {
|
|
33
|
+
cpuModel: cleanText(cpus[0]?.model) ?? (cpuinfo ? cpuinfoModel(cpuinfo) : null),
|
|
34
|
+
physicalCores: cpuinfo ? physicalCoreCount(cpuinfo) : null,
|
|
35
|
+
logicalThreads: Math.max(1, cpus.length),
|
|
36
|
+
totalMemoryBytes: Math.max(0, safe(() => environment.totalMemoryBytes(), 0)),
|
|
37
|
+
architecture: safe(() => environment.architecture(), "unknown"),
|
|
38
|
+
platform: environment.platform,
|
|
39
|
+
osName: (osRelease ? prettyOsName(osRelease) : null)
|
|
40
|
+
?? cleanText(`${safe(() => environment.osType(), "")} ${safe(() => environment.osVersion(), "")}`),
|
|
41
|
+
kernelVersion: cleanText(safe(() => environment.kernelRelease(), "")),
|
|
42
|
+
psiAvailable,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/** PSI is available when the system-wide CPU pressure file exists and parses. */
|
|
46
|
+
export async function probePsi(environment) {
|
|
47
|
+
if (environment.platform !== "linux")
|
|
48
|
+
return false;
|
|
49
|
+
const content = await readOptional(environment, path.posix.join(environment.procRoot, "pressure", "cpu"));
|
|
50
|
+
return content !== null && parsePressureStall(content) !== null;
|
|
51
|
+
}
|
|
52
|
+
export async function readOptional(environment, filePath) {
|
|
53
|
+
try {
|
|
54
|
+
return await environment.readFile(filePath);
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
// Missing, unreadable, or kernel-disabled (EOPNOTSUPP) files mean "not reported".
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** Counts unique (physical id, core id) pairs; null when the topology is not exposed. */
|
|
62
|
+
export function physicalCoreCount(cpuinfo) {
|
|
63
|
+
const cores = new Set();
|
|
64
|
+
for (const block of cpuinfo.split(/\r?\n\s*\r?\n/u)) {
|
|
65
|
+
const physicalId = field(block, "physical id") ?? "0";
|
|
66
|
+
const coreId = field(block, "core id");
|
|
67
|
+
if (coreId !== null)
|
|
68
|
+
cores.add(`${physicalId}:${coreId}`);
|
|
69
|
+
}
|
|
70
|
+
return cores.size > 0 ? cores.size : null;
|
|
71
|
+
}
|
|
72
|
+
function cpuinfoModel(cpuinfo) {
|
|
73
|
+
return cleanText(field(cpuinfo, "model name") ?? field(cpuinfo, "Model") ?? undefined);
|
|
74
|
+
}
|
|
75
|
+
function prettyOsName(osRelease) {
|
|
76
|
+
const match = /^PRETTY_NAME=(.*)$/mu.exec(osRelease);
|
|
77
|
+
return match ? cleanText(match[1].trim().replace(/^["']|["']$/gu, "")) : null;
|
|
78
|
+
}
|
|
79
|
+
function field(block, name) {
|
|
80
|
+
const escaped = name.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
|
81
|
+
const match = new RegExp(`^${escaped}\\s*:\\s*(.*)$`, "mu").exec(block);
|
|
82
|
+
return match ? match[1].trim() : null;
|
|
83
|
+
}
|
|
84
|
+
function cleanText(value) {
|
|
85
|
+
const clean = value?.replace(/\s+/gu, " ").trim();
|
|
86
|
+
return clean ? clean.slice(0, 200) : null;
|
|
87
|
+
}
|
|
88
|
+
function safe(read, fallback) {
|
|
89
|
+
try {
|
|
90
|
+
return read();
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return fallback;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { HostLoadGovernorConfig } from "./host-load-governor-config.js";
|
|
2
|
+
import type { HostLoadStepCost } from "./host-load-step-class.js";
|
|
3
|
+
/** Measured host load the admission rule reads. Null means PSI is unavailable or stale. */
|
|
4
|
+
export interface HostLoadSignals {
|
|
5
|
+
/** Host-wide CPU PSI `some avg10`, used as is (never split per cgroup). */
|
|
6
|
+
readonly cpuSomeAvg10: number;
|
|
7
|
+
/** Consecutive samples, ending with the latest, at or above the CPU pressure threshold. */
|
|
8
|
+
readonly cpuPressuredSamples: number;
|
|
9
|
+
/** Host-wide memory PSI `full avg10`; a hard stop above its threshold. */
|
|
10
|
+
readonly memoryFullAvg10: number | null;
|
|
11
|
+
readonly memoryAvailableBytes: number | null;
|
|
12
|
+
/**
|
|
13
|
+
* Host CPU from /proc/stat minus the bridge's dedicated cgroup over the same
|
|
14
|
+
* window. Null when the bridge's cgroup is not dedicated: Forge's own work is
|
|
15
|
+
* then counted only through reserved cost and the host PSI gate.
|
|
16
|
+
*/
|
|
17
|
+
readonly externalCpuCores: number | null;
|
|
18
|
+
}
|
|
19
|
+
export type HostLoadAdmissionReason = "admitted" | "admitted_alone" | "admitted_fallback" | "cpu_budget" | "memory_budget" | "cpu_pressure" | "memory_pressure" | "fallback_slots"
|
|
20
|
+
/** A corrupt ledger was quarantined; admissions wait one lease while owners restore their reservations. */
|
|
21
|
+
| "ledger_recovering";
|
|
22
|
+
export interface HostLoadAdmissionInput {
|
|
23
|
+
readonly request: HostLoadStepCost;
|
|
24
|
+
/** Reserved cost of every live token on this host (all processes). */
|
|
25
|
+
readonly running: readonly HostLoadStepCost[];
|
|
26
|
+
/**
|
|
27
|
+
* Memory the running steps already use. MemAvailable already excludes it, so
|
|
28
|
+
* it is added back to the budget (capped at their reservations) instead of
|
|
29
|
+
* being counted twice.
|
|
30
|
+
*/
|
|
31
|
+
readonly runningMemoryBytes?: number;
|
|
32
|
+
readonly logicalCpus: number;
|
|
33
|
+
readonly signals: HostLoadSignals | null;
|
|
34
|
+
readonly config: Pick<HostLoadGovernorConfig, "cpuBudgetFraction" | "memoryReserveBytes" | "cpuPressureThreshold" | "backpressureSamples" | "memoryFullThreshold" | "fallbackSlots">;
|
|
35
|
+
}
|
|
36
|
+
export interface HostLoadAdmissionDecision {
|
|
37
|
+
readonly admitted: boolean;
|
|
38
|
+
readonly reason: HostLoadAdmissionReason;
|
|
39
|
+
readonly cpuBudgetCores: number | null;
|
|
40
|
+
readonly memoryBudgetBytes: number | null;
|
|
41
|
+
readonly reservedCpuCores: number;
|
|
42
|
+
readonly reservedMemoryBytes: number;
|
|
43
|
+
readonly detail: string;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Decision 0013 admission rule. A step is admitted when the reserved cost of
|
|
47
|
+
* running steps plus its own cost fits the budget and host pressure is under
|
|
48
|
+
* the backpressure threshold. Memory `full` pressure is a hard stop. A step
|
|
49
|
+
* too large for the budget on its own runs only when nothing else does.
|
|
50
|
+
* Without PSI, a simple per-host semaphore applies instead.
|
|
51
|
+
*/
|
|
52
|
+
export declare function decideHostLoadAdmission(input: HostLoadAdmissionInput): HostLoadAdmissionDecision;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
const epsilon = 1e-9;
|
|
2
|
+
/**
|
|
3
|
+
* Decision 0013 admission rule. A step is admitted when the reserved cost of
|
|
4
|
+
* running steps plus its own cost fits the budget and host pressure is under
|
|
5
|
+
* the backpressure threshold. Memory `full` pressure is a hard stop. A step
|
|
6
|
+
* too large for the budget on its own runs only when nothing else does.
|
|
7
|
+
* Without PSI, a simple per-host semaphore applies instead.
|
|
8
|
+
*/
|
|
9
|
+
export function decideHostLoadAdmission(input) {
|
|
10
|
+
const { request, running, signals, config } = input;
|
|
11
|
+
const reservedCpuCores = running.reduce((sum, cost) => sum + cost.cpuCores, 0);
|
|
12
|
+
const reservedMemoryBytes = running.reduce((sum, cost) => sum + cost.memoryBytes, 0);
|
|
13
|
+
const base = { reservedCpuCores, reservedMemoryBytes };
|
|
14
|
+
if (!signals) {
|
|
15
|
+
const admitted = running.length < config.fallbackSlots;
|
|
16
|
+
return {
|
|
17
|
+
...base,
|
|
18
|
+
admitted,
|
|
19
|
+
reason: admitted ? "admitted_fallback" : "fallback_slots",
|
|
20
|
+
cpuBudgetCores: null,
|
|
21
|
+
memoryBudgetBytes: null,
|
|
22
|
+
detail: admitted
|
|
23
|
+
? "Host pressure data is unavailable; admitted under the per-host step semaphore."
|
|
24
|
+
: `Host pressure data is unavailable; ${running.length} of ${config.fallbackSlots} heavy step slot(s) are in use.`,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
const cpuBudgetCores = Math.max(0, input.logicalCpus * config.cpuBudgetFraction - (signals.externalCpuCores ?? 0));
|
|
28
|
+
const usedByRunning = Math.min(reservedMemoryBytes, Math.max(0, input.runningMemoryBytes ?? 0));
|
|
29
|
+
const memoryBudgetBytes = signals.memoryAvailableBytes === null
|
|
30
|
+
? null
|
|
31
|
+
: Math.max(0, signals.memoryAvailableBytes + usedByRunning - config.memoryReserveBytes);
|
|
32
|
+
const budget = { ...base, cpuBudgetCores, memoryBudgetBytes };
|
|
33
|
+
if (signals.memoryFullAvg10 !== null && signals.memoryFullAvg10 > config.memoryFullThreshold) {
|
|
34
|
+
return {
|
|
35
|
+
...budget,
|
|
36
|
+
admitted: false,
|
|
37
|
+
reason: "memory_pressure",
|
|
38
|
+
detail: `Host memory pressure (full avg10 ${signals.memoryFullAvg10}%) is above ${config.memoryFullThreshold}%; no heavy step may start.`,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
if (signals.cpuPressuredSamples >= config.backpressureSamples) {
|
|
42
|
+
return {
|
|
43
|
+
...budget,
|
|
44
|
+
admitted: false,
|
|
45
|
+
reason: "cpu_pressure",
|
|
46
|
+
detail: `Host CPU pressure (some avg10 ${signals.cpuSomeAvg10}%) has been at or above ${config.cpuPressureThreshold}% for ${signals.cpuPressuredSamples} sample(s).`,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
if (running.length === 0) {
|
|
50
|
+
const oversize = request.cpuCores > cpuBudgetCores + epsilon
|
|
51
|
+
|| (memoryBudgetBytes !== null && request.memoryBytes > memoryBudgetBytes + epsilon);
|
|
52
|
+
return {
|
|
53
|
+
...budget,
|
|
54
|
+
admitted: true,
|
|
55
|
+
reason: oversize ? "admitted_alone" : "admitted",
|
|
56
|
+
detail: oversize
|
|
57
|
+
? "The step exceeds the host budget on its own and runs alone because nothing else is running."
|
|
58
|
+
: "The step fits the host budget.",
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
if (reservedCpuCores + request.cpuCores > cpuBudgetCores + epsilon) {
|
|
62
|
+
return {
|
|
63
|
+
...budget,
|
|
64
|
+
admitted: false,
|
|
65
|
+
reason: "cpu_budget",
|
|
66
|
+
detail: `Reserved ${round(reservedCpuCores)} + requested ${round(request.cpuCores)} cores exceed the ${round(cpuBudgetCores)}-core budget${signals.externalCpuCores ? ` (${round(signals.externalCpuCores)} cores of external load)` : ""}.`,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
if (memoryBudgetBytes !== null && reservedMemoryBytes + request.memoryBytes > memoryBudgetBytes + epsilon) {
|
|
70
|
+
return {
|
|
71
|
+
...budget,
|
|
72
|
+
admitted: false,
|
|
73
|
+
reason: "memory_budget",
|
|
74
|
+
detail: `Reserved ${gib(reservedMemoryBytes)} + requested ${gib(request.memoryBytes)} GiB exceed the ${gib(memoryBudgetBytes)} GiB memory budget.`,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
return { ...budget, admitted: true, reason: "admitted", detail: "The step fits the host budget." };
|
|
78
|
+
}
|
|
79
|
+
function round(value) {
|
|
80
|
+
return Math.round(value * 100) / 100;
|
|
81
|
+
}
|
|
82
|
+
function gib(bytes) {
|
|
83
|
+
return round(bytes / 1024 ** 3);
|
|
84
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type HostEnvironment } from "./host-facts.js";
|
|
2
|
+
/**
|
|
3
|
+
* Free memory under the tightest `memory.max` from the cgroup up to and
|
|
4
|
+
* including the root (`memory.max − memory.current`), or null when no limit is
|
|
5
|
+
* set on the path. Inside a container the root is the container's own cgroup,
|
|
6
|
+
* whose `memory.max` is the container limit.
|
|
7
|
+
*/
|
|
8
|
+
export declare function readCgroupMemoryHeadroomBytes(environment: HostEnvironment, cgroupPath: string): Promise<number | null>;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { readOptional } from "./host-facts.js";
|
|
3
|
+
import { parseNonNegativeInteger } from "./host-pressure-stall.js";
|
|
4
|
+
// Decision 0013 cgroup accounting: the memory budget follows the tightest
|
|
5
|
+
// `memory.max` on the bridge's cgroup path, so a step is never admitted past
|
|
6
|
+
// the limit that would OOM-kill it.
|
|
7
|
+
/**
|
|
8
|
+
* Free memory under the tightest `memory.max` from the cgroup up to and
|
|
9
|
+
* including the root (`memory.max − memory.current`), or null when no limit is
|
|
10
|
+
* set on the path. Inside a container the root is the container's own cgroup,
|
|
11
|
+
* whose `memory.max` is the container limit.
|
|
12
|
+
*/
|
|
13
|
+
export async function readCgroupMemoryHeadroomBytes(environment, cgroupPath) {
|
|
14
|
+
let tightest = null;
|
|
15
|
+
for (const current of cgroupPathAndAncestors(cgroupPath)) {
|
|
16
|
+
const directory = cgroupDirectory(environment, current);
|
|
17
|
+
if (!directory)
|
|
18
|
+
return null;
|
|
19
|
+
const [maximum, used] = await Promise.all([
|
|
20
|
+
readOptional(environment, path.posix.join(directory, "memory.max")),
|
|
21
|
+
readOptional(environment, path.posix.join(directory, "memory.current")),
|
|
22
|
+
]);
|
|
23
|
+
const limit = maximum ? parseNonNegativeInteger(maximum) : null;
|
|
24
|
+
const usage = used ? parseNonNegativeInteger(used) : null;
|
|
25
|
+
if (limit === null || usage === null)
|
|
26
|
+
continue;
|
|
27
|
+
const headroom = Math.max(0, limit - usage);
|
|
28
|
+
tightest = tightest === null ? headroom : Math.min(tightest, headroom);
|
|
29
|
+
}
|
|
30
|
+
return tightest;
|
|
31
|
+
}
|
|
32
|
+
/** `/a/b/c`, `/a/b`, `/a`, `/`; nothing for a relative or traversing path. */
|
|
33
|
+
function cgroupPathAndAncestors(cgroupPath) {
|
|
34
|
+
if (!cgroupPath.startsWith("/") || cgroupPath.split("/").includes(".."))
|
|
35
|
+
return [];
|
|
36
|
+
const paths = [];
|
|
37
|
+
for (let current = path.posix.normalize(cgroupPath);; current = path.posix.dirname(current)) {
|
|
38
|
+
paths.push(current);
|
|
39
|
+
if (current === "/")
|
|
40
|
+
return paths;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function cgroupDirectory(environment, cgroupPath) {
|
|
44
|
+
if (!cgroupPath.startsWith("/") || cgroupPath.split("/").includes(".."))
|
|
45
|
+
return null;
|
|
46
|
+
const root = environment.cgroupRoot.replace(/\/+$/u, "");
|
|
47
|
+
if (cgroupPath === "/")
|
|
48
|
+
return root;
|
|
49
|
+
const directory = path.posix.join(root, cgroupPath);
|
|
50
|
+
return directory.startsWith(`${root}/`) ? directory : null;
|
|
51
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export type HostLoadGovernorMode = "on" | "off";
|
|
2
|
+
export interface HostLoadGovernorConfig {
|
|
3
|
+
/** FORGE_HOST_LOAD_GOVERNOR. Off by default in this step; `off` is the operator override. */
|
|
4
|
+
readonly mode: HostLoadGovernorMode;
|
|
5
|
+
/** Share of logical CPUs Forge may reserve for heavy steps. */
|
|
6
|
+
readonly cpuBudgetFraction: number;
|
|
7
|
+
/** Memory kept free for the rest of the host, taken off MemAvailable. */
|
|
8
|
+
readonly memoryReserveBytes: number;
|
|
9
|
+
/** Host CPU PSI `some avg10` (percent) at or above which a sample counts as pressured. */
|
|
10
|
+
readonly cpuPressureThreshold: number;
|
|
11
|
+
/** Consecutive pressured samples that stop new admissions (backpressure). */
|
|
12
|
+
readonly backpressureSamples: number;
|
|
13
|
+
/** Host memory PSI `full avg10` (percent) above which admission is a hard stop. */
|
|
14
|
+
readonly memoryFullThreshold: number;
|
|
15
|
+
/** Maximum queue wait before a retryable host_capacity_timeout. */
|
|
16
|
+
readonly maxWaitMs: number;
|
|
17
|
+
/** Steps allowed at once when PSI is unavailable (the per-host semaphore fallback). */
|
|
18
|
+
readonly fallbackSlots: number;
|
|
19
|
+
/** After this long at the head of the queue, later waiters may no longer overtake it. */
|
|
20
|
+
readonly antiStarvationMs: number;
|
|
21
|
+
/** Token lease; the owner renews well before it expires. */
|
|
22
|
+
readonly leaseMs: number;
|
|
23
|
+
/** How often waiters are re-evaluated against fresh samples and the shared ledger. */
|
|
24
|
+
readonly recheckIntervalMs: number;
|
|
25
|
+
/** A load sample older than this is treated as missing PSI. */
|
|
26
|
+
readonly sampleStaleMs: number;
|
|
27
|
+
/** The sampler's interval; a longer gap between samples resets the pressure streak. */
|
|
28
|
+
readonly sampleIntervalMs: number;
|
|
29
|
+
/** Without a dedicated cgroup, a step this old is assumed to use its reserved memory. */
|
|
30
|
+
readonly memoryRampMs: number;
|
|
31
|
+
}
|
|
32
|
+
export declare const defaultHostLoadGovernorConfig: HostLoadGovernorConfig;
|
|
33
|
+
export declare function parseHostLoadGovernorMode(value: string | undefined): HostLoadGovernorMode;
|
|
34
|
+
export declare function loadHostLoadGovernorConfig(environment?: Readonly<Record<string, string | undefined>>): HostLoadGovernorConfig;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { defaultHostLoadSampleIntervalMs } from "./host-load-sampler.js";
|
|
2
|
+
export const defaultHostLoadGovernorConfig = {
|
|
3
|
+
mode: "off",
|
|
4
|
+
cpuBudgetFraction: 0.8,
|
|
5
|
+
memoryReserveBytes: 1024 ** 3,
|
|
6
|
+
cpuPressureThreshold: 50,
|
|
7
|
+
backpressureSamples: 2,
|
|
8
|
+
memoryFullThreshold: 5,
|
|
9
|
+
maxWaitMs: 30 * 60_000,
|
|
10
|
+
fallbackSlots: 1,
|
|
11
|
+
antiStarvationMs: 2 * 60_000,
|
|
12
|
+
leaseMs: 2 * 60_000,
|
|
13
|
+
recheckIntervalMs: 1_000,
|
|
14
|
+
sampleStaleMs: 30_000,
|
|
15
|
+
sampleIntervalMs: defaultHostLoadSampleIntervalMs,
|
|
16
|
+
memoryRampMs: 60_000,
|
|
17
|
+
};
|
|
18
|
+
export function parseHostLoadGovernorMode(value) {
|
|
19
|
+
const normalized = value?.trim().toLowerCase() ?? "";
|
|
20
|
+
return normalized === "on" || normalized === "true" || normalized === "1" ? "on" : "off";
|
|
21
|
+
}
|
|
22
|
+
export function loadHostLoadGovernorConfig(environment = process.env) {
|
|
23
|
+
const defaults = defaultHostLoadGovernorConfig;
|
|
24
|
+
return {
|
|
25
|
+
mode: parseHostLoadGovernorMode(environment.FORGE_HOST_LOAD_GOVERNOR),
|
|
26
|
+
cpuBudgetFraction: bounded(environment.FORGE_HOST_LOAD_CPU_BUDGET_FRACTION, defaults.cpuBudgetFraction, 0.05, 1),
|
|
27
|
+
memoryReserveBytes: bounded(environment.FORGE_HOST_LOAD_MEMORY_RESERVE_BYTES, defaults.memoryReserveBytes, 0, 1024 ** 4),
|
|
28
|
+
cpuPressureThreshold: bounded(environment.FORGE_HOST_LOAD_CPU_PRESSURE_THRESHOLD, defaults.cpuPressureThreshold, 1, 100),
|
|
29
|
+
backpressureSamples: Math.round(bounded(environment.FORGE_HOST_LOAD_BACKPRESSURE_SAMPLES, defaults.backpressureSamples, 1, 60)),
|
|
30
|
+
memoryFullThreshold: bounded(environment.FORGE_HOST_LOAD_MEMORY_FULL_THRESHOLD, defaults.memoryFullThreshold, 0, 100),
|
|
31
|
+
maxWaitMs: bounded(environment.FORGE_HOST_LOAD_MAX_WAIT_MS, defaults.maxWaitMs, 1_000, 24 * 60 * 60_000),
|
|
32
|
+
fallbackSlots: Math.round(bounded(environment.FORGE_HOST_LOAD_FALLBACK_SLOTS, defaults.fallbackSlots, 1, 64)),
|
|
33
|
+
antiStarvationMs: defaults.antiStarvationMs,
|
|
34
|
+
leaseMs: defaults.leaseMs,
|
|
35
|
+
recheckIntervalMs: defaults.recheckIntervalMs,
|
|
36
|
+
sampleStaleMs: defaults.sampleStaleMs,
|
|
37
|
+
sampleIntervalMs: defaults.sampleIntervalMs,
|
|
38
|
+
memoryRampMs: defaults.memoryRampMs,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function bounded(raw, fallback, minimum, maximum) {
|
|
42
|
+
if (raw === undefined || raw.trim() === "")
|
|
43
|
+
return fallback;
|
|
44
|
+
const value = Number(raw);
|
|
45
|
+
return Number.isFinite(value) ? Math.min(maximum, Math.max(minimum, value)) : fallback;
|
|
46
|
+
}
|
|
@@ -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
|
+
}
|