@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.
- package/README.md +2 -2
- package/dist/bridge/bridge.service.d.ts +14 -1
- package/dist/bridge/bridge.service.js +73 -8
- package/dist/bridge/bridge.types.d.ts +11 -0
- package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
- package/dist/bridge/dispatch-result-outbox.js +31 -6
- package/dist/bridge/runner-host-capabilities.d.ts +2 -0
- package/dist/bridge/runner-host-capabilities.js +4 -0
- package/dist/bridge/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- 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 +4 -0
- package/dist/runtime/host-runtime-contract.js +6 -1
- package/dist/runtime/host-runtime-lease.d.ts +13 -2
- package/dist/runtime/host-runtime-lease.js +82 -11
- package/dist/runtime/host-runtime-promotion.js +12 -0
- package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
- package/dist/runtime/host-runtime-requirements-check.js +29 -0
- package/dist/runtime/host-runtime-requirements.d.ts +36 -0
- package/dist/runtime/host-runtime-requirements.js +117 -0
- 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 +35 -1
- package/dist/session/provider-cli/provider-cli.process.js +187 -17
- 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/publishable-worktree-changes.d.ts +54 -0
- package/dist/session/publishable-worktree-changes.js +193 -0
- package/dist/session/session.base.d.ts +3 -0
- package/dist/session/session.service.d.ts +2 -0
- package/dist/session/session.service.js +5 -0
- package/dist/session/session.types.d.ts +3 -0
- package/dist/session/session.types.js +14 -2
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import { ForgeFailureError } from "../session/session.types.js";
|
|
4
|
+
export class HostCapacityLedgerUnavailableError extends ForgeFailureError {
|
|
5
|
+
code = "host_capacity_ledger_unavailable";
|
|
6
|
+
constructor(detail, options) {
|
|
7
|
+
super("host_capacity_ledger_unavailable", `host_capacity_ledger_unavailable: ${detail}`, "bridge", options);
|
|
8
|
+
this.name = "HostCapacityLedgerUnavailableError";
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Cross-process exclusive lock file for the host load ledger.
|
|
13
|
+
*
|
|
14
|
+
* Every lock file, and every break lock, is claimed with a complete
|
|
15
|
+
* `{ token, holder }` record: written to a private temporary file and
|
|
16
|
+
* hard-linked into place, which fails if the path exists. No path is ever
|
|
17
|
+
* renamed or replaced, so nothing anyone holds can be moved out from under them.
|
|
18
|
+
*
|
|
19
|
+
* A lock is broken only when its holder is provably dead (or it has no readable
|
|
20
|
+
* holder and is old). Breakers of one stale lock serialize on a chain of break
|
|
21
|
+
* locks named after that lock's identity: `<lock>.break-<identity>.1`, `.2`, …
|
|
22
|
+
* A breaker claims the first link it can; it moves on to the next only when the
|
|
23
|
+
* holder of the current one is dead, and never removes it. Under its link it
|
|
24
|
+
* re-judges the lock and unlinks it only if the path still holds that same stale
|
|
25
|
+
* lock. Identities never repeat, so the stale lock cannot reappear, and while
|
|
26
|
+
* it exists nobody can create a new lock; so at most one live breaker can ever
|
|
27
|
+
* act on it, and the unlink can never touch a lock someone acquired meanwhile.
|
|
28
|
+
*/
|
|
29
|
+
export class HostLoadLedgerLock {
|
|
30
|
+
options;
|
|
31
|
+
constructor(options) {
|
|
32
|
+
this.options = options;
|
|
33
|
+
}
|
|
34
|
+
async acquire() {
|
|
35
|
+
const token = randomUUID();
|
|
36
|
+
const started = Date.now();
|
|
37
|
+
for (;;) {
|
|
38
|
+
try {
|
|
39
|
+
await this.claim(this.options.lockPath, token);
|
|
40
|
+
return token;
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (error.code !== "EEXIST")
|
|
44
|
+
throw error;
|
|
45
|
+
if (await this.breakIfStale())
|
|
46
|
+
continue;
|
|
47
|
+
if (Date.now() - started >= this.options.timeoutMs) {
|
|
48
|
+
throw new HostCapacityLedgerUnavailableError("the host load ledger lock could not be acquired.", { cause: error });
|
|
49
|
+
}
|
|
50
|
+
await new Promise(resolve => setTimeout(resolve, 10));
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Creates `target` holding a complete `{ token, holder }` record, or fails with
|
|
56
|
+
* EEXIST. `link` never replaces an existing path, and the record is fully
|
|
57
|
+
* written before the path appears.
|
|
58
|
+
*/
|
|
59
|
+
async claim(target, token) {
|
|
60
|
+
const temporary = `${target}.${randomUUID()}.claim`;
|
|
61
|
+
try {
|
|
62
|
+
const handle = await fs.open(temporary, "wx", 0o600);
|
|
63
|
+
try {
|
|
64
|
+
await handle.writeFile(JSON.stringify({ token, holder: this.options.holder() }));
|
|
65
|
+
}
|
|
66
|
+
finally {
|
|
67
|
+
await handle.close();
|
|
68
|
+
}
|
|
69
|
+
await fs.link(temporary, target);
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
await fs.rm(temporary, { force: true }).catch(() => undefined);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** True while `token` still owns the lock file. */
|
|
76
|
+
async holds(token) {
|
|
77
|
+
return (await readLock(this.options.lockPath))?.token === token;
|
|
78
|
+
}
|
|
79
|
+
async release(token) {
|
|
80
|
+
// Only a breaker removes a lock it did not take, and only a stale one: a live
|
|
81
|
+
// holder's file cannot change between this check and the removal.
|
|
82
|
+
if (await this.holds(token))
|
|
83
|
+
await fs.rm(this.options.lockPath, { force: true });
|
|
84
|
+
}
|
|
85
|
+
async breakIfStale() {
|
|
86
|
+
const observed = await this.judgeStale(this.options.lockPath);
|
|
87
|
+
if (observed === "absent")
|
|
88
|
+
return true;
|
|
89
|
+
if (!observed)
|
|
90
|
+
return false;
|
|
91
|
+
await this.options.beforeStaleBreak?.();
|
|
92
|
+
const breaker = await this.acquireBreaker(observed.identity);
|
|
93
|
+
if (!breaker)
|
|
94
|
+
return false;
|
|
95
|
+
let broken = false;
|
|
96
|
+
try {
|
|
97
|
+
// Re-judged under the break lock: the path must still hold the same stale lock.
|
|
98
|
+
const current = await this.judgeStale(this.options.lockPath);
|
|
99
|
+
if (current === "absent")
|
|
100
|
+
return true;
|
|
101
|
+
if (!current || current.identity !== observed.identity)
|
|
102
|
+
return false;
|
|
103
|
+
await fs.unlink(this.options.lockPath).catch(error => {
|
|
104
|
+
if (error.code !== "ENOENT")
|
|
105
|
+
throw error;
|
|
106
|
+
});
|
|
107
|
+
broken = true;
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
finally {
|
|
111
|
+
// Once the stale lock is gone its chain is never needed again: dead breakers'
|
|
112
|
+
// links are cleared too. Otherwise only this breaker's own link is returned.
|
|
113
|
+
const links = broken ? breaker.chain : [breaker.path];
|
|
114
|
+
await Promise.all(links.map(link => this.releaseOwn(link, broken ? null : breaker.token)));
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* The lock at `lockPath` if it is stale (with an identity that never repeats:
|
|
119
|
+
* its token, or for an unreadable file its inode and timestamps), "absent" if
|
|
120
|
+
* there is none, or null if it is live or too young to judge.
|
|
121
|
+
*/
|
|
122
|
+
async judgeStale(lockPath) {
|
|
123
|
+
const stat = await fs.lstat(lockPath).catch(() => null);
|
|
124
|
+
if (!stat)
|
|
125
|
+
return "absent";
|
|
126
|
+
const observed = stat.isFile() && stat.size <= 16 * 1024 ? await readLock(lockPath) : null;
|
|
127
|
+
if (observed?.holder && validHolder(observed.holder) && typeof observed.token === "string") {
|
|
128
|
+
// A live holder keeps its lock however old it is.
|
|
129
|
+
if (this.options.isLive(observed.holder))
|
|
130
|
+
return null;
|
|
131
|
+
return { identity: `t-${observed.token}` };
|
|
132
|
+
}
|
|
133
|
+
// Unreadable (claims are atomic, so this is corruption): give it until the stale age.
|
|
134
|
+
if (Date.now() - stat.mtimeMs < (this.options.unreadableStaleAfterMs ?? 30_000))
|
|
135
|
+
return null;
|
|
136
|
+
return { identity: `i-${stat.dev}-${stat.ino}-${Math.trunc(stat.mtimeMs)}-${stat.size}` };
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Claims the next free link of the stale lock's break chain, held only for the
|
|
140
|
+
* few milliseconds the lock is re-judged and unlinked. A link whose holder is
|
|
141
|
+
* live means another breaker is on it; a dead holder's link is skipped, never
|
|
142
|
+
* removed or replaced.
|
|
143
|
+
*/
|
|
144
|
+
async acquireBreaker(identity) {
|
|
145
|
+
const base = `${this.options.lockPath}.break-${identity.replace(/[^A-Za-z0-9-]/gu, "_")}`;
|
|
146
|
+
const token = randomUUID();
|
|
147
|
+
const chain = [];
|
|
148
|
+
for (let generation = 1; generation <= maximumBreakGenerations; generation += 1) {
|
|
149
|
+
const link = `${base}.${generation}`;
|
|
150
|
+
chain.push(link);
|
|
151
|
+
try {
|
|
152
|
+
await this.claim(link, token);
|
|
153
|
+
return { path: link, token, chain };
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
if (error.code !== "EEXIST")
|
|
157
|
+
throw error;
|
|
158
|
+
}
|
|
159
|
+
const holder = await this.judgeStale(link);
|
|
160
|
+
// Live (or just written): another breaker is on it. Gone: retry from the start later.
|
|
161
|
+
if (holder === null || holder === "absent")
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
/** Removes `link` if `token` holds it, or unconditionally (null) once the stale lock it guarded is gone. */
|
|
167
|
+
async releaseOwn(link, token) {
|
|
168
|
+
if (token === null || (await readLock(link))?.token === token)
|
|
169
|
+
await fs.rm(link, { force: true }).catch(() => undefined);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/** A chain longer than this means breakers keep dying; the acquire times out instead. */
|
|
173
|
+
const maximumBreakGenerations = 16;
|
|
174
|
+
async function readLock(lockPath) {
|
|
175
|
+
return await fs.readFile(lockPath, "utf8")
|
|
176
|
+
.then(value => JSON.parse(value))
|
|
177
|
+
.catch(() => null);
|
|
178
|
+
}
|
|
179
|
+
function validHolder(value) {
|
|
180
|
+
const holder = value;
|
|
181
|
+
return Boolean(holder)
|
|
182
|
+
&& Number.isSafeInteger(holder.pid) && holder.pid > 0
|
|
183
|
+
&& typeof holder.processInstanceId === "string"
|
|
184
|
+
&& (holder.processIdentity === null || typeof holder.processIdentity === "string");
|
|
185
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { type HostEnvironment, type HostFacts } from "./host-facts.js";
|
|
2
|
+
import { type PressureStallResource } from "./host-pressure-stall.js";
|
|
3
|
+
export interface HostSystemPressure {
|
|
4
|
+
readonly cpu: PressureStallResource | null;
|
|
5
|
+
readonly memory: PressureStallResource | null;
|
|
6
|
+
readonly io: PressureStallResource | null;
|
|
7
|
+
}
|
|
8
|
+
/** Load attributed to the systemd unit (cgroup v2) the bridge itself runs in. */
|
|
9
|
+
export interface HostOwnCgroupLoad {
|
|
10
|
+
readonly unit: string;
|
|
11
|
+
readonly cpuPressure: PressureStallResource | null;
|
|
12
|
+
readonly memoryPressure: PressureStallResource | null;
|
|
13
|
+
/** CPU cores consumed by the unit, from `cpu.stat` usage deltas between samples. */
|
|
14
|
+
readonly cpuCoresInUse: number | null;
|
|
15
|
+
/** Anonymous memory (`memory.stat` anon): the RSS-like figure, excluding page cache. */
|
|
16
|
+
readonly memoryAnonBytes: number | null;
|
|
17
|
+
/** All memory charged to the unit (`memory.current`), including page cache. */
|
|
18
|
+
readonly memoryChargedBytes: number | null;
|
|
19
|
+
}
|
|
20
|
+
/** Live host load. Reported in every heartbeat but never a material capability signal. */
|
|
21
|
+
export interface HostLoadSnapshot {
|
|
22
|
+
readonly sampledAt: string;
|
|
23
|
+
readonly psiAvailable: boolean;
|
|
24
|
+
readonly systemPressure: HostSystemPressure | null;
|
|
25
|
+
/** True only when the bridge runs in a cgroup of its own (see isDedicatedBridgeUnit). */
|
|
26
|
+
readonly ownCgroupDedicated: boolean;
|
|
27
|
+
/** Reported only for a dedicated unit; never a shared terminal/session/app scope. */
|
|
28
|
+
readonly ownCgroup: HostOwnCgroupLoad | null;
|
|
29
|
+
readonly memoryAvailableBytes: number | null;
|
|
30
|
+
}
|
|
31
|
+
/** What the bridge service needs: static facts plus the latest cached load sample. */
|
|
32
|
+
export interface HostLoadSource {
|
|
33
|
+
start(): Promise<void>;
|
|
34
|
+
stop(): void;
|
|
35
|
+
facts(): HostFacts | null;
|
|
36
|
+
current(): HostLoadSnapshot | null;
|
|
37
|
+
/**
|
|
38
|
+
* Recent samples, oldest first, ending with `current()`. The governor reads its
|
|
39
|
+
* pressure streak from them, so samples taken while no step waited still count.
|
|
40
|
+
*/
|
|
41
|
+
recent(): readonly HostLoadSnapshot[];
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Host CPU time split into the bridge's own share and everything else, over one
|
|
45
|
+
* sampling window (decision 0013). Kept in the bridge for the host load governor;
|
|
46
|
+
* it is not part of the heartbeat payload.
|
|
47
|
+
*/
|
|
48
|
+
export interface HostCpuAttribution {
|
|
49
|
+
readonly sampledAt: string;
|
|
50
|
+
/** Busy cores on the whole host, from /proc/stat deltas. */
|
|
51
|
+
readonly hostCoresInUse: number;
|
|
52
|
+
/** Cores used by the bridge's dedicated cgroup; null when the cgroup is not dedicated. */
|
|
53
|
+
readonly ownCoresInUse: number | null;
|
|
54
|
+
/** hostCoresInUse minus ownCoresInUse; null unless the own share is known. */
|
|
55
|
+
readonly externalCoresInUse: number | null;
|
|
56
|
+
}
|
|
57
|
+
/** The governor's view: the load sample plus the CPU attribution from the same window. */
|
|
58
|
+
export interface HostLoadGovernorSource extends Pick<HostLoadSource, "start" | "facts" | "current" | "recent"> {
|
|
59
|
+
cpuAttribution?(): HostCpuAttribution | null;
|
|
60
|
+
/**
|
|
61
|
+
* Free memory under the tightest cgroup `memory.max` on the bridge's path
|
|
62
|
+
* (null when none is set), from the latest sample. The governor budgets
|
|
63
|
+
* against the smaller of this and MemAvailable (decision 0013).
|
|
64
|
+
*/
|
|
65
|
+
cgroupMemoryHeadroomBytes?(): number | null;
|
|
66
|
+
}
|
|
67
|
+
export interface HostLoadSamplerOptions {
|
|
68
|
+
readonly environment?: HostEnvironment;
|
|
69
|
+
readonly intervalMs?: number;
|
|
70
|
+
/** Wall clock for `sampledAt`. */
|
|
71
|
+
readonly now?: () => number;
|
|
72
|
+
/** Monotonic clock (ms) for usage deltas, so wall-clock steps cannot skew cores in use. */
|
|
73
|
+
readonly monotonicNow?: () => number;
|
|
74
|
+
/** Systemd unit the operator dedicates to the bridge (FORGE_BRIDGE_CGROUP_UNIT). */
|
|
75
|
+
readonly cgroupUnit?: string | null;
|
|
76
|
+
}
|
|
77
|
+
export declare const defaultHostLoadSampleIntervalMs = 5000;
|
|
78
|
+
/**
|
|
79
|
+
* Samples Linux PSI and the bridge's own cgroup on an interval and caches the
|
|
80
|
+
* latest snapshot. Every read is async and failure-tolerant: a host without PSI
|
|
81
|
+
* (non-Linux, old kernel, `psi=0`) reports `psiAvailable: false` and no pressure.
|
|
82
|
+
*/
|
|
83
|
+
export declare class HostLoadSampler implements HostLoadSource {
|
|
84
|
+
private readonly environment;
|
|
85
|
+
private readonly intervalMs;
|
|
86
|
+
private readonly now;
|
|
87
|
+
private readonly monotonicNow;
|
|
88
|
+
private readonly cgroupUnit;
|
|
89
|
+
private generation;
|
|
90
|
+
private timer;
|
|
91
|
+
private starting;
|
|
92
|
+
private inFlight;
|
|
93
|
+
private hostFacts;
|
|
94
|
+
private latest;
|
|
95
|
+
private readonly history;
|
|
96
|
+
private cpuMark;
|
|
97
|
+
private hostCpuMark;
|
|
98
|
+
private latestCpuAttribution;
|
|
99
|
+
private latestMemoryHeadroom;
|
|
100
|
+
constructor(options?: HostLoadSamplerOptions);
|
|
101
|
+
facts(): HostFacts | null;
|
|
102
|
+
current(): HostLoadSnapshot | null;
|
|
103
|
+
cpuAttribution(): HostCpuAttribution | null;
|
|
104
|
+
cgroupMemoryHeadroomBytes(): number | null;
|
|
105
|
+
recent(): readonly HostLoadSnapshot[];
|
|
106
|
+
/** Detects static facts once, takes a first sample, then samples on the interval. Idempotent. */
|
|
107
|
+
start(): Promise<void>;
|
|
108
|
+
stop(): void;
|
|
109
|
+
/** Takes one sample now and caches it. Concurrent callers share one read. */
|
|
110
|
+
sample(): Promise<HostLoadSnapshot>;
|
|
111
|
+
private startOnce;
|
|
112
|
+
private readSnapshot;
|
|
113
|
+
private readCgroupMemoryHeadroom;
|
|
114
|
+
private readSystemPressure;
|
|
115
|
+
private readOwnCgroup;
|
|
116
|
+
private coresInUse;
|
|
117
|
+
private readHostCoresInUse;
|
|
118
|
+
private readMemoryAvailable;
|
|
119
|
+
private fallbackFreeMemory;
|
|
120
|
+
private readPressure;
|
|
121
|
+
}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { defaultHostEnvironment, detectHostFacts, readOptional, } from "./host-facts.js";
|
|
3
|
+
import { cgroupLeafName, isDedicatedBridgeUnit, parseCgroupCpuUsageUsec, parseCgroupMemoryAnonBytes, parseMemAvailableBytes, parseNonNegativeInteger, parsePressureStall, parseProcStatCpuTotals, parseUnifiedCgroupMembership, parseUnifiedCgroupPath, } from "./host-pressure-stall.js";
|
|
4
|
+
import { readCgroupMemoryHeadroomBytes } from "./host-load-forge-cgroups.js";
|
|
5
|
+
export const defaultHostLoadSampleIntervalMs = 5_000;
|
|
6
|
+
/** Samples kept for the governor's pressure streak (FORGE_HOST_LOAD_BACKPRESSURE_SAMPLES is at most 60). */
|
|
7
|
+
const retainedSampleCount = 64;
|
|
8
|
+
/**
|
|
9
|
+
* Samples Linux PSI and the bridge's own cgroup on an interval and caches the
|
|
10
|
+
* latest snapshot. Every read is async and failure-tolerant: a host without PSI
|
|
11
|
+
* (non-Linux, old kernel, `psi=0`) reports `psiAvailable: false` and no pressure.
|
|
12
|
+
*/
|
|
13
|
+
export class HostLoadSampler {
|
|
14
|
+
environment;
|
|
15
|
+
intervalMs;
|
|
16
|
+
now;
|
|
17
|
+
monotonicNow;
|
|
18
|
+
cgroupUnit;
|
|
19
|
+
generation = 0;
|
|
20
|
+
timer = null;
|
|
21
|
+
starting = null;
|
|
22
|
+
inFlight = null;
|
|
23
|
+
hostFacts = null;
|
|
24
|
+
latest = null;
|
|
25
|
+
history = [];
|
|
26
|
+
cpuMark = null;
|
|
27
|
+
hostCpuMark = null;
|
|
28
|
+
latestCpuAttribution = null;
|
|
29
|
+
latestMemoryHeadroom = null;
|
|
30
|
+
constructor(options = {}) {
|
|
31
|
+
this.environment = options.environment ?? defaultHostEnvironment();
|
|
32
|
+
this.intervalMs = options.intervalMs !== undefined && Number.isFinite(options.intervalMs) && options.intervalMs > 0
|
|
33
|
+
? options.intervalMs
|
|
34
|
+
: defaultHostLoadSampleIntervalMs;
|
|
35
|
+
this.now = options.now ?? Date.now;
|
|
36
|
+
this.monotonicNow = options.monotonicNow ?? (() => performance.now());
|
|
37
|
+
this.cgroupUnit = options.cgroupUnit !== undefined
|
|
38
|
+
? options.cgroupUnit
|
|
39
|
+
: process.env.FORGE_BRIDGE_CGROUP_UNIT?.trim() || null;
|
|
40
|
+
}
|
|
41
|
+
facts() {
|
|
42
|
+
return this.hostFacts;
|
|
43
|
+
}
|
|
44
|
+
current() {
|
|
45
|
+
return this.latest;
|
|
46
|
+
}
|
|
47
|
+
cpuAttribution() {
|
|
48
|
+
return this.latestCpuAttribution;
|
|
49
|
+
}
|
|
50
|
+
cgroupMemoryHeadroomBytes() {
|
|
51
|
+
return this.latestMemoryHeadroom;
|
|
52
|
+
}
|
|
53
|
+
recent() {
|
|
54
|
+
return [...this.history];
|
|
55
|
+
}
|
|
56
|
+
/** Detects static facts once, takes a first sample, then samples on the interval. Idempotent. */
|
|
57
|
+
start() {
|
|
58
|
+
if (this.timer)
|
|
59
|
+
return Promise.resolve();
|
|
60
|
+
this.starting ??= this.startOnce().finally(() => {
|
|
61
|
+
this.starting = null;
|
|
62
|
+
});
|
|
63
|
+
return this.starting;
|
|
64
|
+
}
|
|
65
|
+
stop() {
|
|
66
|
+
// Invalidates an in-progress start() so it cannot arm the interval afterwards.
|
|
67
|
+
this.generation += 1;
|
|
68
|
+
if (this.timer)
|
|
69
|
+
clearInterval(this.timer);
|
|
70
|
+
this.timer = null;
|
|
71
|
+
}
|
|
72
|
+
/** Takes one sample now and caches it. Concurrent callers share one read. */
|
|
73
|
+
sample() {
|
|
74
|
+
this.inFlight ??= this.readSnapshot()
|
|
75
|
+
.then(snapshot => {
|
|
76
|
+
this.latest = snapshot;
|
|
77
|
+
this.history.push(snapshot);
|
|
78
|
+
if (this.history.length > retainedSampleCount)
|
|
79
|
+
this.history.splice(0, this.history.length - retainedSampleCount);
|
|
80
|
+
return snapshot;
|
|
81
|
+
})
|
|
82
|
+
.finally(() => {
|
|
83
|
+
this.inFlight = null;
|
|
84
|
+
});
|
|
85
|
+
return this.inFlight;
|
|
86
|
+
}
|
|
87
|
+
async startOnce() {
|
|
88
|
+
const generation = this.generation;
|
|
89
|
+
if (!this.hostFacts) {
|
|
90
|
+
this.hostFacts = await detectHostFacts(this.environment).catch(() => null);
|
|
91
|
+
}
|
|
92
|
+
await this.sample().catch(() => undefined);
|
|
93
|
+
if (this.timer || generation !== this.generation)
|
|
94
|
+
return;
|
|
95
|
+
this.timer = setInterval(() => {
|
|
96
|
+
void this.sample().catch(() => undefined);
|
|
97
|
+
}, this.intervalMs);
|
|
98
|
+
this.timer.unref?.();
|
|
99
|
+
}
|
|
100
|
+
async readSnapshot() {
|
|
101
|
+
const sampledAtMs = this.now();
|
|
102
|
+
const monotonicMs = this.monotonicNow();
|
|
103
|
+
const linux = this.environment.platform === "linux";
|
|
104
|
+
const [systemPressure, ownCgroup, memoryAvailableBytes, hostCoresInUse, cgroupMemoryHeadroomBytes] = linux
|
|
105
|
+
? await Promise.all([
|
|
106
|
+
this.readSystemPressure(),
|
|
107
|
+
this.readOwnCgroup(monotonicMs),
|
|
108
|
+
this.readMemoryAvailable(),
|
|
109
|
+
this.readHostCoresInUse(),
|
|
110
|
+
this.readCgroupMemoryHeadroom(),
|
|
111
|
+
])
|
|
112
|
+
: [null, null, this.fallbackFreeMemory(), null, null];
|
|
113
|
+
const sampledAt = new Date(sampledAtMs).toISOString();
|
|
114
|
+
this.latestMemoryHeadroom = cgroupMemoryHeadroomBytes;
|
|
115
|
+
this.latestCpuAttribution = hostCpuAttribution(sampledAt, hostCoresInUse, ownCgroup?.cpuCoresInUse ?? null);
|
|
116
|
+
return {
|
|
117
|
+
sampledAt,
|
|
118
|
+
psiAvailable: systemPressure !== null,
|
|
119
|
+
systemPressure,
|
|
120
|
+
ownCgroupDedicated: ownCgroup !== null,
|
|
121
|
+
ownCgroup,
|
|
122
|
+
memoryAvailableBytes,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
async readCgroupMemoryHeadroom() {
|
|
126
|
+
const membership = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "self", "cgroup"));
|
|
127
|
+
const cgroupPath = membership ? parseUnifiedCgroupMembership(membership) : null;
|
|
128
|
+
return cgroupPath ? await readCgroupMemoryHeadroomBytes(this.environment, cgroupPath).catch(() => null) : null;
|
|
129
|
+
}
|
|
130
|
+
async readSystemPressure() {
|
|
131
|
+
const pressureRoot = path.posix.join(this.environment.procRoot, "pressure");
|
|
132
|
+
const [cpu, memory, io] = await Promise.all(["cpu", "memory", "io"].map(resource => this.readPressure(path.posix.join(pressureRoot, resource))));
|
|
133
|
+
// CPU pressure is the governor's primary signal; without it PSI is unavailable.
|
|
134
|
+
return cpu ? { cpu, memory: memory ?? null, io: io ?? null } : null;
|
|
135
|
+
}
|
|
136
|
+
async readOwnCgroup(monotonicMs) {
|
|
137
|
+
const membership = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "self", "cgroup"));
|
|
138
|
+
const cgroupPath = membership ? parseUnifiedCgroupPath(membership) : null;
|
|
139
|
+
const unit = cgroupPath ? cgroupLeafName(cgroupPath) : null;
|
|
140
|
+
if (!cgroupPath || !unit || !isDedicatedBridgeUnit(unit, this.cgroupUnit)) {
|
|
141
|
+
this.cpuMark = null;
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
const directory = path.posix.join(this.environment.cgroupRoot, cgroupPath);
|
|
145
|
+
if (!directory.startsWith(`${this.environment.cgroupRoot.replace(/\/+$/u, "")}/`))
|
|
146
|
+
return null;
|
|
147
|
+
const [cpuPressure, memoryPressure, cpuStat, memoryStat, memoryCurrent] = await Promise.all([
|
|
148
|
+
this.readPressure(path.posix.join(directory, "cpu.pressure")),
|
|
149
|
+
this.readPressure(path.posix.join(directory, "memory.pressure")),
|
|
150
|
+
readOptional(this.environment, path.posix.join(directory, "cpu.stat")),
|
|
151
|
+
readOptional(this.environment, path.posix.join(directory, "memory.stat")),
|
|
152
|
+
readOptional(this.environment, path.posix.join(directory, "memory.current")),
|
|
153
|
+
]);
|
|
154
|
+
const usageUsec = cpuStat ? parseCgroupCpuUsageUsec(cpuStat) : null;
|
|
155
|
+
const memoryAnonBytes = memoryStat ? parseCgroupMemoryAnonBytes(memoryStat) : null;
|
|
156
|
+
const memoryChargedBytes = memoryCurrent ? parseNonNegativeInteger(memoryCurrent) : null;
|
|
157
|
+
// Ownership is settled by membership and the unit name above; metric files that are
|
|
158
|
+
// unavailable yield null values (and reset the CPU mark) but never demote the unit to shared.
|
|
159
|
+
return {
|
|
160
|
+
unit,
|
|
161
|
+
cpuPressure,
|
|
162
|
+
memoryPressure,
|
|
163
|
+
cpuCoresInUse: this.coresInUse(cgroupPath, usageUsec, monotonicMs),
|
|
164
|
+
memoryAnonBytes,
|
|
165
|
+
memoryChargedBytes,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
coresInUse(cgroupPath, usageUsec, atMs) {
|
|
169
|
+
const previous = this.cpuMark;
|
|
170
|
+
this.cpuMark = usageUsec === null ? null : { cgroupPath, usageUsec, atMs };
|
|
171
|
+
if (!previous || usageUsec === null || previous.cgroupPath !== cgroupPath)
|
|
172
|
+
return null;
|
|
173
|
+
const elapsedUsec = (atMs - previous.atMs) * 1_000;
|
|
174
|
+
const usedUsec = usageUsec - previous.usageUsec;
|
|
175
|
+
// A restarted unit resets its counter; elapsed time comes from a monotonic clock.
|
|
176
|
+
if (elapsedUsec <= 0 || usedUsec < 0)
|
|
177
|
+
return null;
|
|
178
|
+
return roundCores(usedUsec / elapsedUsec);
|
|
179
|
+
}
|
|
180
|
+
async readHostCoresInUse() {
|
|
181
|
+
const content = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "stat"));
|
|
182
|
+
const totals = content ? parseProcStatCpuTotals(content) : null;
|
|
183
|
+
const previous = this.hostCpuMark;
|
|
184
|
+
this.hostCpuMark = totals;
|
|
185
|
+
if (!totals || !previous || previous.cpuCount !== totals.cpuCount)
|
|
186
|
+
return null;
|
|
187
|
+
const totalDelta = totals.totalTicks - previous.totalTicks;
|
|
188
|
+
const busyDelta = totals.busyTicks - previous.busyTicks;
|
|
189
|
+
if (totalDelta <= 0 || busyDelta < 0)
|
|
190
|
+
return null;
|
|
191
|
+
return roundCores((busyDelta / totalDelta) * totals.cpuCount);
|
|
192
|
+
}
|
|
193
|
+
async readMemoryAvailable() {
|
|
194
|
+
const meminfo = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "meminfo"));
|
|
195
|
+
return (meminfo ? parseMemAvailableBytes(meminfo) : null) ?? this.fallbackFreeMemory();
|
|
196
|
+
}
|
|
197
|
+
fallbackFreeMemory() {
|
|
198
|
+
try {
|
|
199
|
+
const free = this.environment.freeMemoryBytes();
|
|
200
|
+
return Number.isFinite(free) && free >= 0 ? free : null;
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
return null;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
async readPressure(filePath) {
|
|
207
|
+
const content = await readOptional(this.environment, filePath);
|
|
208
|
+
return content ? parsePressureStall(content) : null;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
function roundCores(value) {
|
|
212
|
+
return Math.round(value * 100) / 100;
|
|
213
|
+
}
|
|
214
|
+
function hostCpuAttribution(sampledAt, hostCoresInUse, ownCoresInUse) {
|
|
215
|
+
if (hostCoresInUse === null)
|
|
216
|
+
return null;
|
|
217
|
+
return {
|
|
218
|
+
sampledAt,
|
|
219
|
+
hostCoresInUse,
|
|
220
|
+
ownCoresInUse,
|
|
221
|
+
// Own usage only exists for a dedicated cgroup; a shared scope never yields external load.
|
|
222
|
+
externalCoresInUse: ownCoresInUse === null ? null : roundCores(Math.max(0, hostCoresInUse - ownCoresInUse)),
|
|
223
|
+
};
|
|
224
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export interface HostLoadStepCost {
|
|
2
|
+
/** Cores the step is expected to keep busy. */
|
|
3
|
+
readonly cpuCores: number;
|
|
4
|
+
/** Peak resident memory the step is expected to need. */
|
|
5
|
+
readonly memoryBytes: number;
|
|
6
|
+
}
|
|
7
|
+
export interface HostLoadStepClassification {
|
|
8
|
+
readonly stepClass: string;
|
|
9
|
+
readonly cost: HostLoadStepCost;
|
|
10
|
+
}
|
|
11
|
+
export declare const defaultHostLoadStepCosts: {
|
|
12
|
+
readonly dotnetTier: {
|
|
13
|
+
readonly cpuCores: 2;
|
|
14
|
+
readonly memoryBytes: number;
|
|
15
|
+
};
|
|
16
|
+
readonly vitest: {
|
|
17
|
+
readonly cpuCores: 1;
|
|
18
|
+
readonly memoryBytes: number;
|
|
19
|
+
};
|
|
20
|
+
readonly playwright: {
|
|
21
|
+
readonly cpuCores: 2;
|
|
22
|
+
readonly memoryBytes: number;
|
|
23
|
+
};
|
|
24
|
+
readonly generic: {
|
|
25
|
+
readonly cpuCores: 1;
|
|
26
|
+
readonly memoryBytes: number;
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Maps a pre-publication validation step to its class: `dotnet.tier.<tier>`,
|
|
31
|
+
* `vitest.<suite>`, `playwright.e2e`, or `generic` for everything else.
|
|
32
|
+
*/
|
|
33
|
+
export declare function classifyValidationStep(checkId: string, command: string, args: readonly string[]): HostLoadStepClassification;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// Step classes and conservative default costs for governed heavy steps
|
|
2
|
+
// (decision 0013). Step 4 replaces the defaults with P75 estimates from history.
|
|
3
|
+
const gib = 1024 ** 3;
|
|
4
|
+
export const defaultHostLoadStepCosts = {
|
|
5
|
+
dotnetTier: { cpuCores: 2, memoryBytes: 3 * gib },
|
|
6
|
+
vitest: { cpuCores: 1, memoryBytes: 1.5 * gib },
|
|
7
|
+
playwright: { cpuCores: 2, memoryBytes: 2 * gib },
|
|
8
|
+
generic: { cpuCores: 1, memoryBytes: 1 * gib },
|
|
9
|
+
};
|
|
10
|
+
const dotnetTierScripts = ["scripts/run-dotnet-test-tier.ps1", "scripts/run-dotnet-test-tier-set.ps1"];
|
|
11
|
+
const affectedDotnetScript = "scripts/run-affected-dotnet-tests.mjs";
|
|
12
|
+
const vitestSuites = new Set(["client", "bridge"]);
|
|
13
|
+
/**
|
|
14
|
+
* Maps a pre-publication validation step to its class: `dotnet.tier.<tier>`,
|
|
15
|
+
* `vitest.<suite>`, `playwright.e2e`, or `generic` for everything else.
|
|
16
|
+
*/
|
|
17
|
+
export function classifyValidationStep(checkId, command, args) {
|
|
18
|
+
const normalized = args.map(argument => argument.replaceAll("\\", "/"));
|
|
19
|
+
if (checkId === "playwright-e2e") {
|
|
20
|
+
return { stepClass: "playwright.e2e", cost: defaultHostLoadStepCosts.playwright };
|
|
21
|
+
}
|
|
22
|
+
if (normalized.some(argument => dotnetTierScripts.some(script => argument.endsWith(script)))) {
|
|
23
|
+
return { stepClass: `dotnet.tier.${stepClassSegment(tierArgument(normalized))}`, cost: defaultHostLoadStepCosts.dotnetTier };
|
|
24
|
+
}
|
|
25
|
+
if (normalized.some(argument => argument.endsWith(affectedDotnetScript))) {
|
|
26
|
+
return { stepClass: "dotnet.tier.affected", cost: defaultHostLoadStepCosts.dotnetTier };
|
|
27
|
+
}
|
|
28
|
+
if (vitestSuites.has(checkId) && isTestScript(command, normalized)) {
|
|
29
|
+
return { stepClass: `vitest.${checkId}`, cost: defaultHostLoadStepCosts.vitest };
|
|
30
|
+
}
|
|
31
|
+
return { stepClass: "generic", cost: defaultHostLoadStepCosts.generic };
|
|
32
|
+
}
|
|
33
|
+
function tierArgument(args) {
|
|
34
|
+
const index = args.findIndex(argument => /^-(tier|tiers)$/iu.test(argument));
|
|
35
|
+
return index >= 0 ? args[index + 1] ?? "unknown" : "unknown";
|
|
36
|
+
}
|
|
37
|
+
function isTestScript(command, args) {
|
|
38
|
+
if (!["npm", "pnpm", "npx", "vitest"].includes(command))
|
|
39
|
+
return false;
|
|
40
|
+
const last = args.at(-1);
|
|
41
|
+
return last === "test" || command === "vitest" || args.includes("vitest");
|
|
42
|
+
}
|
|
43
|
+
function stepClassSegment(value) {
|
|
44
|
+
const segment = value.trim().toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "");
|
|
45
|
+
return segment || "unknown";
|
|
46
|
+
}
|