@loucompanion/forge-bridge 0.1.4-dev.bbb61d3d6127 → 0.1.4-dev.c1ae24134918
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/dist/bridge/bridge.service.js +10 -4
- package/dist/cli/cli.service.js +1 -1
- package/dist/runtime/host-load-child-environment.d.ts +22 -0
- package/dist/runtime/host-load-child-environment.js +65 -0
- package/dist/runtime/host-load-forge-cgroups.d.ts +41 -0
- package/dist/runtime/host-load-forge-cgroups.js +93 -4
- package/dist/runtime/host-load-governor.d.ts +60 -11
- package/dist/runtime/host-load-governor.js +145 -41
- package/dist/runtime/host-load-sampler.d.ts +5 -0
- package/dist/runtime/host-load-sampler.js +12 -4
- package/dist/runtime/host-load-step-class.d.ts +35 -0
- package/dist/runtime/host-load-step-class.js +60 -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 +58 -19
- package/dist/runtime/host-load-token-ledger.js +111 -35
- package/dist/runtime/host-runtime-lease.d.ts +4 -1
- package/dist/runtime/host-runtime-lease.js +59 -5
- 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.js +120 -24
- package/dist/session/managed-command-host-load.d.ts +45 -0
- package/dist/session/managed-command-host-load.js +82 -0
- package/dist/session/phase-completion.d.ts +2 -0
- package/dist/session/phase-completion.runtime.d.ts +1 -1
- package/dist/session/phase-completion.runtime.js +14 -6
- package/dist/session/pre-publication-host-load.js +31 -16
- package/dist/session/pre-publication-process.d.ts +3 -0
- package/dist/session/pre-publication-process.js +23 -11
- package/dist/session/pre-publication-validation.js +4 -0
- package/dist/session/provider-cli/provider-cli.process.js +2 -2
- package/dist/session/provider-cli/provider-cli.service.js +20 -12
- package/dist/session/provider-cli/provider-cli.types.d.ts +4 -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.service.js +16 -4
- 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 +6 -1
- package/dist/worktree/worktree.service.js +14 -2
- package/dist/worktree/worktree.types.d.ts +7 -0
- package/package.json +1 -1
|
@@ -32,6 +32,9 @@ import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
|
|
|
32
32
|
import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
|
|
33
33
|
import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
|
|
34
34
|
import { HostLoadGovernor } from "./host-load-governor.js";
|
|
35
|
+
import { hostLoadChildEnvironment } from "./host-load-child-environment.js";
|
|
36
|
+
import { aspNetPrebuildStepClass } from "./host-load-step-class.js";
|
|
37
|
+
import { attachSupervisedStepProcess, runHostGovernedStep } from "./host-load-step-run.js";
|
|
35
38
|
import { HostLoadSampler } from "./host-load-sampler.js";
|
|
36
39
|
const hostCapacityWaiterScanLimit = 64;
|
|
37
40
|
const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
|
|
@@ -94,6 +97,9 @@ export class HostRuntimeLeaseManager {
|
|
|
94
97
|
this.capacityConfiguration = loadHostCapacityConfiguration(capacityResourceSample);
|
|
95
98
|
this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
|
|
96
99
|
}
|
|
100
|
+
hostLoadChildEnvironment() {
|
|
101
|
+
return this.hostLoadGovernor.enabled ? hostLoadChildEnvironment(this.stateRoot) : {};
|
|
102
|
+
}
|
|
97
103
|
async reap(options) {
|
|
98
104
|
// Heavy-step tokens whose owner died or whose lease lapsed are returned first.
|
|
99
105
|
await this.hostLoadGovernor.reclaim().catch(() => undefined);
|
|
@@ -221,6 +227,11 @@ export class HostRuntimeLeaseManager {
|
|
|
221
227
|
// drop that met a lingering session) are removed once no live lease holds them.
|
|
222
228
|
// A degraded lease may still own running processes after a restart, so its database is kept.
|
|
223
229
|
await this.databaseBroker?.reapOrphans(id => this.active.has(id) || this.degraded.has(id)).catch(() => undefined);
|
|
230
|
+
// Heavy-step tokens of a dead owner with no recorded process tree (an attempt that
|
|
231
|
+
// ended with a crashed bridge or MCP server) are returned once no live lease holds
|
|
232
|
+
// their attempt; a degraded lease may still own the running step, so its tokens stay.
|
|
233
|
+
await this.hostLoadGovernor.releaseOrphaned(token => !token.dispatchAttemptId
|
|
234
|
+
|| (!this.active.has(token.dispatchAttemptId) && !this.degraded.has(token.dispatchAttemptId))).catch(() => undefined);
|
|
224
235
|
return report;
|
|
225
236
|
}
|
|
226
237
|
snapshot() {
|
|
@@ -1248,7 +1259,29 @@ export class HostRuntimeLeaseManager {
|
|
|
1248
1259
|
message: `Preparing the ASP.NET runtime for commit ${active.inputCommitSha.slice(0, 12)} before binding its assigned port.`,
|
|
1249
1260
|
data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath },
|
|
1250
1261
|
});
|
|
1251
|
-
|
|
1262
|
+
let hostLoadWaitMs = null;
|
|
1263
|
+
const build = await ensureAspNetRuntimePrebuilt(prebuild,
|
|
1264
|
+
// Only a real build (not a verified cache hit) takes a host load token.
|
|
1265
|
+
async (plan, buildSignal) => await runHostGovernedStep(this.hostLoadGovernor, {
|
|
1266
|
+
classification: aspNetPrebuildStepClass,
|
|
1267
|
+
label: prebuild.projectPath,
|
|
1268
|
+
dispatchAttemptId,
|
|
1269
|
+
priority: this.admissions.get(dispatchAttemptId)?.priority ?? "foreground",
|
|
1270
|
+
signal: buildSignal,
|
|
1271
|
+
onWaiting: async (decision) => await onProjectCheckpoint?.({
|
|
1272
|
+
code: "host_runtime_build_waiting_for_host_capacity",
|
|
1273
|
+
message: `The ASP.NET runtime build is waiting for host capacity: ${decision.detail}`,
|
|
1274
|
+
data: { status: "waiting_for_host_capacity", step_class: aspNetPrebuildStepClass.stepClass, reason: decision.reason },
|
|
1275
|
+
}),
|
|
1276
|
+
}, async (waitMs, control) => {
|
|
1277
|
+
hostLoadWaitMs = waitMs;
|
|
1278
|
+
// A reclaimed token stops the build: its capacity is no longer reserved. So does a
|
|
1279
|
+
// build whose process tree cannot be recorded on its token (a reclaim could not stop it).
|
|
1280
|
+
const unrecorded = new AbortController();
|
|
1281
|
+
const stepSignal = anySignal(buildSignal, control.fenced, unrecorded.signal);
|
|
1282
|
+
return await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, stepSignal, capabilitySecrets, async (metadataPath) => await attachSupervisedStepProcess(control, metadataPath)
|
|
1283
|
+
.catch((error) => { unrecorded.abort(error); }));
|
|
1284
|
+
}), signal);
|
|
1252
1285
|
await onProjectCheckpoint?.({
|
|
1253
1286
|
code: build.cacheHit ? "host_runtime_build_cached" : "host_runtime_build_completed",
|
|
1254
1287
|
message: build.cacheHit
|
|
@@ -1258,6 +1291,7 @@ export class HostRuntimeLeaseManager {
|
|
|
1258
1291
|
input_commit_sha: active.inputCommitSha,
|
|
1259
1292
|
build_fingerprint: build.fingerprint,
|
|
1260
1293
|
receipt_path: build.receiptPath,
|
|
1294
|
+
...(hostLoadWaitMs === null ? {} : { host_load_wait_ms: hostLoadWaitMs }),
|
|
1261
1295
|
},
|
|
1262
1296
|
});
|
|
1263
1297
|
}
|
|
@@ -1442,7 +1476,9 @@ export class HostRuntimeLeaseManager {
|
|
|
1442
1476
|
if (!preservePreparation)
|
|
1443
1477
|
this.pendingRenewals.delete(dispatchAttemptId);
|
|
1444
1478
|
if (!active) {
|
|
1445
|
-
|
|
1479
|
+
// Queued steps are cancelled and running ones stopped; each returns its own
|
|
1480
|
+
// token once its processes are gone (never before, or capacity is reused early).
|
|
1481
|
+
this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
|
|
1446
1482
|
this.cancelAdmissionWaiters(dispatchAttemptId, fencingToken, "Managed host admission was released before acquisition.");
|
|
1447
1483
|
this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
|
|
1448
1484
|
this.releaseParallelProjects(dispatchAttemptId, fencingToken);
|
|
@@ -1452,8 +1488,11 @@ export class HostRuntimeLeaseManager {
|
|
|
1452
1488
|
if (active.lease.fencingToken !== fencingToken)
|
|
1453
1489
|
return null;
|
|
1454
1490
|
active.releasing = true;
|
|
1455
|
-
// Attempt teardown
|
|
1456
|
-
|
|
1491
|
+
// Attempt teardown cancels the attempt's queued heavy steps and stops its running
|
|
1492
|
+
// ones. Each running step (an ASP.NET prebuild, an install, a validation step)
|
|
1493
|
+
// returns its own token only after its processes have exited, so the capacity is
|
|
1494
|
+
// not reused while, say, a build is still being terminated.
|
|
1495
|
+
this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
|
|
1457
1496
|
for (const pending of active.pendingAdapterLaunches.values()) {
|
|
1458
1497
|
pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
|
|
1459
1498
|
}
|
|
@@ -1465,6 +1504,15 @@ export class HostRuntimeLeaseManager {
|
|
|
1465
1504
|
try {
|
|
1466
1505
|
if (!active.runtimeResourcesReleased) {
|
|
1467
1506
|
await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
|
|
1507
|
+
// The attempt's MCP servers and process trees are stopped now; tokens they held
|
|
1508
|
+
// belong to dead owners and go back to the host budget at once, including any
|
|
1509
|
+
// without a recorded process tree (their steps were inside the stopped trees).
|
|
1510
|
+
await this.hostLoadGovernor.reclaim().catch(() => undefined);
|
|
1511
|
+
await this.hostLoadGovernor.releaseOrphaned(token => token.dispatchAttemptId === dispatchAttemptId)
|
|
1512
|
+
.catch(() => undefined);
|
|
1513
|
+
// This bridge's own steps whose trees only stopAll could prove gone (a supervised
|
|
1514
|
+
// validation step whose termination failed earlier) return their tokens now.
|
|
1515
|
+
await this.hostLoadGovernor.releaseRetainedAfterTeardown(dispatchAttemptId).catch(() => undefined);
|
|
1468
1516
|
await releaseAdapterResources(active.adapterCleanups);
|
|
1469
1517
|
if (active.databaseCapability && this.databaseBroker) {
|
|
1470
1518
|
// A database the broker cannot drop now is reaped later; it must not hold host capacity.
|
|
@@ -2165,7 +2213,12 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
|
|
|
2165
2213
|
environment.FORGE_BASE_URL = resolvedBaseUrls[0];
|
|
2166
2214
|
return environment;
|
|
2167
2215
|
}
|
|
2168
|
-
|
|
2216
|
+
function anySignal(...signals) {
|
|
2217
|
+
return AbortSignal.any(signals.filter((signal) => signal !== undefined));
|
|
2218
|
+
}
|
|
2219
|
+
async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal, exactSecrets = [],
|
|
2220
|
+
/** Once the build's supervised tree is up: records it on the build's host load token. */
|
|
2221
|
+
onStarted) {
|
|
2169
2222
|
const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
|
|
2170
2223
|
const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
|
|
2171
2224
|
const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
|
|
@@ -2190,6 +2243,7 @@ async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal,
|
|
|
2190
2243
|
await append(stderrLogPath, line);
|
|
2191
2244
|
},
|
|
2192
2245
|
}, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
|
|
2246
|
+
await onStarted?.(child.metadataPath);
|
|
2193
2247
|
const result = await child.result;
|
|
2194
2248
|
return {
|
|
2195
2249
|
exitCode: result.exitCode,
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import type { HostLoadStepGate } from "../runtime/host-load-governor.js";
|
|
2
|
+
import type { HostLoadStepProcess } from "../runtime/host-load-step-reaper.js";
|
|
3
|
+
import type { HostLoadTokenPriority } from "../runtime/host-load-token-ledger.js";
|
|
4
|
+
export declare const sandboxHostCapacityBrokerEnvironment = "FORGE_HOST_LOAD_BROKER";
|
|
5
|
+
export declare const sandboxHostCapacityBrokerProtocol = "stdout-v1";
|
|
6
|
+
export declare const sandboxHostCapacityLineType = "forge_host_capacity";
|
|
7
|
+
export declare const sandboxHostCapacityResponseRoot = "/run/forge/host-capacity";
|
|
8
|
+
/** Owner of authentic replies inside the container: root, via `docker exec --user 0`. */
|
|
9
|
+
export declare const sandboxHostCapacityResponseOwnerUid = 0;
|
|
10
|
+
export declare const sandboxHostCapacityMaxWaitEnvironment = "FORGE_HOST_LOAD_BROKER_MAX_WAIT_MS";
|
|
11
|
+
export interface SandboxHostCapacityRequest {
|
|
12
|
+
readonly action: "acquire" | "release";
|
|
13
|
+
readonly requestId: string;
|
|
14
|
+
readonly stepClass: string;
|
|
15
|
+
readonly label: string;
|
|
16
|
+
}
|
|
17
|
+
export interface SandboxHostCapacityResponse {
|
|
18
|
+
readonly requestId: string;
|
|
19
|
+
/** Rises with every reply the broker sends; the container keeps only the newest. */
|
|
20
|
+
readonly sequence: number;
|
|
21
|
+
readonly status: "waiting" | "admitted" | "failed" | "fenced";
|
|
22
|
+
readonly waitMs?: number;
|
|
23
|
+
readonly reason?: string;
|
|
24
|
+
readonly detail?: string;
|
|
25
|
+
readonly code?: string;
|
|
26
|
+
readonly message?: string;
|
|
27
|
+
}
|
|
28
|
+
export type SandboxHostCapacityDelivery = (response: SandboxHostCapacityResponse) => Promise<void>;
|
|
29
|
+
/** Parses one stdout line; null when it is not a well-formed broker request. */
|
|
30
|
+
export declare function parseSandboxHostCapacityRequest(line: string): SandboxHostCapacityRequest | null;
|
|
31
|
+
export interface SandboxHostCapacityBrokerOptions {
|
|
32
|
+
/** Requests (acquire or release) one sandbox may hold or start at once. */
|
|
33
|
+
readonly maximumOutstanding?: number;
|
|
34
|
+
/** Request lines allowed in a burst, and their sustained rate. */
|
|
35
|
+
readonly burst?: number;
|
|
36
|
+
readonly refillPerSecond?: number;
|
|
37
|
+
/** The sandbox's process tree (its container's init), recorded on each brokered token. */
|
|
38
|
+
readonly stepProcess?: () => Promise<HostLoadStepProcess | null>;
|
|
39
|
+
/** Delay before retrying a failed delivery; doubles up to a few seconds. */
|
|
40
|
+
readonly retryMs?: number;
|
|
41
|
+
readonly now?: () => number;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* One sandbox's brokered tokens. The sandbox never chooses the cost or the
|
|
45
|
+
* attempt. Replies for one request go out one at a time, newest state only,
|
|
46
|
+
* each with a rising sequence the container-side writer uses to refuse an
|
|
47
|
+
* older reply; a failed delivery is retried until a newer state replaces it
|
|
48
|
+
* or the broker closes. A sandbox that floods requests or exceeds its
|
|
49
|
+
* outstanding limit stops the broker and fails its attempt.
|
|
50
|
+
*/
|
|
51
|
+
export declare class SandboxHostCapacityBroker {
|
|
52
|
+
private readonly gate;
|
|
53
|
+
private readonly dispatchAttemptId;
|
|
54
|
+
private readonly priority;
|
|
55
|
+
private readonly deliver;
|
|
56
|
+
private readonly options;
|
|
57
|
+
private readonly tokens;
|
|
58
|
+
private readonly deliveries;
|
|
59
|
+
private readonly work;
|
|
60
|
+
private readonly maximumOutstanding;
|
|
61
|
+
private readonly burst;
|
|
62
|
+
private readonly refillPerSecond;
|
|
63
|
+
private readonly retryMs;
|
|
64
|
+
private readonly now;
|
|
65
|
+
private sequence;
|
|
66
|
+
private allowance;
|
|
67
|
+
private allowanceAtMs;
|
|
68
|
+
private closed;
|
|
69
|
+
private abuse;
|
|
70
|
+
constructor(gate: HostLoadStepGate, dispatchAttemptId: string, priority: HostLoadTokenPriority, deliver: SandboxHostCapacityDelivery, options?: SandboxHostCapacityBrokerOptions);
|
|
71
|
+
/**
|
|
72
|
+
* True when the line was a broker request; such a line is never a runner
|
|
73
|
+
* event. Throws sandbox_host_capacity_abuse once the sandbox breaks its
|
|
74
|
+
* limits: its tokens are returned and the attempt fails with that reason.
|
|
75
|
+
*/
|
|
76
|
+
handleLine(line: string): boolean;
|
|
77
|
+
/** The sandbox exited: cancel its waits and return every token it holds. */
|
|
78
|
+
close(): Promise<void>;
|
|
79
|
+
/** Requests waiting or admitted, for diagnostics and tests. */
|
|
80
|
+
outstanding(): number;
|
|
81
|
+
private stop;
|
|
82
|
+
private takeAllowance;
|
|
83
|
+
private track;
|
|
84
|
+
private acquire;
|
|
85
|
+
private release;
|
|
86
|
+
/** Queues the newest state for a request; at most one delivery per request is in flight. */
|
|
87
|
+
private respond;
|
|
88
|
+
private pump;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Adds the broker variables to a worker `docker create` command, just before
|
|
92
|
+
* its image: the protocol, and the host's maximum queue wait so the
|
|
93
|
+
* container's own fail-safe never fires before the host answers.
|
|
94
|
+
*/
|
|
95
|
+
export declare function withSandboxHostCapacityBroker(createArgs: readonly string[], image: string, maxWaitMs: number): string[];
|
|
96
|
+
/** `docker exec` arguments that write one reply into the container as root. */
|
|
97
|
+
export declare function sandboxHostCapacityDeliveryExecArgs(container: string): string[];
|
|
98
|
+
/**
|
|
99
|
+
* The `node -e` script that writes one response file inside the container, run
|
|
100
|
+
* as root. It keeps the newest reply: one with a lower or equal sequence than
|
|
101
|
+
* the file already holds is dropped, so a late delivery can never replace a
|
|
102
|
+
* newer state. Replies are world-readable but owned by the writer (root, via
|
|
103
|
+
* `docker exec --user 0`). The directory must already be owned by that same uid
|
|
104
|
+
* and writable by no one else, i.e. the root-owned reply mount; it is never
|
|
105
|
+
* created here, where it could turn out to be the sandbox's own directory.
|
|
106
|
+
*/
|
|
107
|
+
export declare const sandboxHostCapacityResponseScript: string;
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { hostLoadStepCostForClass } from "../runtime/host-load-step-class.js";
|
|
2
|
+
import { ForgeFailureError } from "../session/session.types.js";
|
|
3
|
+
// Host side of Docker-sandbox admission (decision 0013). The validator inside a
|
|
4
|
+
// container cannot reach the host ledger, so it asks the bridge over the
|
|
5
|
+
// channels the sandbox already has: a request line on the worker's stdout
|
|
6
|
+
// (which the bridge parses anyway) and a response file the bridge writes with
|
|
7
|
+
// `docker exec`. The bridge's own governor holds the token, renews it, and
|
|
8
|
+
// returns it when the sandbox releases it or exits, so Docker steps share the
|
|
9
|
+
// host budget.
|
|
10
|
+
//
|
|
11
|
+
// Replies are unforgeable from inside the sandbox. They live on their own tmpfs
|
|
12
|
+
// owned by root with mode 0755, mounted only for brokered workers, and are
|
|
13
|
+
// written by `docker exec --user 0`. The workload runs as uid 10001 with every
|
|
14
|
+
// capability dropped and no-new-privileges, so it can neither write there nor
|
|
15
|
+
// create any root-owned file anywhere, and a mount point cannot be renamed
|
|
16
|
+
// away. The validator accepts only a regular, root-owned, single-link reply
|
|
17
|
+
// that no one else can write (sandbox-host-capacity-gate.ts).
|
|
18
|
+
export const sandboxHostCapacityBrokerEnvironment = "FORGE_HOST_LOAD_BROKER";
|
|
19
|
+
export const sandboxHostCapacityBrokerProtocol = "stdout-v1";
|
|
20
|
+
export const sandboxHostCapacityLineType = "forge_host_capacity";
|
|
21
|
+
export const sandboxHostCapacityResponseRoot = "/run/forge/host-capacity";
|
|
22
|
+
/** Owner of authentic replies inside the container: root, via `docker exec --user 0`. */
|
|
23
|
+
export const sandboxHostCapacityResponseOwnerUid = 0;
|
|
24
|
+
export const sandboxHostCapacityMaxWaitEnvironment = "FORGE_HOST_LOAD_BROKER_MAX_WAIT_MS";
|
|
25
|
+
const requestIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
|
|
26
|
+
const stepClassPattern = /^[a-z0-9][a-z0-9._-]{0,63}$/u;
|
|
27
|
+
/** A sandbox validates one step at a time; a small bound stops a runaway from hoarding tokens. */
|
|
28
|
+
const defaultMaximumOutstanding = 2;
|
|
29
|
+
/** A validation run sends two lines per step; this leaves room for reruns and caps docker exec churn. */
|
|
30
|
+
const defaultBurst = 40;
|
|
31
|
+
const defaultRefillPerSecond = 2;
|
|
32
|
+
function codeOf(error) {
|
|
33
|
+
const code = error?.code;
|
|
34
|
+
return typeof code === "string" ? code : null;
|
|
35
|
+
}
|
|
36
|
+
function hasCode(error, code) {
|
|
37
|
+
return codeOf(error) === code;
|
|
38
|
+
}
|
|
39
|
+
/** Parses one stdout line; null when it is not a well-formed broker request. */
|
|
40
|
+
export function parseSandboxHostCapacityRequest(line) {
|
|
41
|
+
const trimmed = line.trim();
|
|
42
|
+
if (!trimmed.startsWith("{") || !trimmed.includes(sandboxHostCapacityLineType) || trimmed.length > 4096)
|
|
43
|
+
return null;
|
|
44
|
+
let value;
|
|
45
|
+
try {
|
|
46
|
+
value = JSON.parse(trimmed);
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
if (!value || value.type !== sandboxHostCapacityLineType || value.version !== 1)
|
|
52
|
+
return null;
|
|
53
|
+
if (value.action !== "acquire" && value.action !== "release")
|
|
54
|
+
return null;
|
|
55
|
+
if (typeof value.requestId !== "string" || !requestIdPattern.test(value.requestId))
|
|
56
|
+
return null;
|
|
57
|
+
const stepClass = typeof value.stepClass === "string" && stepClassPattern.test(value.stepClass) ? value.stepClass : "generic";
|
|
58
|
+
// Diagnostics only, but never control characters or markup from the sandbox.
|
|
59
|
+
const label = typeof value.label === "string" ? value.label.replace(/[^\w .:/@+-]/gu, "_").slice(0, 128) : "";
|
|
60
|
+
return { action: value.action, requestId: value.requestId, stepClass, label };
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* One sandbox's brokered tokens. The sandbox never chooses the cost or the
|
|
64
|
+
* attempt. Replies for one request go out one at a time, newest state only,
|
|
65
|
+
* each with a rising sequence the container-side writer uses to refuse an
|
|
66
|
+
* older reply; a failed delivery is retried until a newer state replaces it
|
|
67
|
+
* or the broker closes. A sandbox that floods requests or exceeds its
|
|
68
|
+
* outstanding limit stops the broker and fails its attempt.
|
|
69
|
+
*/
|
|
70
|
+
export class SandboxHostCapacityBroker {
|
|
71
|
+
gate;
|
|
72
|
+
dispatchAttemptId;
|
|
73
|
+
priority;
|
|
74
|
+
deliver;
|
|
75
|
+
options;
|
|
76
|
+
tokens = new Map();
|
|
77
|
+
deliveries = new Map();
|
|
78
|
+
work = new Set();
|
|
79
|
+
maximumOutstanding;
|
|
80
|
+
burst;
|
|
81
|
+
refillPerSecond;
|
|
82
|
+
retryMs;
|
|
83
|
+
now;
|
|
84
|
+
sequence = 0;
|
|
85
|
+
allowance;
|
|
86
|
+
allowanceAtMs;
|
|
87
|
+
closed = false;
|
|
88
|
+
abuse = null;
|
|
89
|
+
constructor(gate, dispatchAttemptId, priority, deliver, options = {}) {
|
|
90
|
+
this.gate = gate;
|
|
91
|
+
this.dispatchAttemptId = dispatchAttemptId;
|
|
92
|
+
this.priority = priority;
|
|
93
|
+
this.deliver = deliver;
|
|
94
|
+
this.options = options;
|
|
95
|
+
this.maximumOutstanding = options.maximumOutstanding ?? defaultMaximumOutstanding;
|
|
96
|
+
this.burst = options.burst ?? defaultBurst;
|
|
97
|
+
this.refillPerSecond = options.refillPerSecond ?? defaultRefillPerSecond;
|
|
98
|
+
this.retryMs = options.retryMs ?? 250;
|
|
99
|
+
this.now = options.now ?? Date.now;
|
|
100
|
+
this.allowance = this.burst;
|
|
101
|
+
this.allowanceAtMs = this.now();
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* True when the line was a broker request; such a line is never a runner
|
|
105
|
+
* event. Throws sandbox_host_capacity_abuse once the sandbox breaks its
|
|
106
|
+
* limits: its tokens are returned and the attempt fails with that reason.
|
|
107
|
+
*/
|
|
108
|
+
handleLine(line) {
|
|
109
|
+
if (this.abuse)
|
|
110
|
+
throw this.abuse;
|
|
111
|
+
const request = parseSandboxHostCapacityRequest(line);
|
|
112
|
+
if (!request)
|
|
113
|
+
return false;
|
|
114
|
+
if (!this.takeAllowance()) {
|
|
115
|
+
this.stop(`more than ${this.burst} host capacity requests in a burst (sustained limit ${this.refillPerSecond}/s)`);
|
|
116
|
+
}
|
|
117
|
+
if (request.action === "acquire" && !this.tokens.has(request.requestId) && this.tokens.size >= this.maximumOutstanding) {
|
|
118
|
+
this.stop(`more than ${this.maximumOutstanding} host capacity requests outstanding at once`);
|
|
119
|
+
}
|
|
120
|
+
this.track(request.action === "acquire" ? this.acquire(request) : this.release(request.requestId));
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
/** The sandbox exited: cancel its waits and return every token it holds. */
|
|
124
|
+
async close() {
|
|
125
|
+
this.closed = true;
|
|
126
|
+
await Promise.allSettled([...this.tokens.keys()].map(requestId => this.release(requestId)));
|
|
127
|
+
await Promise.allSettled([...this.work]);
|
|
128
|
+
}
|
|
129
|
+
/** Requests waiting or admitted, for diagnostics and tests. */
|
|
130
|
+
outstanding() {
|
|
131
|
+
return this.tokens.size;
|
|
132
|
+
}
|
|
133
|
+
stop(reason) {
|
|
134
|
+
this.abuse = new ForgeFailureError("sandbox_host_capacity_abuse", `sandbox_host_capacity_abuse: the sandbox sent ${reason}; Forge returned its host capacity and stopped the attempt.`, "sandbox");
|
|
135
|
+
void this.close();
|
|
136
|
+
throw this.abuse;
|
|
137
|
+
}
|
|
138
|
+
takeAllowance() {
|
|
139
|
+
const nowMs = this.now();
|
|
140
|
+
this.allowance = Math.min(this.burst, this.allowance + ((nowMs - this.allowanceAtMs) / 1000) * this.refillPerSecond);
|
|
141
|
+
this.allowanceAtMs = nowMs;
|
|
142
|
+
if (this.allowance < 1)
|
|
143
|
+
return false;
|
|
144
|
+
this.allowance -= 1;
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
147
|
+
track(task) {
|
|
148
|
+
const tracked = task.catch(() => undefined);
|
|
149
|
+
this.work.add(tracked);
|
|
150
|
+
void tracked.finally(() => this.work.delete(tracked));
|
|
151
|
+
}
|
|
152
|
+
async acquire(request) {
|
|
153
|
+
if (this.closed || this.tokens.has(request.requestId))
|
|
154
|
+
return;
|
|
155
|
+
const entry = { controller: new AbortController(), admission: null, released: false };
|
|
156
|
+
this.tokens.set(request.requestId, entry);
|
|
157
|
+
let admission;
|
|
158
|
+
try {
|
|
159
|
+
admission = await this.gate.acquire({
|
|
160
|
+
stepClass: request.stepClass,
|
|
161
|
+
label: `sandbox ${request.label || request.stepClass}`,
|
|
162
|
+
// The host decides the cost from the class; the sandbox cannot claim a cheaper one.
|
|
163
|
+
cost: hostLoadStepCostForClass(request.stepClass),
|
|
164
|
+
dispatchAttemptId: this.dispatchAttemptId,
|
|
165
|
+
priority: this.priority,
|
|
166
|
+
}, {
|
|
167
|
+
signal: entry.controller.signal,
|
|
168
|
+
// Sequenced when called, so it can never overtake the admission that follows.
|
|
169
|
+
onWaiting: decision => this.respond({
|
|
170
|
+
requestId: request.requestId, status: "waiting", reason: decision.reason, detail: decision.detail,
|
|
171
|
+
}),
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
catch (error) {
|
|
175
|
+
this.tokens.delete(request.requestId);
|
|
176
|
+
if (entry.released)
|
|
177
|
+
return;
|
|
178
|
+
const failure = error;
|
|
179
|
+
void this.respond({
|
|
180
|
+
requestId: request.requestId,
|
|
181
|
+
status: "failed",
|
|
182
|
+
code: typeof failure.code === "string" ? failure.code : "host_capacity_broker_failed",
|
|
183
|
+
message: typeof failure.message === "string" ? failure.message : String(error),
|
|
184
|
+
...(typeof failure.waitMs === "number" ? { waitMs: Math.round(failure.waitMs) } : {}),
|
|
185
|
+
});
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
if (entry.released) {
|
|
189
|
+
await admission.release().catch(() => undefined);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
entry.admission = admission;
|
|
193
|
+
// A reclaim after a bridge crash then stops the sandbox before reusing its capacity.
|
|
194
|
+
// Without a known process (lookup failed) the token has no tree and, on a crash,
|
|
195
|
+
// stays degraded with its cost; a failed recording is terminal, not ignored.
|
|
196
|
+
let attachFailure = null;
|
|
197
|
+
if (!admission.fenced.aborted) {
|
|
198
|
+
const stepProcess = await this.options.stepProcess?.().catch(() => null);
|
|
199
|
+
if (stepProcess)
|
|
200
|
+
attachFailure = await admission.attachProcess(stepProcess).then(() => null, (error) => error);
|
|
201
|
+
}
|
|
202
|
+
if (entry.released)
|
|
203
|
+
return;
|
|
204
|
+
if (admission.fenced.aborted || attachFailure !== null) {
|
|
205
|
+
// Lost before the sandbox was told it may start: it never runs this step, so
|
|
206
|
+
// it gets a terminal answer instead of "admitted", and the token goes back now.
|
|
207
|
+
const reason = admission.fenced.aborted ? admission.fenced.reason : attachFailure;
|
|
208
|
+
const fenced = admission.fenced.aborted || hasCode(reason, "host_capacity_token_fenced");
|
|
209
|
+
entry.released = true;
|
|
210
|
+
this.tokens.delete(request.requestId);
|
|
211
|
+
void this.respond({
|
|
212
|
+
requestId: request.requestId,
|
|
213
|
+
status: fenced ? "fenced" : "failed",
|
|
214
|
+
code: fenced ? "host_capacity_token_fenced" : codeOf(reason) ?? "host_capacity_broker_failed",
|
|
215
|
+
message: reason instanceof Error ? reason.message : String(reason),
|
|
216
|
+
});
|
|
217
|
+
await admission.release().catch(() => undefined);
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
// Registered synchronously after the check above, so no fence can slip between them.
|
|
221
|
+
admission.fenced.addEventListener("abort", () => {
|
|
222
|
+
void this.respond({
|
|
223
|
+
requestId: request.requestId,
|
|
224
|
+
status: "fenced",
|
|
225
|
+
code: "host_capacity_token_fenced",
|
|
226
|
+
message: admission.fenced.reason instanceof Error ? admission.fenced.reason.message : "host_capacity_token_fenced",
|
|
227
|
+
});
|
|
228
|
+
}, { once: true });
|
|
229
|
+
void this.respond({
|
|
230
|
+
requestId: request.requestId, status: "admitted", waitMs: Math.round(admission.waitMs), reason: admission.decision.reason,
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
async release(requestId) {
|
|
234
|
+
const entry = this.tokens.get(requestId);
|
|
235
|
+
if (!entry || entry.released)
|
|
236
|
+
return;
|
|
237
|
+
entry.released = true;
|
|
238
|
+
this.tokens.delete(requestId);
|
|
239
|
+
this.deliveries.delete(requestId);
|
|
240
|
+
entry.controller.abort(new Error("The sandbox released its host capacity request."));
|
|
241
|
+
await entry.admission?.release().catch(() => undefined);
|
|
242
|
+
}
|
|
243
|
+
/** Queues the newest state for a request; at most one delivery per request is in flight. */
|
|
244
|
+
respond(response) {
|
|
245
|
+
// A container that already exited cannot read the answer; the token is released on close.
|
|
246
|
+
if (this.closed)
|
|
247
|
+
return Promise.resolve();
|
|
248
|
+
this.sequence += 1;
|
|
249
|
+
const state = this.deliveries.get(response.requestId) ?? { latest: null, delivering: false };
|
|
250
|
+
this.deliveries.set(response.requestId, state);
|
|
251
|
+
state.latest = { ...response, sequence: this.sequence };
|
|
252
|
+
if (state.delivering)
|
|
253
|
+
return Promise.resolve();
|
|
254
|
+
state.delivering = true;
|
|
255
|
+
const pump = this.pump(response.requestId, state);
|
|
256
|
+
this.track(pump);
|
|
257
|
+
return pump;
|
|
258
|
+
}
|
|
259
|
+
async pump(requestId, state) {
|
|
260
|
+
// The reply chain for one request; ends when its newest state landed or the broker closed.
|
|
261
|
+
let delayMs = this.retryMs;
|
|
262
|
+
try {
|
|
263
|
+
while (state.latest && !this.closed) {
|
|
264
|
+
const next = state.latest;
|
|
265
|
+
try {
|
|
266
|
+
await this.deliver(next);
|
|
267
|
+
if (state.latest === next)
|
|
268
|
+
state.latest = null;
|
|
269
|
+
delayMs = this.retryMs;
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
// Redeliver the newest state (this one, unless a newer one arrived meanwhile).
|
|
273
|
+
await new Promise(resolve => setTimeout(resolve, delayMs));
|
|
274
|
+
delayMs = Math.min(delayMs * 2, 4_000);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
finally {
|
|
279
|
+
state.delivering = false;
|
|
280
|
+
if (!this.tokens.has(requestId) && this.deliveries.get(requestId) === state)
|
|
281
|
+
this.deliveries.delete(requestId);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Adds the broker variables to a worker `docker create` command, just before
|
|
287
|
+
* its image: the protocol, and the host's maximum queue wait so the
|
|
288
|
+
* container's own fail-safe never fires before the host answers.
|
|
289
|
+
*/
|
|
290
|
+
export function withSandboxHostCapacityBroker(createArgs, image, maxWaitMs) {
|
|
291
|
+
const imageIndex = createArgs.lastIndexOf(image);
|
|
292
|
+
if (imageIndex < 0)
|
|
293
|
+
throw new Error("sandbox_host_capacity_broker_invalid: the worker image is missing from its create command.");
|
|
294
|
+
const args = [...createArgs];
|
|
295
|
+
args.splice(imageIndex, 0,
|
|
296
|
+
// Root-owned and not writable by the sandbox user: only the bridge's replies land here.
|
|
297
|
+
"--tmpfs", `${sandboxHostCapacityResponseRoot}:rw,nosuid,nodev,noexec,size=4m,uid=0,gid=0,mode=0755`, "--env", `${sandboxHostCapacityBrokerEnvironment}=${sandboxHostCapacityBrokerProtocol}`, "--env", `${sandboxHostCapacityMaxWaitEnvironment}=${Math.round(maxWaitMs)}`);
|
|
298
|
+
return args;
|
|
299
|
+
}
|
|
300
|
+
/** `docker exec` arguments that write one reply into the container as root. */
|
|
301
|
+
export function sandboxHostCapacityDeliveryExecArgs(container) {
|
|
302
|
+
return ["exec", "--interactive", "--user", "0", container, "node", "-e", sandboxHostCapacityResponseScript];
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* The `node -e` script that writes one response file inside the container, run
|
|
306
|
+
* as root. It keeps the newest reply: one with a lower or equal sequence than
|
|
307
|
+
* the file already holds is dropped, so a late delivery can never replace a
|
|
308
|
+
* newer state. Replies are world-readable but owned by the writer (root, via
|
|
309
|
+
* `docker exec --user 0`). The directory must already be owned by that same uid
|
|
310
|
+
* and writable by no one else, i.e. the root-owned reply mount; it is never
|
|
311
|
+
* created here, where it could turn out to be the sandbox's own directory.
|
|
312
|
+
*/
|
|
313
|
+
export const sandboxHostCapacityResponseScript = "let s='';process.stdin.setEncoding('utf8');process.stdin.on('data',c=>s+=c);process.stdin.on('end',()=>{const f=require('fs'),r=JSON.parse(s),d='"
|
|
314
|
+
+ sandboxHostCapacityResponseRoot
|
|
315
|
+
+ "';if(!/^[0-9a-f-]{36}$/.test(r.requestId)||!Number.isSafeInteger(r.sequence))process.exit(2);const st=f.lstatSync(d);if(!st.isDirectory()||st.uid!==process.getuid()||(st.mode&0o022))process.exit(3);const p=d+'/'+r.requestId+'.json',t=p+'.'+process.pid+'.tmp';let o=-1;try{o=JSON.parse(f.readFileSync(p,'utf8')).sequence}catch{}if(Number.isSafeInteger(o)&&o>=r.sequence)return;f.writeFileSync(t,s,{mode:0o644,flag:'wx'});f.renameSync(t,p)})";
|
|
@@ -2,6 +2,7 @@ import type { BridgeServiceConfig } from "../bridge/bridge.types.js";
|
|
|
2
2
|
import type { SessionEventSink } from "../session/session.base.js";
|
|
3
3
|
import { type RunOnceDispatchPacket, type RunOnceResultPacket } from "../session/session.types.js";
|
|
4
4
|
import type { SandboxService, ValidatedSandboxContract } from "./sandbox.types.js";
|
|
5
|
+
import type { HostLoadStepGate } from "../runtime/host-load-governor.js";
|
|
5
6
|
import { type RuntimeIsolationLease } from "../runtime/runtime-isolation-lease.js";
|
|
6
7
|
export interface SandboxRuntime {
|
|
7
8
|
runOnce(dispatch: RunOnceDispatchPacket, sink: SessionEventSink, signal?: AbortSignal): Promise<RunOnceResultPacket>;
|
|
@@ -87,12 +88,18 @@ export type SandboxPublicationGrantRedeemer = (request: SandboxPublicationGrantR
|
|
|
87
88
|
export declare class DockerSandboxRuntime implements SandboxRuntime {
|
|
88
89
|
private readonly config;
|
|
89
90
|
private readonly publicationGrantRedeemer?;
|
|
91
|
+
/** The host load governor; with it on, the sandbox's validation steps are brokered through it (decision 0013). */
|
|
92
|
+
private readonly hostLoadGate?;
|
|
90
93
|
private readonly active;
|
|
91
94
|
private readonly degraded;
|
|
92
95
|
private readonly builds;
|
|
93
96
|
private readonly verifiedCatalogImages;
|
|
94
97
|
private buildTail;
|
|
95
|
-
|
|
98
|
+
/** Shared with every sampler on the state root, so sandbox CPU is never external load. */
|
|
99
|
+
private readonly forgeCgroups;
|
|
100
|
+
constructor(config: BridgeServiceConfig, publicationGrantRedeemer?: SandboxPublicationGrantRedeemer | undefined,
|
|
101
|
+
/** The host load governor; with it on, the sandbox's validation steps are brokered through it (decision 0013). */
|
|
102
|
+
hostLoadGate?: HostLoadStepGate | undefined);
|
|
96
103
|
runOnce(dispatch: RunOnceDispatchPacket, sink: SessionEventSink, signal?: AbortSignal): Promise<RunOnceResultPacket>;
|
|
97
104
|
updateLease(dispatchAttemptId: string, fencingToken: string, expiresAt: string): Promise<void>;
|
|
98
105
|
private pushLeaseUpdate;
|
|
@@ -133,6 +140,8 @@ export declare class DockerSandboxRuntime implements SandboxRuntime {
|
|
|
133
140
|
private inspectImageMetadata;
|
|
134
141
|
private startPeakMemorySampler;
|
|
135
142
|
private docker;
|
|
143
|
+
/** The container's init process: stopping it stops every process in the sandbox. */
|
|
144
|
+
private containerInitProcess;
|
|
136
145
|
private dockerArgs;
|
|
137
146
|
}
|
|
138
147
|
export declare function managedBranchUpdateExpectedValue(current: string, expectedInput: string, imported: string): string;
|