@loucompanion/forge-bridge 0.1.4-dev.9e8a5b93cbcb → 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 +84 -2
- package/dist/bridge/bridge.service.js +357 -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 +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/attempt-process-supervisor.d.ts +19 -0
- package/dist/runtime/attempt-process-supervisor.js +50 -0
- package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
- package/dist/runtime/host-database-capability-boundary.js +1 -0
- package/dist/runtime/host-facts.d.ts +35 -0
- package/dist/runtime/host-facts.js +95 -0
- package/dist/runtime/host-load-admission.d.ts +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 +6 -1
- package/dist/runtime/host-runtime-lease.d.ts +74 -4
- package/dist/runtime/host-runtime-lease.js +336 -20
- 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/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/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 +27 -0
- package/dist/session/managed-attempt-tools.js +356 -40
- package/dist/session/managed-build-coordinator.d.ts +1 -1
- package/dist/session/managed-build-coordinator.js +4 -1
- 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 +70 -35
- 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 +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 +9 -9
- package/dist/session/pre-publication-validation.js +48 -112
- package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
- package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
- package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +35 -1
- package/dist/session/provider-cli/provider-cli.process.js +189 -19
- 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 +244 -36
- 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,214 @@
|
|
|
1
|
+
import { parseHostLoadGovernorMode } from "./host-load-governor-config.js";
|
|
2
|
+
// Decision 0014 §3 "Precedence" and §6 "Bridge hub": the server pushes a runner
|
|
3
|
+
// settings document (`ApplySettings`) and is the source of truth. Host env vars
|
|
4
|
+
// are one-sided safety bounds only: a ceiling on capacity, a floor on reserves.
|
|
5
|
+
// The bridge reports the effective values, their sources and every env bound it
|
|
6
|
+
// saw back to the server (`SettingsApplied`), so a host bound is never silent.
|
|
7
|
+
// Nothing here is persisted to bridge.json (0014 agent constraint).
|
|
8
|
+
export const runnerSettingKeys = [
|
|
9
|
+
"maxConcurrentAttempts",
|
|
10
|
+
"cpuBudgetPercent",
|
|
11
|
+
"yieldCpuBudgetPercent",
|
|
12
|
+
"memoryReserveBytes",
|
|
13
|
+
"maxHeavySteps",
|
|
14
|
+
"yieldToForeground",
|
|
15
|
+
];
|
|
16
|
+
export const defaultCpuBudgetPercent = 80;
|
|
17
|
+
export const defaultYieldCpuBudgetPercent = 50;
|
|
18
|
+
const MiB = 1024 ** 2;
|
|
19
|
+
const GiB = 1024 ** 3;
|
|
20
|
+
/** The server's ranges (contract); a value outside them is rejected, not clamped, so it is never silent. */
|
|
21
|
+
const serverRanges = {
|
|
22
|
+
maxConcurrentAttempts: { min: 1, max: 32 },
|
|
23
|
+
cpuBudgetPercent: { min: 10, max: 100 },
|
|
24
|
+
yieldCpuBudgetPercent: { min: 10, max: 100 },
|
|
25
|
+
memoryReserveBytes: { min: 512 * MiB, max: 128 * GiB },
|
|
26
|
+
maxHeavySteps: { min: 1, max: 64 },
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Computes every effective value (decision 0014 precedence):
|
|
30
|
+
* - ceiling keys: server != null ? min(server, ceiling ?? +inf) : (ceiling ?? default);
|
|
31
|
+
* - memory reserve (floor): server != null ? max(server, floor ?? 0) : (floor ?? adaptive default);
|
|
32
|
+
* - yield: server OR the local `forge-bridge yield on` flag.
|
|
33
|
+
* With no document at all (and the local flag off) the values equal today's env/default behaviour.
|
|
34
|
+
*/
|
|
35
|
+
export function computeEffectiveRunnerSettings(document, environment, hostDefaults, localYield) {
|
|
36
|
+
const rejected = [];
|
|
37
|
+
const server = (key) => {
|
|
38
|
+
const value = document?.[key] ?? null;
|
|
39
|
+
if (value === null)
|
|
40
|
+
return null;
|
|
41
|
+
const range = serverRanges[key];
|
|
42
|
+
if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value)) {
|
|
43
|
+
rejected.push({ key, reason: `${String(value)} is not a whole number; the host default applies.`, kind: "invalid" });
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
if (value < range.min || value > range.max) {
|
|
47
|
+
rejected.push({ key, reason: `${value} is outside ${range.min}-${range.max}; the host default applies.`, kind: "invalid" });
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
return value;
|
|
51
|
+
};
|
|
52
|
+
const attemptsCeiling = integerEnv(environment, "FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", 1, 32);
|
|
53
|
+
const cpuCeilings = cpuBudgetCeilings(environment);
|
|
54
|
+
const reserveFloor = integerEnv(environment, "FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * MiB, 128 * GiB);
|
|
55
|
+
const heavyStepsCeiling = integerEnv(environment, "FORGE_HOST_MAX_HEAVY_STEPS", 1, 64);
|
|
56
|
+
const attempts = ceilingValue(server("maxConcurrentAttempts"), lowest(attemptsCeiling), hostDefaults.maxConcurrentAttempts);
|
|
57
|
+
const cpu = ceilingValue(server("cpuBudgetPercent"), lowest(...cpuCeilings), defaultCpuBudgetPercent);
|
|
58
|
+
// The yield budget's ceilings are the CPU budget's. Without a server value they
|
|
59
|
+
// cap its default rather than replace it: a host allowing 90% CPU must not raise
|
|
60
|
+
// the 50% yield default, which no env var sets today.
|
|
61
|
+
const serverYieldCpu = server("yieldCpuBudgetPercent");
|
|
62
|
+
const yieldCpu = ceilingValue(serverYieldCpu ?? defaultYieldCpuBudgetPercent, lowest(...cpuCeilings), defaultYieldCpuBudgetPercent);
|
|
63
|
+
const yieldCpuSource = serverYieldCpu === null && yieldCpu.source === "server" ? "default" : yieldCpu.source;
|
|
64
|
+
const reserve = floorValue(server("memoryReserveBytes"), reserveFloor?.value ?? null, hostDefaults.memoryReserveBytes);
|
|
65
|
+
const heavySteps = ceilingValue(server("maxHeavySteps"), lowest(heavyStepsCeiling), null);
|
|
66
|
+
const serverYield = document?.yieldToForeground === true;
|
|
67
|
+
const yielding = serverYield || localYield;
|
|
68
|
+
// The host's own switch wins the label: turning the server toggle off would not stop it.
|
|
69
|
+
const yieldSource = localYield ? "host_local" : serverYield ? "server" : "default";
|
|
70
|
+
const bounds = [];
|
|
71
|
+
const addCeilings = (key, set) => {
|
|
72
|
+
for (const bound of set)
|
|
73
|
+
if (bound)
|
|
74
|
+
bounds.push({ key, envVar: bound.envVar, value: bound.value, kind: "ceiling" });
|
|
75
|
+
};
|
|
76
|
+
addCeilings("maxConcurrentAttempts", [attemptsCeiling]);
|
|
77
|
+
addCeilings("cpuBudgetPercent", cpuCeilings);
|
|
78
|
+
addCeilings("yieldCpuBudgetPercent", cpuCeilings);
|
|
79
|
+
if (reserveFloor)
|
|
80
|
+
bounds.push({ key: "memoryReserveBytes", envVar: reserveFloor.envVar, value: reserveFloor.value, kind: "floor" });
|
|
81
|
+
addCeilings("maxHeavySteps", [heavyStepsCeiling]);
|
|
82
|
+
const values = {
|
|
83
|
+
maxConcurrentAttempts: attempts.value,
|
|
84
|
+
cpuBudgetPercent: cpu.value,
|
|
85
|
+
yieldCpuBudgetPercent: yieldCpu.value,
|
|
86
|
+
memoryReserveBytes: reserve.value,
|
|
87
|
+
maxHeavySteps: heavySteps.value,
|
|
88
|
+
yieldToForeground: yielding,
|
|
89
|
+
};
|
|
90
|
+
const budgetPercent = yielding ? Math.min(values.yieldCpuBudgetPercent, values.cpuBudgetPercent) : values.cpuBudgetPercent;
|
|
91
|
+
return {
|
|
92
|
+
report: {
|
|
93
|
+
version: null,
|
|
94
|
+
governor: parseHostLoadGovernorMode(environment.FORGE_HOST_LOAD_GOVERNOR),
|
|
95
|
+
values,
|
|
96
|
+
sources: {
|
|
97
|
+
maxConcurrentAttempts: attempts.source,
|
|
98
|
+
cpuBudgetPercent: cpu.source,
|
|
99
|
+
yieldCpuBudgetPercent: yieldCpuSource,
|
|
100
|
+
memoryReserveBytes: reserve.source,
|
|
101
|
+
maxHeavySteps: heavySteps.source,
|
|
102
|
+
yieldToForeground: yieldSource,
|
|
103
|
+
},
|
|
104
|
+
bounds,
|
|
105
|
+
rejected,
|
|
106
|
+
},
|
|
107
|
+
yielding,
|
|
108
|
+
governorCpuBudgetFraction: budgetPercent / 100,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Parses the `ApplySettings` argument. Returns null when it has no usable version
|
|
113
|
+
* (the bridge then ignores it); malformed values become null so the host default applies.
|
|
114
|
+
*/
|
|
115
|
+
export function parseRunnerSettingsDocument(raw) {
|
|
116
|
+
if (!raw || typeof raw !== "object")
|
|
117
|
+
return null;
|
|
118
|
+
const record = raw;
|
|
119
|
+
const version = record.version;
|
|
120
|
+
if (typeof version !== "number" || !Number.isSafeInteger(version) || version < 0)
|
|
121
|
+
return null;
|
|
122
|
+
const numeric = (key) => {
|
|
123
|
+
const value = record[key];
|
|
124
|
+
// Kept as-is (even out of range) so computeEffectiveRunnerSettings can report it as rejected.
|
|
125
|
+
return typeof value === "number" ? value : null;
|
|
126
|
+
};
|
|
127
|
+
return {
|
|
128
|
+
runnerId: typeof record.runnerId === "string" ? record.runnerId : null,
|
|
129
|
+
version,
|
|
130
|
+
maxConcurrentAttempts: numeric("maxConcurrentAttempts"),
|
|
131
|
+
cpuBudgetPercent: numeric("cpuBudgetPercent"),
|
|
132
|
+
yieldCpuBudgetPercent: numeric("yieldCpuBudgetPercent"),
|
|
133
|
+
memoryReserveBytes: numeric("memoryReserveBytes"),
|
|
134
|
+
maxHeavySteps: numeric("maxHeavySteps"),
|
|
135
|
+
yieldToForeground: record.yieldToForeground === true,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* The report for what is actually in force after an apply in which the host
|
|
140
|
+
* failed to put some keys in force: each failed key keeps the value (and source)
|
|
141
|
+
* that was in force before, and its failure is reported as an `apply_failed`
|
|
142
|
+
* rejection, so the server never reads a desired value as applied.
|
|
143
|
+
*/
|
|
144
|
+
export function runnerSettingsInForce(report, previous, failures) {
|
|
145
|
+
if (failures.length === 0)
|
|
146
|
+
return report;
|
|
147
|
+
const values = { ...report.values };
|
|
148
|
+
const sources = { ...report.sources };
|
|
149
|
+
for (const failure of failures) {
|
|
150
|
+
keepPrevious(values, previous.values, failure.key);
|
|
151
|
+
sources[failure.key] = previous.sources[failure.key];
|
|
152
|
+
}
|
|
153
|
+
return { ...report, values, sources, rejected: [...report.rejected, ...failures] };
|
|
154
|
+
}
|
|
155
|
+
function keepPrevious(target, previous, key) {
|
|
156
|
+
target[key] = previous[key];
|
|
157
|
+
}
|
|
158
|
+
/** True when two reports say the same thing (version included), so an unchanged recompute is not re-sent. */
|
|
159
|
+
export function sameRunnerSettingsReport(left, right) {
|
|
160
|
+
return JSON.stringify(left) === JSON.stringify(right);
|
|
161
|
+
}
|
|
162
|
+
function ceilingValue(server, ceiling, fallback) {
|
|
163
|
+
if (server !== null) {
|
|
164
|
+
return ceiling && ceiling.value < server
|
|
165
|
+
? { value: ceiling.value, source: "host_env" }
|
|
166
|
+
: { value: server, source: "server" };
|
|
167
|
+
}
|
|
168
|
+
return ceiling ? { value: ceiling.value, source: "host_env" } : { value: fallback, source: "default" };
|
|
169
|
+
}
|
|
170
|
+
function floorValue(server, floor, fallback) {
|
|
171
|
+
if (server !== null) {
|
|
172
|
+
return floor !== null && floor > server
|
|
173
|
+
? { value: floor, source: "host_env" }
|
|
174
|
+
: { value: server, source: "server" };
|
|
175
|
+
}
|
|
176
|
+
return floor !== null ? { value: floor, source: "host_env" } : { value: fallback, source: "default" };
|
|
177
|
+
}
|
|
178
|
+
function lowest(...bounds) {
|
|
179
|
+
let result = null;
|
|
180
|
+
for (const bound of bounds) {
|
|
181
|
+
if (bound && (result === null || bound.value < result.value))
|
|
182
|
+
result = bound;
|
|
183
|
+
}
|
|
184
|
+
return result;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Both CPU ceilings: the new FORGE_HOST_CPU_BUDGET_PERCENT (10–100) and the
|
|
188
|
+
* existing FORGE_HOST_LOAD_CPU_BUDGET_FRACTION (0.05–1, the governor's own
|
|
189
|
+
* parse), reported as a percent.
|
|
190
|
+
*/
|
|
191
|
+
function cpuBudgetCeilings(environment) {
|
|
192
|
+
const percent = numberEnv(environment, "FORGE_HOST_CPU_BUDGET_PERCENT", 10, 100);
|
|
193
|
+
const fraction = numberEnv(environment, "FORGE_HOST_LOAD_CPU_BUDGET_FRACTION", 0.05, 1);
|
|
194
|
+
return [
|
|
195
|
+
percent,
|
|
196
|
+
fraction ? { envVar: fraction.envVar, value: Math.round(fraction.value * 10_000) / 100 } : null,
|
|
197
|
+
];
|
|
198
|
+
}
|
|
199
|
+
/** Matches the lease manager's parse (parseInt, clamped); an unparsable value counts as unset. */
|
|
200
|
+
function integerEnv(environment, envVar, minimum, maximum) {
|
|
201
|
+
const raw = environment[envVar];
|
|
202
|
+
if (raw === undefined || raw.trim() === "")
|
|
203
|
+
return null;
|
|
204
|
+
const parsed = Number.parseInt(raw, 10);
|
|
205
|
+
return Number.isFinite(parsed) ? { envVar, value: Math.max(minimum, Math.min(maximum, parsed)) } : null;
|
|
206
|
+
}
|
|
207
|
+
/** Matches the governor config's parse (Number, clamped); an unparsable value counts as unset. */
|
|
208
|
+
function numberEnv(environment, envVar, minimum, maximum) {
|
|
209
|
+
const raw = environment[envVar];
|
|
210
|
+
if (raw === undefined || raw.trim() === "")
|
|
211
|
+
return null;
|
|
212
|
+
const parsed = Number(raw);
|
|
213
|
+
return Number.isFinite(parsed) ? { envVar, value: Math.min(maximum, Math.max(minimum, parsed)) } : null;
|
|
214
|
+
}
|
|
@@ -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;
|