@loucompanion/forge-bridge 0.1.4-dev.bfa11ebe98c6 → 0.1.4-dev.c03d3c89ec4a
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 +45 -3
- package/dist/bridge/bridge.base.d.ts +9 -0
- package/dist/bridge/bridge.service.d.ts +84 -2
- package/dist/bridge/bridge.service.js +358 -12
- package/dist/bridge/bridge.types.d.ts +22 -0
- package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
- package/dist/bridge/dispatch-result-outbox.js +31 -6
- 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 +20 -2
- 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/attempt-database-broker.d.ts +89 -0
- package/dist/runtime/attempt-database-broker.js +390 -0
- package/dist/runtime/attempt-process-supervisor.d.ts +24 -0
- package/dist/runtime/attempt-process-supervisor.js +77 -3
- 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-diagnostics.js +4 -3
- 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 +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 +126 -0
- package/dist/runtime/host-load-sampler.js +232 -0
- 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 +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 +75 -11
- package/dist/runtime/host-runtime-lease.d.ts +76 -4
- package/dist/runtime/host-runtime-lease.js +386 -32
- 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/managed-command-teardown.d.ts +62 -0
- package/dist/runtime/managed-command-teardown.js +607 -0
- package/dist/runtime/node-host-runtime-adapter.js +5 -4
- 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 +18 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
- 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/repository-lock.js +3 -2
- package/dist/sandbox/runtime.d.ts +10 -1
- package/dist/sandbox/runtime.js +50 -6
- 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 +27 -0
- package/dist/session/managed-attempt-tools.js +366 -45
- package/dist/session/managed-build-coordinator.d.ts +1 -1
- package/dist/session/managed-build-coordinator.js +8 -4
- 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 +78 -36
- 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 +206 -221
- 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-pass.d.ts +60 -0
- package/dist/session/pre-publication-pass.js +145 -0
- package/dist/session/pre-publication-process.d.ts +23 -0
- package/dist/session/pre-publication-process.js +109 -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 +30 -20
- package/dist/session/pre-publication-validation.js +178 -193
- package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
- package/dist/session/provider-cli/pre-publication-repair.js +243 -0
- 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 +299 -25
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +7 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +62 -9
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +6 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
- package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
- package/dist/session/provider-cli/provider-cli.service.js +200 -162
- 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/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/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-recovery.js +3 -2
- package/dist/shared/process/host-process-supervisor.d.ts +1 -0
- package/dist/shared/process/host-process-supervisor.js +6 -5
- 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/shared/provider-capabilities.js +5 -6
- package/dist/shared/time/monotonic.d.ts +1 -0
- package/dist/shared/time/monotonic.js +8 -0
- 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 +120 -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
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ProviderProcessHandlers, ProviderProcessRunRequest, ProviderProcessRunner, ProviderProcessRunResult } from "../session/provider-cli/provider-cli.process.js";
|
|
2
|
+
import { type ManagedCommandTeardownOptions, type ManagedCommandTeardownOutcome } from "./managed-command-teardown.js";
|
|
2
3
|
export type AttemptProcessChildStatus = "starting" | "running" | "stopping" | "exited" | "failed";
|
|
3
4
|
export type AttemptProcessSupervisorStatus = "active" | "stopping" | "stopped" | "degraded";
|
|
4
5
|
export interface AttemptProcessSupervisorIdentity {
|
|
@@ -32,6 +33,8 @@ export interface AttemptProcessSupervisorLedger {
|
|
|
32
33
|
readonly status: AttemptProcessSupervisorStatus;
|
|
33
34
|
readonly updatedAt: string;
|
|
34
35
|
readonly children: readonly AttemptProcessChildLedgerEntry[];
|
|
36
|
+
/** A provider-exit managed-command cleanup that failed and was left to attempt teardown. */
|
|
37
|
+
readonly deferredManagedCommandTeardownFailure?: string;
|
|
35
38
|
}
|
|
36
39
|
export interface AttemptProcessChildHandle {
|
|
37
40
|
readonly name: string;
|
|
@@ -46,6 +49,9 @@ export interface AttemptProcessChildHandle {
|
|
|
46
49
|
export interface AttemptProcessSupervisorOptions {
|
|
47
50
|
readonly metadataReadyTimeoutMs?: number;
|
|
48
51
|
readonly signal?: AbortSignal;
|
|
52
|
+
readonly replaceLedgerFile?: (temporaryPath: string, ledgerPath: string) => Promise<void>;
|
|
53
|
+
readonly ledgerReplaceRetryMs?: number;
|
|
54
|
+
readonly managedCommandTeardownGraceMs?: number;
|
|
49
55
|
}
|
|
50
56
|
export interface AttemptProcessChildReadyOptions {
|
|
51
57
|
readonly maxStartAttempts?: number;
|
|
@@ -62,6 +68,9 @@ export declare class AttemptProcessSupervisor {
|
|
|
62
68
|
readonly ledgerPath: string;
|
|
63
69
|
private readonly identity;
|
|
64
70
|
private readonly metadataReadyTimeoutMs;
|
|
71
|
+
private readonly replaceLedgerFile;
|
|
72
|
+
private readonly ledgerReplaceRetryMs;
|
|
73
|
+
private readonly managedCommandTeardownGraceMs;
|
|
65
74
|
private readonly records;
|
|
66
75
|
private readonly currentByName;
|
|
67
76
|
private readonly attemptController;
|
|
@@ -69,6 +78,8 @@ export declare class AttemptProcessSupervisor {
|
|
|
69
78
|
private persistTail;
|
|
70
79
|
private persistenceFailure;
|
|
71
80
|
private stopOperation;
|
|
81
|
+
private managedCommandTeardownTail;
|
|
82
|
+
private deferredManagedCommandTeardownFailure;
|
|
72
83
|
constructor(identity: AttemptProcessSupervisorIdentity, runner: ProviderProcessRunner, options?: AttemptProcessSupervisorOptions);
|
|
73
84
|
startChild(name: string, request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<AttemptProcessChildHandle>;
|
|
74
85
|
/**
|
|
@@ -82,10 +93,23 @@ export declare class AttemptProcessSupervisor {
|
|
|
82
93
|
stopChild(name: string, generation: number, fencingToken: string, reason?: unknown): Promise<ProviderProcessRunResult>;
|
|
83
94
|
stopAll(fencingToken: string, reason?: unknown): Promise<void>;
|
|
84
95
|
private performStopAll;
|
|
96
|
+
/**
|
|
97
|
+
* Stops the managed commands this attempt's MCP servers started and finalizes their
|
|
98
|
+
* receipts. With `onlyOrphaned`, a command whose owning MCP server is still alive is
|
|
99
|
+
* left running: it survives wait slices and MCP call boundaries within a live provider.
|
|
100
|
+
*/
|
|
101
|
+
terminateManagedCommands(options: Omit<ManagedCommandTeardownOptions, "graceMs">): Promise<readonly ManagedCommandTeardownOutcome[]>;
|
|
102
|
+
/**
|
|
103
|
+
* After a provider exits, stops the managed commands its MCP server left behind. It never
|
|
104
|
+
* fails the provider's result: a command it cannot prove stopped is recorded in the ledger
|
|
105
|
+
* and left to attempt teardown, which fails closed.
|
|
106
|
+
*/
|
|
107
|
+
stopOrphanedManagedCommands(): Promise<void>;
|
|
85
108
|
snapshot(): AttemptProcessSupervisorLedger;
|
|
86
109
|
providerMemoryTelemetry(): AttemptProcessTreeMemoryTelemetry | null;
|
|
87
110
|
private observeChildReady;
|
|
88
111
|
private settleChild;
|
|
112
|
+
private replaceLedger;
|
|
89
113
|
private assertFence;
|
|
90
114
|
private persist;
|
|
91
115
|
}
|
|
@@ -2,8 +2,15 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import fs from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { ForgeFailureError, sanitizeFailureError } from "../session/session.types.js";
|
|
5
|
+
import { terminateAttemptManagedCommands, } from "./managed-command-teardown.js";
|
|
6
|
+
import { monotonicNowMs } from "../shared/time/monotonic.js";
|
|
5
7
|
const terminalChildStatuses = new Set(["exited", "failed"]);
|
|
6
8
|
const defaultMetadataReadyTimeoutMs = process.platform === "win32" ? 60_000 : 10_000;
|
|
9
|
+
// Windows refuses to replace a file another process (a scanner or indexer) briefly holds
|
|
10
|
+
// open. One such refusal must not degrade the attempt, so the ledger replace is retried.
|
|
11
|
+
const ledgerReplaceAttempts = 40;
|
|
12
|
+
const defaultLedgerReplaceRetryMs = 25;
|
|
13
|
+
const transientLedgerReplaceCodes = new Set(["EPERM", "EACCES", "EBUSY"]);
|
|
7
14
|
/**
|
|
8
15
|
* Owns the independently supervised process trees that belong to one host
|
|
9
16
|
* dispatch attempt. Each named child gets a distinct Windows Job Object or
|
|
@@ -15,6 +22,9 @@ export class AttemptProcessSupervisor {
|
|
|
15
22
|
ledgerPath;
|
|
16
23
|
identity;
|
|
17
24
|
metadataReadyTimeoutMs;
|
|
25
|
+
replaceLedgerFile;
|
|
26
|
+
ledgerReplaceRetryMs;
|
|
27
|
+
managedCommandTeardownGraceMs;
|
|
18
28
|
records = [];
|
|
19
29
|
currentByName = new Map();
|
|
20
30
|
attemptController = new AbortController();
|
|
@@ -22,10 +32,15 @@ export class AttemptProcessSupervisor {
|
|
|
22
32
|
persistTail = Promise.resolve();
|
|
23
33
|
persistenceFailure;
|
|
24
34
|
stopOperation = null;
|
|
35
|
+
managedCommandTeardownTail = Promise.resolve();
|
|
36
|
+
deferredManagedCommandTeardownFailure;
|
|
25
37
|
constructor(identity, runner, options = {}) {
|
|
26
38
|
this.runner = runner;
|
|
27
39
|
this.identity = validateIdentity(identity);
|
|
28
40
|
this.metadataReadyTimeoutMs = boundedInteger(options.metadataReadyTimeoutMs ?? defaultMetadataReadyTimeoutMs, 100, 120_000, "metadataReadyTimeoutMs");
|
|
41
|
+
this.replaceLedgerFile = options.replaceLedgerFile ?? ((temporaryPath, ledgerPath) => fs.rename(temporaryPath, ledgerPath));
|
|
42
|
+
this.ledgerReplaceRetryMs = options.ledgerReplaceRetryMs ?? defaultLedgerReplaceRetryMs;
|
|
43
|
+
this.managedCommandTeardownGraceMs = options.managedCommandTeardownGraceMs;
|
|
29
44
|
this.ledgerPath = path.join(this.identity.logDirectory, "attempt-process-supervisor.json");
|
|
30
45
|
if (options.signal?.aborted) {
|
|
31
46
|
this.status = "stopping";
|
|
@@ -189,6 +204,14 @@ export class AttemptProcessSupervisor {
|
|
|
189
204
|
const rejected = results.flatMap((result, index) => result.status === "rejected"
|
|
190
205
|
? [sanitizeFailureError(result.reason, active[index].failureRedactionValues)]
|
|
191
206
|
: []);
|
|
207
|
+
// Managed commands run in their own process groups, outside every child tree stopped
|
|
208
|
+
// above. The attempt is not stopped until each of them is proven stopped too.
|
|
209
|
+
try {
|
|
210
|
+
await this.terminateManagedCommands({ reason: "attempt_teardown" });
|
|
211
|
+
}
|
|
212
|
+
catch (error) {
|
|
213
|
+
rejected.push(error instanceof Error ? error : new Error(String(error)));
|
|
214
|
+
}
|
|
192
215
|
const terminalStatus = rejected.length > 0 || this.persistenceFailure !== undefined ? "degraded" : "stopped";
|
|
193
216
|
await this.persist({
|
|
194
217
|
...this.snapshot(),
|
|
@@ -202,6 +225,40 @@ export class AttemptProcessSupervisor {
|
|
|
202
225
|
if (this.persistenceFailure !== undefined)
|
|
203
226
|
throw this.persistenceFailure;
|
|
204
227
|
}
|
|
228
|
+
/**
|
|
229
|
+
* Stops the managed commands this attempt's MCP servers started and finalizes their
|
|
230
|
+
* receipts. With `onlyOrphaned`, a command whose owning MCP server is still alive is
|
|
231
|
+
* left running: it survives wait slices and MCP call boundaries within a live provider.
|
|
232
|
+
*/
|
|
233
|
+
async terminateManagedCommands(options) {
|
|
234
|
+
// One sweep at a time: a provider-exit sweep and attempt teardown would otherwise
|
|
235
|
+
// signal the same groups and write the same receipts concurrently, and stopAll must
|
|
236
|
+
// not report the attempt stopped while an earlier sweep is still writing.
|
|
237
|
+
const sweep = this.managedCommandTeardownTail.then(async () => await terminateAttemptManagedCommands({
|
|
238
|
+
logDirectory: this.identity.logDirectory,
|
|
239
|
+
dispatchAttemptId: this.identity.dispatchAttemptId,
|
|
240
|
+
runtimeLeaseId: this.identity.executionLeaseId,
|
|
241
|
+
}, {
|
|
242
|
+
...options,
|
|
243
|
+
...(this.managedCommandTeardownGraceMs === undefined ? {} : { graceMs: this.managedCommandTeardownGraceMs }),
|
|
244
|
+
}));
|
|
245
|
+
this.managedCommandTeardownTail = sweep.catch(() => undefined);
|
|
246
|
+
return await sweep;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* After a provider exits, stops the managed commands its MCP server left behind. It never
|
|
250
|
+
* fails the provider's result: a command it cannot prove stopped is recorded in the ledger
|
|
251
|
+
* and left to attempt teardown, which fails closed.
|
|
252
|
+
*/
|
|
253
|
+
async stopOrphanedManagedCommands() {
|
|
254
|
+
try {
|
|
255
|
+
await this.terminateManagedCommands({ reason: "owner_exited", onlyOrphaned: true });
|
|
256
|
+
}
|
|
257
|
+
catch (error) {
|
|
258
|
+
this.deferredManagedCommandTeardownFailure = boundedFailure(error, []);
|
|
259
|
+
await this.persist().catch(() => undefined);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
205
262
|
snapshot() {
|
|
206
263
|
return {
|
|
207
264
|
schemaVersion: 1,
|
|
@@ -210,6 +267,9 @@ export class AttemptProcessSupervisor {
|
|
|
210
267
|
executionLeaseId: this.identity.executionLeaseId,
|
|
211
268
|
status: this.status,
|
|
212
269
|
updatedAt: new Date().toISOString(),
|
|
270
|
+
...(this.deferredManagedCommandTeardownFailure
|
|
271
|
+
? { deferredManagedCommandTeardownFailure: this.deferredManagedCommandTeardownFailure }
|
|
272
|
+
: {}),
|
|
213
273
|
children: this.records.map(record => ({
|
|
214
274
|
name: record.name,
|
|
215
275
|
generation: record.generation,
|
|
@@ -248,8 +308,8 @@ export class AttemptProcessSupervisor {
|
|
|
248
308
|
};
|
|
249
309
|
}
|
|
250
310
|
async observeChildReady(record) {
|
|
251
|
-
const deadline =
|
|
252
|
-
while (
|
|
311
|
+
const deadline = monotonicNowMs() + this.metadataReadyTimeoutMs;
|
|
312
|
+
while (monotonicNowMs() <= deadline) {
|
|
253
313
|
if (await fileExists(record.metadataPath)) {
|
|
254
314
|
if (record.status === "starting") {
|
|
255
315
|
record.status = "running";
|
|
@@ -290,6 +350,20 @@ export class AttemptProcessSupervisor {
|
|
|
290
350
|
this.status = "degraded";
|
|
291
351
|
});
|
|
292
352
|
}
|
|
353
|
+
async replaceLedger(temporary) {
|
|
354
|
+
for (let attempt = 1;; attempt += 1) {
|
|
355
|
+
try {
|
|
356
|
+
await this.replaceLedgerFile(temporary, this.ledgerPath);
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
catch (error) {
|
|
360
|
+
const code = error.code;
|
|
361
|
+
if (attempt >= ledgerReplaceAttempts || !code || !transientLedgerReplaceCodes.has(code))
|
|
362
|
+
throw error;
|
|
363
|
+
await wait(this.ledgerReplaceRetryMs);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
}
|
|
293
367
|
assertFence(fencingToken) {
|
|
294
368
|
if (fencingToken !== this.identity.fencingToken) {
|
|
295
369
|
throw new Error("attempt_process_supervisor_fenced: fencing token does not own this attempt.");
|
|
@@ -308,7 +382,7 @@ export class AttemptProcessSupervisor {
|
|
|
308
382
|
finally {
|
|
309
383
|
await handle.close();
|
|
310
384
|
}
|
|
311
|
-
await
|
|
385
|
+
await this.replaceLedger(temporary);
|
|
312
386
|
}
|
|
313
387
|
catch (error) {
|
|
314
388
|
await fs.rm(temporary, { force: true }).catch(() => undefined);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export declare const hostDatabaseCapabilityEnvironmentNames: readonly ["FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING", "FORGE_TEST_POSTGRES_CONNECTION_STRING"];
|
|
1
|
+
export declare const hostDatabaseCapabilityEnvironmentNames: readonly ["FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING", "FORGE_TEST_POSTGRES_CONNECTION_STRING", "FORGE_TEST_POSTGRES_PROVISIONER_CONNECTION_STRING"];
|
|
2
2
|
export interface HostDatabaseCapabilityBoundaryOptions {
|
|
3
3
|
readonly platform?: NodeJS.Platform;
|
|
4
4
|
readonly processEnvironment?: NodeJS.ProcessEnv;
|
|
@@ -3,6 +3,7 @@ import path from "node:path";
|
|
|
3
3
|
export const hostDatabaseCapabilityEnvironmentNames = [
|
|
4
4
|
"FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING",
|
|
5
5
|
"FORGE_TEST_POSTGRES_CONNECTION_STRING",
|
|
6
|
+
"FORGE_TEST_POSTGRES_PROVISIONER_CONNECTION_STRING",
|
|
6
7
|
];
|
|
7
8
|
const boundaryAttestationEnvironment = "FORGE_HOST_DATABASE_CAPABILITY_BOUNDARY";
|
|
8
9
|
const boundaryAttestationValue = "user_store_clear";
|
|
@@ -6,6 +6,7 @@ import { assertCanonicalDirectory } from "./attempt-private-directory.js";
|
|
|
6
6
|
import { runAttemptArchiveOperation, runAttemptPathOperation } from "./attempt-path-operation.js";
|
|
7
7
|
import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
|
|
8
8
|
import { compactHostAttemptId } from "./host-execution-root.js";
|
|
9
|
+
import { monotonicNowMs } from "../shared/time/monotonic.js";
|
|
9
10
|
const maximumEvidenceBytes = 200 * 1024 * 1024;
|
|
10
11
|
const diagnosticsRetentionDeadlineMs = 30_000;
|
|
11
12
|
const diagnosticsHelperTerminationConfirmationMs = 2_000;
|
|
@@ -21,7 +22,7 @@ export async function retainHostDiagnostics(stateRoot, attemptRoot, attemptId, e
|
|
|
21
22
|
const configuredDeadlineMs = Math.max(1, Math.min(diagnosticsRetentionDeadlineMs, Number.isFinite(requestedDeadlineMs) && (requestedDeadlineMs ?? 0) > 0
|
|
22
23
|
? Math.floor(requestedDeadlineMs)
|
|
23
24
|
: diagnosticsRetentionDeadlineMs));
|
|
24
|
-
const retentionDeadline =
|
|
25
|
+
const retentionDeadline = monotonicNowMs() + configuredDeadlineMs;
|
|
25
26
|
const identity = attemptId.replaceAll("-", "").toLowerCase();
|
|
26
27
|
const compactAttemptRoot = path.resolve(attemptOwnerRoot, "a", compactHostAttemptId(attemptId));
|
|
27
28
|
const legacyAttemptRoot = path.resolve(stateRoot, "host-attempts", identity);
|
|
@@ -155,7 +156,7 @@ function remainingHelperTiming(retentionDeadline, configuredDeadlineMs) {
|
|
|
155
156
|
return { operationTimeoutMs, terminationConfirmationMs };
|
|
156
157
|
}
|
|
157
158
|
function remainingRetentionMs(retentionDeadline, configuredDeadlineMs) {
|
|
158
|
-
const remainingMs = retentionDeadline -
|
|
159
|
+
const remainingMs = retentionDeadline - monotonicNowMs();
|
|
159
160
|
if (remainingMs <= 0)
|
|
160
161
|
throw diagnosticsDeadlineError(configuredDeadlineMs);
|
|
161
162
|
return remainingMs;
|
|
@@ -181,7 +182,7 @@ async function runWithinRetentionHelperDeadline(operation, retentionDeadline, co
|
|
|
181
182
|
return await operation();
|
|
182
183
|
}
|
|
183
184
|
catch (error) {
|
|
184
|
-
if (
|
|
185
|
+
if (monotonicNowMs() >= retentionDeadline)
|
|
185
186
|
throw diagnosticsDeadlineError(configuredDeadlineMs);
|
|
186
187
|
throw error;
|
|
187
188
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
/** Static hardware and OS facts a bridge host reports once per process (decision 0013). */
|
|
3
|
+
export interface HostFacts {
|
|
4
|
+
readonly cpuModel: string | null;
|
|
5
|
+
readonly physicalCores: number | null;
|
|
6
|
+
readonly logicalThreads: number;
|
|
7
|
+
readonly totalMemoryBytes: number;
|
|
8
|
+
readonly architecture: string;
|
|
9
|
+
readonly platform: string;
|
|
10
|
+
readonly osName: string | null;
|
|
11
|
+
readonly kernelVersion: string | null;
|
|
12
|
+
readonly psiAvailable: boolean;
|
|
13
|
+
}
|
|
14
|
+
export type HostFileReader = (filePath: string) => Promise<string>;
|
|
15
|
+
export interface HostEnvironment {
|
|
16
|
+
readonly platform: NodeJS.Platform;
|
|
17
|
+
readonly procRoot: string;
|
|
18
|
+
readonly etcRoot: string;
|
|
19
|
+
readonly cgroupRoot: string;
|
|
20
|
+
readonly readFile: HostFileReader;
|
|
21
|
+
readonly cpus: () => readonly Pick<os.CpuInfo, "model">[];
|
|
22
|
+
readonly totalMemoryBytes: () => number;
|
|
23
|
+
readonly freeMemoryBytes: () => number;
|
|
24
|
+
readonly architecture: () => string;
|
|
25
|
+
readonly kernelRelease: () => string;
|
|
26
|
+
readonly osType: () => string;
|
|
27
|
+
readonly osVersion: () => string;
|
|
28
|
+
}
|
|
29
|
+
export declare function defaultHostEnvironment(overrides?: Partial<HostEnvironment>): HostEnvironment;
|
|
30
|
+
export declare function detectHostFacts(environment?: HostEnvironment): Promise<HostFacts>;
|
|
31
|
+
/** PSI is available when the system-wide CPU pressure file exists and parses. */
|
|
32
|
+
export declare function probePsi(environment: HostEnvironment): Promise<boolean>;
|
|
33
|
+
export declare function readOptional(environment: HostEnvironment, filePath: string): Promise<string | null>;
|
|
34
|
+
/** Counts unique (physical id, core id) pairs; null when the topology is not exposed. */
|
|
35
|
+
export declare function physicalCoreCount(cpuinfo: string): number | null;
|
|
@@ -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,60 @@
|
|
|
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
|
+
/** Decision 0014: the host already runs the owner's maximum number of heavy steps. */
|
|
21
|
+
| "heavy_step_limit"
|
|
22
|
+
/** A corrupt ledger was quarantined; admissions wait one lease while owners restore their reservations. */
|
|
23
|
+
| "ledger_recovering";
|
|
24
|
+
export interface HostLoadAdmissionInput {
|
|
25
|
+
readonly request: HostLoadStepCost;
|
|
26
|
+
/** Reserved cost of every live token on this host (all processes). */
|
|
27
|
+
readonly running: readonly HostLoadStepCost[];
|
|
28
|
+
/**
|
|
29
|
+
* Memory the running steps already use. MemAvailable already excludes it, so
|
|
30
|
+
* it is added back to the budget (capped at their reservations) instead of
|
|
31
|
+
* being counted twice.
|
|
32
|
+
*/
|
|
33
|
+
readonly runningMemoryBytes?: number;
|
|
34
|
+
readonly logicalCpus: number;
|
|
35
|
+
readonly signals: HostLoadSignals | null;
|
|
36
|
+
readonly config: Pick<HostLoadGovernorConfig, "cpuBudgetFraction" | "memoryReserveBytes" | "cpuPressureThreshold" | "backpressureSamples" | "memoryFullThreshold" | "fallbackSlots">;
|
|
37
|
+
/**
|
|
38
|
+
* Decision 0014 "Max concurrent heavy steps": a host-wide count limit on top of
|
|
39
|
+
* the budget. Null or absent means the budget alone decides.
|
|
40
|
+
*/
|
|
41
|
+
readonly maxHeavySteps?: number | null;
|
|
42
|
+
}
|
|
43
|
+
export interface HostLoadAdmissionDecision {
|
|
44
|
+
readonly admitted: boolean;
|
|
45
|
+
readonly reason: HostLoadAdmissionReason;
|
|
46
|
+
readonly cpuBudgetCores: number | null;
|
|
47
|
+
readonly memoryBudgetBytes: number | null;
|
|
48
|
+
readonly reservedCpuCores: number;
|
|
49
|
+
readonly reservedMemoryBytes: number;
|
|
50
|
+
readonly detail: string;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Decision 0013 admission rule. A step is admitted when the reserved cost of
|
|
54
|
+
* running steps plus its own cost fits the budget and host pressure is under
|
|
55
|
+
* the backpressure threshold. Memory `full` pressure is a hard stop. A step
|
|
56
|
+
* too large for the budget on its own runs only when nothing else does. An
|
|
57
|
+
* optional count limit (decision 0014) caps how many heavy steps run at once.
|
|
58
|
+
* Without PSI, a simple per-host semaphore applies instead.
|
|
59
|
+
*/
|
|
60
|
+
export declare function decideHostLoadAdmission(input: HostLoadAdmissionInput): HostLoadAdmissionDecision;
|
|
@@ -0,0 +1,99 @@
|
|
|
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. An
|
|
7
|
+
* optional count limit (decision 0014) caps how many heavy steps run at once.
|
|
8
|
+
* Without PSI, a simple per-host semaphore applies instead.
|
|
9
|
+
*/
|
|
10
|
+
export function decideHostLoadAdmission(input) {
|
|
11
|
+
const { request, running, signals, config } = input;
|
|
12
|
+
const reservedCpuCores = running.reduce((sum, cost) => sum + cost.cpuCores, 0);
|
|
13
|
+
const reservedMemoryBytes = running.reduce((sum, cost) => sum + cost.memoryBytes, 0);
|
|
14
|
+
const base = { reservedCpuCores, reservedMemoryBytes };
|
|
15
|
+
const maxHeavySteps = input.maxHeavySteps ?? null;
|
|
16
|
+
if (!signals) {
|
|
17
|
+
// The count limit narrows the semaphore: min(fallback slots, max heavy steps).
|
|
18
|
+
const limited = maxHeavySteps !== null && maxHeavySteps < config.fallbackSlots;
|
|
19
|
+
const slots = limited ? maxHeavySteps : config.fallbackSlots;
|
|
20
|
+
const admitted = running.length < slots;
|
|
21
|
+
return {
|
|
22
|
+
...base,
|
|
23
|
+
admitted,
|
|
24
|
+
reason: admitted ? "admitted_fallback" : limited ? "heavy_step_limit" : "fallback_slots",
|
|
25
|
+
cpuBudgetCores: null,
|
|
26
|
+
memoryBudgetBytes: null,
|
|
27
|
+
detail: admitted
|
|
28
|
+
? "Host pressure data is unavailable; admitted under the per-host step semaphore."
|
|
29
|
+
: limited
|
|
30
|
+
? `Host pressure data is unavailable; ${running.length} of ${slots} heavy step(s) allowed at once are running (max heavy steps).`
|
|
31
|
+
: `Host pressure data is unavailable; ${running.length} of ${config.fallbackSlots} heavy step slot(s) are in use.`,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
const cpuBudgetCores = Math.max(0, input.logicalCpus * config.cpuBudgetFraction - (signals.externalCpuCores ?? 0));
|
|
35
|
+
const usedByRunning = Math.min(reservedMemoryBytes, Math.max(0, input.runningMemoryBytes ?? 0));
|
|
36
|
+
const memoryBudgetBytes = signals.memoryAvailableBytes === null
|
|
37
|
+
? null
|
|
38
|
+
: Math.max(0, signals.memoryAvailableBytes + usedByRunning - config.memoryReserveBytes);
|
|
39
|
+
const budget = { ...base, cpuBudgetCores, memoryBudgetBytes };
|
|
40
|
+
if (signals.memoryFullAvg10 !== null && signals.memoryFullAvg10 > config.memoryFullThreshold) {
|
|
41
|
+
return {
|
|
42
|
+
...budget,
|
|
43
|
+
admitted: false,
|
|
44
|
+
reason: "memory_pressure",
|
|
45
|
+
detail: `Host memory pressure (full avg10 ${signals.memoryFullAvg10}%) is above ${config.memoryFullThreshold}%; no heavy step may start.`,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
if (signals.cpuPressuredSamples >= config.backpressureSamples) {
|
|
49
|
+
return {
|
|
50
|
+
...budget,
|
|
51
|
+
admitted: false,
|
|
52
|
+
reason: "cpu_pressure",
|
|
53
|
+
detail: `Host CPU pressure (some avg10 ${signals.cpuSomeAvg10}%) has been at or above ${config.cpuPressureThreshold}% for ${signals.cpuPressuredSamples} sample(s).`,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
if (maxHeavySteps !== null && running.length >= maxHeavySteps) {
|
|
57
|
+
return {
|
|
58
|
+
...budget,
|
|
59
|
+
admitted: false,
|
|
60
|
+
reason: "heavy_step_limit",
|
|
61
|
+
detail: `${running.length} heavy step(s) are running and the host allows at most ${maxHeavySteps} at once.`,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
if (running.length === 0) {
|
|
65
|
+
const oversize = request.cpuCores > cpuBudgetCores + epsilon
|
|
66
|
+
|| (memoryBudgetBytes !== null && request.memoryBytes > memoryBudgetBytes + epsilon);
|
|
67
|
+
return {
|
|
68
|
+
...budget,
|
|
69
|
+
admitted: true,
|
|
70
|
+
reason: oversize ? "admitted_alone" : "admitted",
|
|
71
|
+
detail: oversize
|
|
72
|
+
? "The step exceeds the host budget on its own and runs alone because nothing else is running."
|
|
73
|
+
: "The step fits the host budget.",
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
if (reservedCpuCores + request.cpuCores > cpuBudgetCores + epsilon) {
|
|
77
|
+
return {
|
|
78
|
+
...budget,
|
|
79
|
+
admitted: false,
|
|
80
|
+
reason: "cpu_budget",
|
|
81
|
+
detail: `Reserved ${round(reservedCpuCores)} + requested ${round(request.cpuCores)} cores exceed the ${round(cpuBudgetCores)}-core budget${signals.externalCpuCores ? ` (${round(signals.externalCpuCores)} cores of external load)` : ""}.`,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
if (memoryBudgetBytes !== null && reservedMemoryBytes + request.memoryBytes > memoryBudgetBytes + epsilon) {
|
|
85
|
+
return {
|
|
86
|
+
...budget,
|
|
87
|
+
admitted: false,
|
|
88
|
+
reason: "memory_budget",
|
|
89
|
+
detail: `Reserved ${gib(reservedMemoryBytes)} + requested ${gib(request.memoryBytes)} GiB exceed the ${gib(memoryBudgetBytes)} GiB memory budget.`,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
return { ...budget, admitted: true, reason: "admitted", detail: "The step fits the host budget." };
|
|
93
|
+
}
|
|
94
|
+
function round(value) {
|
|
95
|
+
return Math.round(value * 100) / 100;
|
|
96
|
+
}
|
|
97
|
+
function gib(bytes) {
|
|
98
|
+
return round(bytes / 1024 ** 3);
|
|
99
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { HostLoadGovernor } from "./host-load-governor.js";
|
|
2
|
+
export declare const hostLoadGovernorEnvironment = "FORGE_HOST_LOAD_GOVERNOR";
|
|
3
|
+
export declare const hostLoadStateRootEnvironment = "FORGE_HOST_LOAD_STATE_ROOT";
|
|
4
|
+
/** True for the variables that carry the governor into a child process. */
|
|
5
|
+
/**
|
|
6
|
+
* A process environment with every host load governor variable removed
|
|
7
|
+
* (FORGE_HOST_LOAD_*, any case). A governed step's own processes must never join
|
|
8
|
+
* the host ledger, or broker control, that their step's token is held in.
|
|
9
|
+
*/
|
|
10
|
+
export declare function withoutHostLoadGovernorVariables<T extends Readonly<Record<string, string | undefined>>>(environment: T): T;
|
|
11
|
+
export declare function isHostLoadChildEnvironmentName(name: string): boolean;
|
|
12
|
+
/**
|
|
13
|
+
* The variables a child needs to share this bridge's ledger: the flag, the
|
|
14
|
+
* state root, the operator's FORGE_HOST_LOAD_* tuning and the bridge's cgroup
|
|
15
|
+
* unit. Empty with the governor off, so the child stays ungoverned.
|
|
16
|
+
*/
|
|
17
|
+
export declare function hostLoadChildEnvironment(stateRoot: string, environment?: Readonly<Record<string, string | undefined>>): Readonly<Record<string, string>>;
|
|
18
|
+
/**
|
|
19
|
+
* The governor a child process uses, from the variables above. Undefined when
|
|
20
|
+
* the flag is off or no state root was handed over: the child is ungoverned.
|
|
21
|
+
*/
|
|
22
|
+
export declare function hostLoadGovernorFromChildEnvironment(environment?: Readonly<Record<string, string | undefined>>): HostLoadGovernor | undefined;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { HostLoadGovernor } from "./host-load-governor.js";
|
|
3
|
+
import { loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
|
|
4
|
+
import { FileForgeCgroupRegistry } from "./host-load-forge-cgroups.js";
|
|
5
|
+
import { HostLoadSampler } from "./host-load-sampler.js";
|
|
6
|
+
// How a process the bridge starts (the completion MCP server, which runs
|
|
7
|
+
// managed commands) joins the bridge's host load governor (decision 0013).
|
|
8
|
+
// The ledger is file-backed, so the child builds its own governor on the
|
|
9
|
+
// bridge's state root and every token counts against one host budget.
|
|
10
|
+
export const hostLoadGovernorEnvironment = "FORGE_HOST_LOAD_GOVERNOR";
|
|
11
|
+
export const hostLoadStateRootEnvironment = "FORGE_HOST_LOAD_STATE_ROOT";
|
|
12
|
+
const cgroupUnitEnvironment = "FORGE_BRIDGE_CGROUP_UNIT";
|
|
13
|
+
/** True for the variables that carry the governor into a child process. */
|
|
14
|
+
/**
|
|
15
|
+
* A process environment with every host load governor variable removed
|
|
16
|
+
* (FORGE_HOST_LOAD_*, any case). A governed step's own processes must never join
|
|
17
|
+
* the host ledger, or broker control, that their step's token is held in.
|
|
18
|
+
*/
|
|
19
|
+
export function withoutHostLoadGovernorVariables(environment) {
|
|
20
|
+
const kept = {};
|
|
21
|
+
for (const [name, value] of Object.entries(environment)) {
|
|
22
|
+
if (!name.toUpperCase().startsWith("FORGE_HOST_LOAD_"))
|
|
23
|
+
kept[name] = value;
|
|
24
|
+
}
|
|
25
|
+
return kept;
|
|
26
|
+
}
|
|
27
|
+
// Decision 0014 operator ceilings the child's governor applies itself (host-load-governor-config.ts).
|
|
28
|
+
const hostCeilingEnvironmentNames = new Set(["FORGE_HOST_CPU_BUDGET_PERCENT", "FORGE_HOST_MAX_HEAVY_STEPS"]);
|
|
29
|
+
export function isHostLoadChildEnvironmentName(name) {
|
|
30
|
+
return name.startsWith("FORGE_HOST_LOAD_") || name === cgroupUnitEnvironment || hostCeilingEnvironmentNames.has(name);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The variables a child needs to share this bridge's ledger: the flag, the
|
|
34
|
+
* state root, the operator's FORGE_HOST_LOAD_* tuning and the bridge's cgroup
|
|
35
|
+
* unit. Empty with the governor off, so the child stays ungoverned.
|
|
36
|
+
*/
|
|
37
|
+
export function hostLoadChildEnvironment(stateRoot, environment = process.env) {
|
|
38
|
+
if (loadHostLoadGovernorConfig(environment).mode !== "on")
|
|
39
|
+
return {};
|
|
40
|
+
const forwarded = {};
|
|
41
|
+
for (const [name, value] of Object.entries(environment)) {
|
|
42
|
+
if (typeof value === "string" && value.trim() && isHostLoadChildEnvironmentName(name))
|
|
43
|
+
forwarded[name] = value;
|
|
44
|
+
}
|
|
45
|
+
forwarded[hostLoadGovernorEnvironment] = "on";
|
|
46
|
+
forwarded[hostLoadStateRootEnvironment] = path.resolve(stateRoot);
|
|
47
|
+
return forwarded;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The governor a child process uses, from the variables above. Undefined when
|
|
51
|
+
* the flag is off or no state root was handed over: the child is ungoverned.
|
|
52
|
+
*/
|
|
53
|
+
export function hostLoadGovernorFromChildEnvironment(environment = process.env) {
|
|
54
|
+
const config = loadHostLoadGovernorConfig(environment);
|
|
55
|
+
const stateRoot = environment[hostLoadStateRootEnvironment]?.trim();
|
|
56
|
+
if (config.mode !== "on" || !stateRoot || !path.isAbsolute(stateRoot))
|
|
57
|
+
return undefined;
|
|
58
|
+
return new HostLoadGovernor({
|
|
59
|
+
stateRoot,
|
|
60
|
+
config,
|
|
61
|
+
load: new HostLoadSampler({
|
|
62
|
+
cgroupUnit: environment[cgroupUnitEnvironment]?.trim() || null,
|
|
63
|
+
// The bridge registers its Docker sandboxes here: their CPU is Forge's own here too.
|
|
64
|
+
forgeCgroups: new FileForgeCgroupRegistry(stateRoot),
|
|
65
|
+
}),
|
|
66
|
+
});
|
|
67
|
+
}
|