@loucompanion/forge-bridge 0.1.4-dev.9ddc336f8a9d → 0.1.4-dev.a5a3a7ab2f02
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 +35 -2
- package/dist/bridge/bridge.base.d.ts +9 -0
- package/dist/bridge/bridge.service.d.ts +72 -1
- package/dist/bridge/bridge.service.js +308 -9
- package/dist/bridge/bridge.types.d.ts +16 -0
- package/dist/bridge/local-yield-flag.d.ts +6 -0
- package/dist/bridge/local-yield-flag.js +34 -0
- 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/cleanup/cleanup.service.d.ts +9 -0
- package/dist/cleanup/cleanup.service.js +72 -109
- package/dist/cleanup/cleanup.types.d.ts +4 -0
- package/dist/cleanup/forge-owned-paths.d.ts +9 -0
- package/dist/cleanup/forge-owned-paths.js +53 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
- package/dist/cleanup/host-runtime-ledger.js +109 -0
- package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
- package/dist/cleanup/managed-branch-sweep.js +111 -0
- package/dist/cli/cli.help.js +18 -0
- package/dist/cli/cli.service.d.ts +16 -0
- package/dist/cli/cli.service.js +142 -16
- package/dist/cli/local-config.d.ts +4 -0
- package/dist/cli/local-config.js +26 -4
- package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
- package/dist/runtime/host-load-admission.d.ts +60 -0
- package/dist/runtime/host-load-admission.js +99 -0
- package/dist/runtime/host-load-child-environment.d.ts +22 -0
- package/dist/runtime/host-load-child-environment.js +67 -0
- package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
- package/dist/runtime/host-load-forge-cgroups.js +140 -0
- package/dist/runtime/host-load-governor-config.d.ts +43 -0
- package/dist/runtime/host-load-governor-config.js +76 -0
- package/dist/runtime/host-load-governor.d.ts +174 -0
- package/dist/runtime/host-load-governor.js +541 -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-runtime-settings.d.ts +25 -0
- package/dist/runtime/host-load-runtime-settings.js +78 -0
- package/dist/runtime/host-load-sampler.d.ts +43 -0
- package/dist/runtime/host-load-sampler.js +74 -6
- package/dist/runtime/host-load-step-class.d.ts +68 -0
- package/dist/runtime/host-load-step-class.js +106 -0
- package/dist/runtime/host-load-step-reaper.d.ts +27 -0
- package/dist/runtime/host-load-step-reaper.js +95 -0
- package/dist/runtime/host-load-step-run.d.ts +73 -0
- package/dist/runtime/host-load-step-run.js +102 -0
- package/dist/runtime/host-load-token-ledger.d.ts +174 -0
- package/dist/runtime/host-load-token-ledger.js +421 -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-contract.d.ts +3 -0
- package/dist/runtime/host-runtime-contract.js +4 -1
- package/dist/runtime/host-runtime-lease.d.ts +74 -4
- package/dist/runtime/host-runtime-lease.js +281 -11
- package/dist/runtime/host-runtime-promotion.d.ts +23 -0
- package/dist/runtime/host-runtime-promotion.js +48 -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/playwright-host-runtime-adapter.d.ts +7 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
- package/dist/runtime/runner-settings.d.ts +100 -0
- package/dist/runtime/runner-settings.js +214 -0
- package/dist/sandbox/host-capacity-broker.d.ts +107 -0
- package/dist/sandbox/host-capacity-broker.js +315 -0
- package/dist/sandbox/runtime.d.ts +10 -1
- package/dist/sandbox/runtime.js +45 -2
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/session/managed-attempt-tools.d.ts +2 -0
- package/dist/session/managed-attempt-tools.js +156 -37
- package/dist/session/managed-command-host-load.d.ts +45 -0
- package/dist/session/managed-command-host-load.js +82 -0
- package/dist/session/mcp-argument-coercion.d.ts +23 -0
- package/dist/session/mcp-argument-coercion.js +121 -0
- package/dist/session/phase-completion.artifacts.d.ts +7 -0
- package/dist/session/phase-completion.artifacts.js +98 -25
- package/dist/session/phase-completion.command-validation.d.ts +7 -0
- package/dist/session/phase-completion.command-validation.js +77 -0
- package/dist/session/phase-completion.d.ts +4 -0
- package/dist/session/phase-completion.helpers.js +13 -12
- package/dist/session/phase-completion.js +4 -0
- package/dist/session/phase-completion.prompts.js +6 -1
- package/dist/session/phase-completion.runtime.d.ts +5 -3
- package/dist/session/phase-completion.runtime.js +49 -19
- package/dist/session/phase-completion.schema-parts.d.ts +19 -0
- package/dist/session/phase-completion.schema-parts.js +188 -0
- package/dist/session/phase-completion.schemas.d.ts +3 -3
- package/dist/session/phase-completion.schemas.js +184 -209
- package/dist/session/phase-completion.validation.d.ts +2 -3
- package/dist/session/phase-completion.validation.js +46 -92
- package/dist/session/pre-publication-host-load.d.ts +27 -0
- package/dist/session/pre-publication-host-load.js +111 -0
- package/dist/session/pre-publication-process.d.ts +3 -0
- package/dist/session/pre-publication-process.js +23 -11
- 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 +21 -55
- 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 +32 -1
- package/dist/session/provider-cli/provider-cli.process.js +122 -30
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +20 -2
- package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
- package/dist/session/provider-cli/provider-cli.service.js +237 -33
- package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
- 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/sandbox-host-capacity-gate.d.ts +30 -0
- package/dist/session/sandbox-host-capacity-gate.js +229 -0
- package/dist/session/session.base.d.ts +9 -1
- package/dist/session/session.service.d.ts +9 -2
- package/dist/session/session.service.js +120 -5
- package/dist/session/session.types.d.ts +3 -0
- package/dist/session/session.types.js +15 -3
- package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
- package/dist/session/workspace-runtime-fingerprint.js +138 -0
- package/dist/shared/process/host-process-supervisor.d.ts +1 -0
- package/dist/shared/process/host-process-supervisor.js +1 -1
- package/dist/shared/process/process-tree.d.ts +52 -0
- package/dist/shared/process/process-tree.js +144 -0
- package/dist/shared/process/process.d.ts +67 -0
- package/dist/shared/process/process.js +213 -11
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/dependency-warmer.d.ts +25 -0
- package/dist/worktree/dependency-warmer.js +46 -10
- package/dist/worktree/worktree.service.d.ts +10 -1
- package/dist/worktree/worktree.service.js +42 -2
- package/dist/worktree/worktree.types.d.ts +7 -0
- package/package.json +2 -2
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import fs from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { ForgeFailureError } from "../session/session.types.js";
|
|
6
|
+
import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
|
|
7
|
+
import { HostCapacityLedgerUnavailableError, HostLoadLedgerLock } from "./host-load-ledger-lock.js";
|
|
8
|
+
import { terminateHostLoadStepProcess, validHostLoadStepProcess, } from "./host-load-step-reaper.js";
|
|
9
|
+
const processInstanceId = randomUUID();
|
|
10
|
+
const maximumLedgerBytes = 1024 * 1024;
|
|
11
|
+
/** A degraded token's tree is retried at most this often, so a stuck process cannot stall every admission. */
|
|
12
|
+
const degradedRetryMs = 30_000;
|
|
13
|
+
export class HostCapacityTokenFencedError extends ForgeFailureError {
|
|
14
|
+
tokenId;
|
|
15
|
+
code = "host_capacity_token_fenced";
|
|
16
|
+
constructor(tokenId, action) {
|
|
17
|
+
super("host_capacity_token_fenced", action === "released_fenced"
|
|
18
|
+
? `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.`
|
|
19
|
+
: `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");
|
|
20
|
+
this.tokenId = tokenId;
|
|
21
|
+
this.name = "HostCapacityTokenFencedError";
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
let cachedCurrentOwner = null;
|
|
25
|
+
/**
|
|
26
|
+
* This process as a token owner, computed once. The birth marker is read only
|
|
27
|
+
* on Linux (a cheap /proc read); elsewhere it would mean a synchronous process
|
|
28
|
+
* spawn, so pid reuse there is covered by the lease and the instance id.
|
|
29
|
+
*/
|
|
30
|
+
export function currentHostLoadTokenOwner() {
|
|
31
|
+
cachedCurrentOwner ??= {
|
|
32
|
+
pid: process.pid,
|
|
33
|
+
processIdentity: linuxProcessIdentity(process.pid),
|
|
34
|
+
processInstanceId,
|
|
35
|
+
};
|
|
36
|
+
return cachedCurrentOwner;
|
|
37
|
+
}
|
|
38
|
+
/** Owner liveness from the OS: dead pid, or a pid reused by a different process, is gone. */
|
|
39
|
+
export const processHostLoadOwnerLiveness = {
|
|
40
|
+
isLive(owner) {
|
|
41
|
+
if (owner.pid === process.pid)
|
|
42
|
+
return owner.processInstanceId === processInstanceId;
|
|
43
|
+
try {
|
|
44
|
+
process.kill(owner.pid, 0);
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
if (error.code !== "EPERM")
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
if (!owner.processIdentity)
|
|
51
|
+
return true;
|
|
52
|
+
const current = linuxProcessIdentity(owner.pid);
|
|
53
|
+
return current === null || current === owner.processIdentity;
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
function linuxProcessIdentity(pid) {
|
|
57
|
+
return process.platform === "linux" ? captureHostProcessIdentity(pid, "linux") : null;
|
|
58
|
+
}
|
|
59
|
+
/** Lapsed: past its lease even after taking away the time the host was suspended since renewal. */
|
|
60
|
+
function leaseLapsed(token, nowMs, suspendedMs) {
|
|
61
|
+
const expiresAtMs = Date.parse(token.expiresAt);
|
|
62
|
+
if (!Number.isFinite(expiresAtMs))
|
|
63
|
+
return true;
|
|
64
|
+
const asleepMs = Math.max(0, suspendedMs - (token.suspendedMsAtRenewal ?? suspendedMs));
|
|
65
|
+
return expiresAtMs + asleepMs <= nowMs;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Total time the host has been suspended (Linux: boot-time uptime minus the
|
|
69
|
+
* monotonic clock, which stops while suspended). Zero where it is unknown.
|
|
70
|
+
*/
|
|
71
|
+
export function hostSuspendedMs() {
|
|
72
|
+
if (process.platform !== "linux")
|
|
73
|
+
return 0;
|
|
74
|
+
try {
|
|
75
|
+
const uptimeMs = Number(readFileSync("/proc/uptime", "utf8").split(/\s+/u)[0]) * 1000;
|
|
76
|
+
const monotonicMs = Number(process.hrtime.bigint() / 1000000n);
|
|
77
|
+
return Number.isFinite(uptimeMs) ? Math.max(0, Math.round(uptimeMs - monotonicMs)) : 0;
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return 0;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
export class HostLoadTokenLedger {
|
|
84
|
+
options;
|
|
85
|
+
root;
|
|
86
|
+
ledgerPath;
|
|
87
|
+
now;
|
|
88
|
+
liveness;
|
|
89
|
+
resolvedOwner;
|
|
90
|
+
lock;
|
|
91
|
+
tail = Promise.resolve();
|
|
92
|
+
constructor(options) {
|
|
93
|
+
this.options = options;
|
|
94
|
+
this.root = path.join(options.stateRoot, "host-load-governor");
|
|
95
|
+
this.ledgerPath = path.join(this.root, "tokens.v1.json");
|
|
96
|
+
this.now = options.now ?? Date.now;
|
|
97
|
+
this.liveness = options.liveness ?? processHostLoadOwnerLiveness;
|
|
98
|
+
this.resolvedOwner = options.owner ?? null;
|
|
99
|
+
this.lock = new HostLoadLedgerLock({
|
|
100
|
+
lockPath: path.join(this.root, "tokens.lock"),
|
|
101
|
+
holder: () => this.owner,
|
|
102
|
+
isLive: holder => this.liveness.isLive(holder),
|
|
103
|
+
timeoutMs: options.lockTimeoutMs ?? 10_000,
|
|
104
|
+
beforeStaleBreak: options.beforeStaleLockBreak,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
suspendedMs() {
|
|
108
|
+
return (this.options.suspendedMs ?? hostSuspendedMs)();
|
|
109
|
+
}
|
|
110
|
+
get owner() {
|
|
111
|
+
this.resolvedOwner ??= currentHostLoadTokenOwner();
|
|
112
|
+
return this.resolvedOwner;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Runs `action` under the cross-process ledger lock against the live token
|
|
116
|
+
* set. Dead or expired tokens are reclaimed first, so every admission
|
|
117
|
+
* decision sees only real reservations.
|
|
118
|
+
*/
|
|
119
|
+
async transaction(action) {
|
|
120
|
+
const run = this.tail.then(() => this.lockedTransaction(action));
|
|
121
|
+
this.tail = run.catch(() => undefined);
|
|
122
|
+
return await run;
|
|
123
|
+
}
|
|
124
|
+
async reclaim() {
|
|
125
|
+
return (await this.transaction(() => undefined)).reclaimed;
|
|
126
|
+
}
|
|
127
|
+
async list() {
|
|
128
|
+
return (await this.transaction(transaction => transaction.tokens)).result;
|
|
129
|
+
}
|
|
130
|
+
/** Extends a token's lease. A fenced, reclaimed or superseded token is rejected. */
|
|
131
|
+
async renew(tokenId, fencingToken) {
|
|
132
|
+
const renewed = (await this.transaction(transaction => transaction.renew(tokenId, fencingToken))).result;
|
|
133
|
+
if (!renewed)
|
|
134
|
+
throw new HostCapacityTokenFencedError(tokenId, "renew");
|
|
135
|
+
return renewed;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Returns a token. A reclaimed or superseded token is rejected, never released
|
|
139
|
+
* twice. A fenced token is removed (its owner's step is over) but still
|
|
140
|
+
* reported as fenced.
|
|
141
|
+
*/
|
|
142
|
+
async release(tokenId, fencingToken) {
|
|
143
|
+
const outcome = (await this.transaction(transaction => {
|
|
144
|
+
const entry = transaction.tokens.find(token => token.tokenId === tokenId && token.fencingToken === fencingToken);
|
|
145
|
+
if (!entry || !transaction.remove(tokenId, fencingToken))
|
|
146
|
+
return "missing";
|
|
147
|
+
return entry.fencedAt ? "fenced" : "released";
|
|
148
|
+
})).result;
|
|
149
|
+
if (outcome === "missing")
|
|
150
|
+
throw new HostCapacityTokenFencedError(tokenId, "release");
|
|
151
|
+
if (outcome === "fenced")
|
|
152
|
+
throw new HostCapacityTokenFencedError(tokenId, "released_fenced");
|
|
153
|
+
}
|
|
154
|
+
async lockedTransaction(action) {
|
|
155
|
+
await fs.mkdir(this.root, { recursive: true, mode: 0o700 }).catch(error => {
|
|
156
|
+
throw new HostCapacityLedgerUnavailableError("the host load ledger directory could not be created.", { cause: error });
|
|
157
|
+
});
|
|
158
|
+
const lockToken = await this.lock.acquire();
|
|
159
|
+
try {
|
|
160
|
+
const { ledger, quarantined } = await this.read();
|
|
161
|
+
const nowMs = this.now();
|
|
162
|
+
const nowIso = new Date(nowMs).toISOString();
|
|
163
|
+
const expiresAt = () => new Date(this.now() + this.options.leaseMs).toISOString();
|
|
164
|
+
const suspendedMs = this.suspendedMs();
|
|
165
|
+
// Each lease records the host's suspend counter, so time asleep never counts as a missed renewal.
|
|
166
|
+
const lease = () => ({ expiresAt: expiresAt(), suspendedMsAtRenewal: suspendedMs });
|
|
167
|
+
const recoveringUntil = ledger.recoveringUntil && Date.parse(ledger.recoveringUntil) > nowMs
|
|
168
|
+
? ledger.recoveringUntil
|
|
169
|
+
: null;
|
|
170
|
+
// Running steps of this owner are renewed before anything is reclaimed.
|
|
171
|
+
const key = (token) => `${token.tokenId}:${token.fencingToken}`;
|
|
172
|
+
const held = this.options.heldTokens?.() ?? [];
|
|
173
|
+
const heldIds = new Set(held.map(key));
|
|
174
|
+
const ledgerIds = new Set(ledger.tokens.map(key));
|
|
175
|
+
// A held token missing from the ledger keeps its cost. While a quarantined
|
|
176
|
+
// ledger is recovering no step was admitted against the gap, so it is put
|
|
177
|
+
// back as is; otherwise capacity may have been reused, so it comes back fenced.
|
|
178
|
+
const restored = held
|
|
179
|
+
.filter(token => !ledgerIds.has(key(token)))
|
|
180
|
+
.map(token => ({ ...token, ...lease(), fencedAt: token.fencedAt ?? (recoveringUntil ? null : nowIso) }));
|
|
181
|
+
const current = [
|
|
182
|
+
...ledger.tokens.map(token => heldIds.has(key(token)) && !token.fencedAt ? { ...token, ...lease() } : token),
|
|
183
|
+
...restored,
|
|
184
|
+
];
|
|
185
|
+
const { reclaimed, degraded, fencedNow } = await this.reapExpired(current, nowMs, suspendedMs, nowIso);
|
|
186
|
+
let tokens = current
|
|
187
|
+
.filter(token => !reclaimed.includes(token))
|
|
188
|
+
.map(token => degraded.get(token) ?? fencedNow.get(token) ?? token);
|
|
189
|
+
let nextFencingToken = Math.max(ledger.nextFencingToken, ...restored.map(token => token.fencingToken + 1));
|
|
190
|
+
let changed = quarantined || reclaimed.length > 0 || degraded.size > 0 || fencedNow.size > 0 || held.length > 0
|
|
191
|
+
|| (ledger.recoveringUntil !== undefined && recoveringUntil === null);
|
|
192
|
+
const transaction = {
|
|
193
|
+
get tokens() { return tokens; },
|
|
194
|
+
recoveringUntil,
|
|
195
|
+
issue: request => {
|
|
196
|
+
const token = {
|
|
197
|
+
tokenId: randomUUID(),
|
|
198
|
+
fencingToken: nextFencingToken,
|
|
199
|
+
stepClass: request.stepClass,
|
|
200
|
+
label: request.label,
|
|
201
|
+
cost: { cpuCores: request.cost.cpuCores, memoryBytes: request.cost.memoryBytes },
|
|
202
|
+
dispatchAttemptId: request.dispatchAttemptId,
|
|
203
|
+
priority: request.priority,
|
|
204
|
+
owner: this.owner,
|
|
205
|
+
admittedAt: new Date(this.now()).toISOString(),
|
|
206
|
+
...lease(),
|
|
207
|
+
};
|
|
208
|
+
nextFencingToken += 1;
|
|
209
|
+
tokens = [...tokens, token];
|
|
210
|
+
changed = true;
|
|
211
|
+
return token;
|
|
212
|
+
},
|
|
213
|
+
renew: (tokenId, fencingToken) => {
|
|
214
|
+
const index = tokens.findIndex(token => token.tokenId === tokenId && token.fencingToken === fencingToken);
|
|
215
|
+
if (index < 0 || tokens[index].fencedAt)
|
|
216
|
+
return null;
|
|
217
|
+
const renewed = { ...tokens[index], ...lease() };
|
|
218
|
+
tokens = tokens.map((token, position) => position === index ? renewed : token);
|
|
219
|
+
changed = true;
|
|
220
|
+
return renewed;
|
|
221
|
+
},
|
|
222
|
+
attach: (tokenId, fencingToken, stepProcess) => {
|
|
223
|
+
const index = tokens.findIndex(token => token.tokenId === tokenId && token.fencingToken === fencingToken);
|
|
224
|
+
if (index < 0 || tokens[index].fencedAt)
|
|
225
|
+
return null;
|
|
226
|
+
const attached = { ...tokens[index], stepProcess };
|
|
227
|
+
tokens = tokens.map((token, position) => position === index ? attached : token);
|
|
228
|
+
changed = true;
|
|
229
|
+
return attached;
|
|
230
|
+
},
|
|
231
|
+
remove: (tokenId, fencingToken) => {
|
|
232
|
+
const before = tokens.length;
|
|
233
|
+
tokens = tokens.filter(token => !(token.tokenId === tokenId && token.fencingToken === fencingToken));
|
|
234
|
+
changed ||= tokens.length !== before;
|
|
235
|
+
return tokens.length !== before;
|
|
236
|
+
},
|
|
237
|
+
};
|
|
238
|
+
const result = await action(transaction);
|
|
239
|
+
if (changed) {
|
|
240
|
+
// A lock broken under us (a stalled holder taken for dead) must not commit.
|
|
241
|
+
if (!await this.lock.holds(lockToken)) {
|
|
242
|
+
throw new HostCapacityLedgerUnavailableError("the ledger lock was lost before the update could be written.");
|
|
243
|
+
}
|
|
244
|
+
await this.write({
|
|
245
|
+
schemaVersion: 1,
|
|
246
|
+
nextFencingToken,
|
|
247
|
+
tokens,
|
|
248
|
+
...recoveringUntil ? { recoveringUntil } : {},
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
const heldNow = tokens.filter(token => heldIds.has(key(token)));
|
|
252
|
+
return {
|
|
253
|
+
result,
|
|
254
|
+
reclaimed,
|
|
255
|
+
fenced: heldNow.filter(token => Boolean(token.fencedAt)),
|
|
256
|
+
renewed: heldNow.filter(token => !token.fencedAt),
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
finally {
|
|
260
|
+
await this.lock.release(lockToken);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Decides every token another owner can no longer vouch for (decision 0013):
|
|
265
|
+
* - owner alive but its lease lapsed (it stalled): the token is fenced, never
|
|
266
|
+
* killed, and keeps its cost; the owner stops its own step when it next
|
|
267
|
+
* touches the ledger and returns the capacity when it releases the token;
|
|
268
|
+
* - owner gone with a recorded process tree: the tree is stopped and confirmed
|
|
269
|
+
* gone first, otherwise the token stays degraded and keeps its cost;
|
|
270
|
+
* - owner gone with no recorded tree: degraded, keeping its cost, until the
|
|
271
|
+
* attempt's teardown or the bridge's restart reap proves the step stopped
|
|
272
|
+
* (releaseOrphaned).
|
|
273
|
+
*/
|
|
274
|
+
async reapExpired(current, nowMs, suspendedMs, nowIso) {
|
|
275
|
+
const reclaimed = [];
|
|
276
|
+
const degraded = new Map();
|
|
277
|
+
const fencedNow = new Map();
|
|
278
|
+
const terminate = this.options.terminateStep ?? terminateHostLoadStepProcess;
|
|
279
|
+
for (const token of current) {
|
|
280
|
+
if (this.liveness.isLive(token.owner)) {
|
|
281
|
+
// Its step may still be running: fence it, but never free its capacity.
|
|
282
|
+
if (!token.fencedAt && leaseLapsed(token, nowMs, suspendedMs))
|
|
283
|
+
fencedNow.set(token, { ...token, fencedAt: nowIso });
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
const lastDegraded = token.degradedAt ? Date.parse(token.degradedAt) : Number.NaN;
|
|
287
|
+
if (Number.isFinite(lastDegraded) && nowMs - lastDegraded < degradedRetryMs)
|
|
288
|
+
continue;
|
|
289
|
+
const gone = Boolean(token.stepProcess) && await terminate(token.stepProcess).catch(() => false);
|
|
290
|
+
if (gone)
|
|
291
|
+
reclaimed.push(token);
|
|
292
|
+
else
|
|
293
|
+
degraded.set(token, { ...token, degradedAt: new Date(nowMs).toISOString() });
|
|
294
|
+
}
|
|
295
|
+
return { reclaimed, degraded, fencedNow };
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Returns dead owners' tokens that have no recorded process tree once the
|
|
299
|
+
* caller has proven their steps stopped (attempt teardown after its process
|
|
300
|
+
* trees are stopped, or the restart reap after attempt recovery).
|
|
301
|
+
*/
|
|
302
|
+
async releaseOrphaned(belongs) {
|
|
303
|
+
return (await this.transaction(transaction => {
|
|
304
|
+
const orphaned = transaction.tokens.filter(token => !token.stepProcess && belongs(token) && !this.liveness.isLive(token.owner));
|
|
305
|
+
for (const token of orphaned)
|
|
306
|
+
transaction.remove(token.tokenId, token.fencingToken);
|
|
307
|
+
return orphaned;
|
|
308
|
+
})).result;
|
|
309
|
+
}
|
|
310
|
+
async read() {
|
|
311
|
+
let content;
|
|
312
|
+
try {
|
|
313
|
+
const stat = await fs.lstat(this.ledgerPath);
|
|
314
|
+
if (!stat.isFile() || stat.size > maximumLedgerBytes)
|
|
315
|
+
return await this.quarantine(null);
|
|
316
|
+
content = await fs.readFile(this.ledgerPath, "utf8");
|
|
317
|
+
}
|
|
318
|
+
catch (error) {
|
|
319
|
+
if (error.code === "ENOENT")
|
|
320
|
+
return { ledger: emptyLedger(), quarantined: false };
|
|
321
|
+
// EMFILE, EACCES and the like say nothing about the ledger's content: keep it.
|
|
322
|
+
throw new HostCapacityLedgerUnavailableError("the host load ledger could not be read.", { cause: error });
|
|
323
|
+
}
|
|
324
|
+
let parsed;
|
|
325
|
+
try {
|
|
326
|
+
parsed = JSON.parse(content);
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
return await this.quarantine(null);
|
|
330
|
+
}
|
|
331
|
+
const nextFencingToken = Number.isSafeInteger(parsed?.nextFencingToken) ? parsed.nextFencingToken : null;
|
|
332
|
+
// One malformed reservation makes the whole ledger untrustworthy: dropping just
|
|
333
|
+
// that token would turn a possibly running step's cost into free capacity.
|
|
334
|
+
if (parsed?.schemaVersion !== 1 || !Array.isArray(parsed.tokens) || nextFencingToken === null
|
|
335
|
+
|| !parsed.tokens.every(validToken)
|
|
336
|
+
|| !uniqueTokenIds(parsed.tokens)
|
|
337
|
+
|| (parsed.recoveringUntil !== undefined && !Number.isFinite(Date.parse(parsed.recoveringUntil)))) {
|
|
338
|
+
return await this.quarantine(nextFencingToken);
|
|
339
|
+
}
|
|
340
|
+
return {
|
|
341
|
+
ledger: {
|
|
342
|
+
schemaVersion: 1,
|
|
343
|
+
nextFencingToken,
|
|
344
|
+
tokens: parsed.tokens,
|
|
345
|
+
...parsed.recoveringUntil !== undefined ? { recoveringUntil: parsed.recoveringUntil } : {},
|
|
346
|
+
},
|
|
347
|
+
quarantined: false,
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* A corrupt ledger is kept aside for inspection and none of its tokens are
|
|
352
|
+
* trusted. Admissions pause for one lease while live owners, which renew
|
|
353
|
+
* several times per lease, put their running steps' reservations back.
|
|
354
|
+
*/
|
|
355
|
+
async quarantine(nextFencingToken) {
|
|
356
|
+
// A unique name: a second quarantine in the same millisecond must not replace the first copy.
|
|
357
|
+
await fs.rename(this.ledgerPath, `${this.ledgerPath}.corrupt-${this.now()}-${randomUUID()}`).catch(() => undefined);
|
|
358
|
+
return {
|
|
359
|
+
ledger: {
|
|
360
|
+
...emptyLedger(),
|
|
361
|
+
nextFencingToken: Math.max(1, nextFencingToken ?? 1),
|
|
362
|
+
recoveringUntil: new Date(this.now() + this.options.leaseMs).toISOString(),
|
|
363
|
+
},
|
|
364
|
+
quarantined: true,
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
async write(ledger) {
|
|
368
|
+
const temporary = `${this.ledgerPath}.${process.pid}.${randomUUID()}.tmp`;
|
|
369
|
+
try {
|
|
370
|
+
const handle = await fs.open(temporary, "wx", 0o600);
|
|
371
|
+
try {
|
|
372
|
+
await handle.writeFile(`${JSON.stringify(ledger)}\n`);
|
|
373
|
+
await handle.sync();
|
|
374
|
+
}
|
|
375
|
+
finally {
|
|
376
|
+
await handle.close();
|
|
377
|
+
}
|
|
378
|
+
await fs.rename(temporary, this.ledgerPath);
|
|
379
|
+
}
|
|
380
|
+
catch (error) {
|
|
381
|
+
await fs.rm(temporary, { force: true }).catch(() => undefined);
|
|
382
|
+
throw new HostCapacityLedgerUnavailableError("the host load ledger could not be written.", { cause: error });
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
function emptyLedger() {
|
|
387
|
+
return { schemaVersion: 1, nextFencingToken: 1, tokens: [] };
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Each reservation needs its own identity: with a duplicate tokenId the owner's
|
|
391
|
+
* held map would keep one copy, and one release would drop both reservations.
|
|
392
|
+
*/
|
|
393
|
+
function uniqueTokenIds(tokens) {
|
|
394
|
+
return new Set(tokens.map(token => token.tokenId)).size === tokens.length;
|
|
395
|
+
}
|
|
396
|
+
function validOwner(value) {
|
|
397
|
+
const owner = value;
|
|
398
|
+
return Boolean(owner)
|
|
399
|
+
&& Number.isSafeInteger(owner.pid) && owner.pid > 0
|
|
400
|
+
&& typeof owner.processInstanceId === "string"
|
|
401
|
+
&& (owner.processIdentity === null || typeof owner.processIdentity === "string");
|
|
402
|
+
}
|
|
403
|
+
function validToken(value) {
|
|
404
|
+
const token = value;
|
|
405
|
+
return Boolean(token)
|
|
406
|
+
&& typeof token.tokenId === "string"
|
|
407
|
+
&& Number.isSafeInteger(token.fencingToken)
|
|
408
|
+
&& typeof token.stepClass === "string"
|
|
409
|
+
&& typeof token.label === "string"
|
|
410
|
+
&& Number.isFinite(token.cost?.cpuCores) && token.cost.cpuCores >= 0
|
|
411
|
+
&& Number.isFinite(token.cost?.memoryBytes) && token.cost.memoryBytes >= 0
|
|
412
|
+
&& (token.dispatchAttemptId === null || typeof token.dispatchAttemptId === "string")
|
|
413
|
+
&& (token.priority === "foreground" || token.priority === "background")
|
|
414
|
+
&& validOwner(token.owner)
|
|
415
|
+
&& typeof token.admittedAt === "string"
|
|
416
|
+
&& typeof token.expiresAt === "string"
|
|
417
|
+
&& (token.stepProcess === undefined || token.stepProcess === null || validHostLoadStepProcess(token.stepProcess))
|
|
418
|
+
&& (token.suspendedMsAtRenewal === undefined || Number.isFinite(token.suspendedMsAtRenewal))
|
|
419
|
+
&& (token.degradedAt === undefined || token.degradedAt === null || typeof token.degradedAt === "string")
|
|
420
|
+
&& (token.fencedAt === undefined || token.fencedAt === null || typeof token.fencedAt === "string");
|
|
421
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type HostRuntimeRequirements } from "./host-runtime-requirements.js";
|
|
1
2
|
export declare const hostRuntimeContractPath = ".forge/forge.runtime.yml";
|
|
2
3
|
export declare const hostRuntimeTestPostgresAdminEnvironment = "FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING";
|
|
3
4
|
export declare const hostRuntimeLegacyTestPostgresEnvironment = "FORGE_TEST_POSTGRES_CONNECTION_STRING";
|
|
@@ -32,6 +33,8 @@ export interface HostRuntimeContract {
|
|
|
32
33
|
readonly browserProfile: "isolated";
|
|
33
34
|
readonly singletonResources: readonly string[];
|
|
34
35
|
};
|
|
36
|
+
/** Decision 0013 placement requirements; absent or null when the contract declares none. */
|
|
37
|
+
readonly requires?: HostRuntimeRequirements | null;
|
|
35
38
|
}
|
|
36
39
|
export interface LoadedHostRuntimeContract {
|
|
37
40
|
readonly contract: HostRuntimeContract;
|
|
@@ -4,6 +4,7 @@ import path from "node:path";
|
|
|
4
4
|
import { isAlias, parseDocument, visit } from "yaml";
|
|
5
5
|
import { readCanonicalSourceFile } from "./canonical-source-file.js";
|
|
6
6
|
import { isGeneratedOutputDirectoryName } from "./generated-output-reset.js";
|
|
7
|
+
import { parseHostRuntimeRequirements } from "./host-runtime-requirements.js";
|
|
7
8
|
export const hostRuntimeContractPath = ".forge/forge.runtime.yml";
|
|
8
9
|
export const hostRuntimeTestPostgresAdminEnvironment = "FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING";
|
|
9
10
|
export const hostRuntimeLegacyTestPostgresEnvironment = "FORGE_TEST_POSTGRES_CONNECTION_STRING";
|
|
@@ -47,7 +48,7 @@ const ignoredDiscoveryDirectories = new Set([
|
|
|
47
48
|
"vendor",
|
|
48
49
|
"venv",
|
|
49
50
|
]);
|
|
50
|
-
const topLevelKeys = new Set(["schemaVersion", "runtime"]);
|
|
51
|
+
const topLevelKeys = new Set(["schemaVersion", "runtime", "requires", "costHints"]);
|
|
51
52
|
const runtimeKeys = new Set(["hostConcurrency", "ports", "playwright", "browserProfile", "singletonResources"]);
|
|
52
53
|
const portKeys = new Set(["adapter", "launch", "env", "baseUrlEnv", "format"]);
|
|
53
54
|
const launchKeys = new Set(["command", "args", "workingDirectory", "environment"]);
|
|
@@ -549,6 +550,7 @@ export function validateHostRuntimeContract(source) {
|
|
|
549
550
|
throw new Error("runtime_contract_invalid: runtime.browserProfile must be isolated.");
|
|
550
551
|
}
|
|
551
552
|
const ports = parsePorts(runtime.ports);
|
|
553
|
+
const requires = parseHostRuntimeRequirements(root.requires, root.costHints);
|
|
552
554
|
return {
|
|
553
555
|
schemaVersion: 1,
|
|
554
556
|
runtime: {
|
|
@@ -558,6 +560,7 @@ export function validateHostRuntimeContract(source) {
|
|
|
558
560
|
browserProfile,
|
|
559
561
|
singletonResources: parseSingletonResources(runtime.singletonResources),
|
|
560
562
|
},
|
|
563
|
+
...(requires ? { requires } : {}),
|
|
561
564
|
};
|
|
562
565
|
}
|
|
563
566
|
function parsePlaywright(value, ports) {
|