@loucompanion/forge-bridge 0.1.4-dev.63db04bcffca → 0.1.4-dev.83728c550770
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 +25 -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 +5 -0
- package/dist/cli/cli.service.js +62 -4
- package/dist/cli/local-config.d.ts +2 -0
- package/dist/cli/local-config.js +7 -1
- 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 +334 -19
- package/dist/runtime/host-runtime-promotion.js +12 -0
- package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
- package/dist/runtime/host-runtime-requirements-check.js +29 -0
- package/dist/runtime/host-runtime-requirements.d.ts +36 -0
- package/dist/runtime/host-runtime-requirements.js +117 -0
- package/dist/runtime/managed-command-teardown.d.ts +62 -0
- package/dist/runtime/managed-command-teardown.js +607 -0
- package/dist/runtime/playwright-browser-cache.d.ts +39 -0
- package/dist/runtime/playwright-browser-cache.js +227 -0
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +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 +37 -1
- package/dist/session/provider-cli/provider-cli.process.js +299 -25
- 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 +1 -1
|
@@ -7,6 +7,7 @@ import { assertHostAttemptRootIdentity, retainHostDiagnostics } from "./host-dia
|
|
|
7
7
|
import { assertHostExecutionRoot, compactHostAttemptId } from "./host-execution-root.js";
|
|
8
8
|
import { PreparedRuntimeReadiness } from "./prepared-runtime-readiness.js";
|
|
9
9
|
import { preparedRuntimeIdentity } from "./prepared-runtime-identity.js";
|
|
10
|
+
import { ForgeFailureError } from "../session/session.types.js";
|
|
10
11
|
import { resolveExistingDirectoryPath } from "../shared/path/path.js";
|
|
11
12
|
import { formatBytes } from "../shared/format/format-bytes.js";
|
|
12
13
|
import { redactText } from "../shared/redaction/redaction.js";
|
|
@@ -16,6 +17,7 @@ import { hostPortEnvironment, loadHostRuntimeContract, } from "./host-runtime-co
|
|
|
16
17
|
import { HostPortBroker, } from "./host-port-broker.js";
|
|
17
18
|
import { NodeHostRuntimeAdapter, } from "./node-host-runtime-adapter.js";
|
|
18
19
|
import { AttemptProcessSupervisorRegistry } from "./attempt-process-supervisor-registry.js";
|
|
20
|
+
import { terminateAttemptManagedCommands } from "./managed-command-teardown.js";
|
|
19
21
|
import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "./attempt-database-broker.js";
|
|
20
22
|
import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
|
|
21
23
|
import { HostListenerInspector } from "./host-listener-inspector.js";
|
|
@@ -29,6 +31,11 @@ import { readCanonicalSourceFile } from "./canonical-source-file.js";
|
|
|
29
31
|
import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
|
|
30
32
|
import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
|
|
31
33
|
import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
|
|
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";
|
|
38
|
+
import { HostLoadSampler } from "./host-load-sampler.js";
|
|
32
39
|
const hostCapacityWaiterScanLimit = 64;
|
|
33
40
|
const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
|
|
34
41
|
export class HostRuntimeLeaseManager {
|
|
@@ -60,10 +67,18 @@ export class HostRuntimeLeaseManager {
|
|
|
60
67
|
workspaceAvailableBytes = Number.MAX_SAFE_INTEGER;
|
|
61
68
|
portBroker;
|
|
62
69
|
nodeAdapter;
|
|
70
|
+
/** Rebuilt by applyCapacityLimits (decision 0014); every admission reads the current one. */
|
|
63
71
|
capacityConfiguration;
|
|
64
72
|
memoryAvailability;
|
|
65
73
|
executionRoot;
|
|
66
|
-
|
|
74
|
+
/** Host-wide admission for heavy steps (decision 0013); inert unless FORGE_HOST_LOAD_GOVERNOR=on. */
|
|
75
|
+
hostLoadGovernor;
|
|
76
|
+
requirementsCheck = null;
|
|
77
|
+
/** Installs the decision 0013 accept-time requirements recheck for host attempts. */
|
|
78
|
+
setRequirementsCheck(check) {
|
|
79
|
+
this.requirementsCheck = check;
|
|
80
|
+
}
|
|
81
|
+
constructor(stateRoot, portBroker = new HostPortBroker(), nodeAdapter, processSupervisors = new AttemptProcessSupervisorRegistry(), processRunner = new StreamingProviderProcessRunner(), listenerInspector = new HostListenerInspector(), promotionStore = new HostParallelPromotionStore(stateRoot), playwrightAdapter = new PlaywrightHostRuntimeAdapter(), processRecovery = new ExactHostProcessRecovery(), capacityResourceSample, executionRoot, databaseBroker = null, hostLoad = null) {
|
|
67
82
|
this.stateRoot = stateRoot;
|
|
68
83
|
this.processSupervisors = processSupervisors;
|
|
69
84
|
this.processRunner = processRunner;
|
|
@@ -73,6 +88,7 @@ export class HostRuntimeLeaseManager {
|
|
|
73
88
|
this.processRecovery = processRecovery;
|
|
74
89
|
this.capacityResourceSample = capacityResourceSample;
|
|
75
90
|
this.databaseBroker = databaseBroker;
|
|
91
|
+
this.hostLoadGovernor = new HostLoadGovernor({ stateRoot, load: hostLoad ?? new HostLoadSampler() });
|
|
76
92
|
this.executionRoot = path.resolve(executionRoot ?? stateRoot);
|
|
77
93
|
if (executionRoot !== undefined)
|
|
78
94
|
assertHostExecutionRoot(this.executionRoot);
|
|
@@ -82,7 +98,40 @@ export class HostRuntimeLeaseManager {
|
|
|
82
98
|
this.capacityConfiguration = loadHostCapacityConfiguration(capacityResourceSample);
|
|
83
99
|
this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
|
|
84
100
|
}
|
|
101
|
+
/** Today's defaults for the limits the server can push, before any env bound (decision 0014). */
|
|
102
|
+
capacityLimitDefaults() {
|
|
103
|
+
return {
|
|
104
|
+
maxConcurrentAttempts: this.capacityConfiguration.defaultHardMaxAttempts,
|
|
105
|
+
memoryReserveBytes: this.capacityConfiguration.adaptiveHostReserveBytes,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Decision 0014: the bridge's effective max attempts and memory reserve. They
|
|
110
|
+
* apply from the next attempt admission; admitted attempts keep their
|
|
111
|
+
* reservations and are never preempted, even when the new limit is lower than
|
|
112
|
+
* what already runs. The idle reserve follows the reserve as at startup.
|
|
113
|
+
*/
|
|
114
|
+
applyCapacityLimits(limits) {
|
|
115
|
+
const current = this.capacityConfiguration;
|
|
116
|
+
const hardMaxAttempts = Math.max(1, Math.min(32, Math.floor(limits.maxConcurrentAttempts)));
|
|
117
|
+
const hostReserveBytes = Math.max(512 * 1024 ** 2, Math.floor(limits.memoryReserveBytes));
|
|
118
|
+
if (hardMaxAttempts === current.hardMaxAttempts && hostReserveBytes === current.hostReserveBytes)
|
|
119
|
+
return;
|
|
120
|
+
this.capacityConfiguration = {
|
|
121
|
+
...current,
|
|
122
|
+
hardMaxAttempts,
|
|
123
|
+
hostReserveBytes,
|
|
124
|
+
idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, current),
|
|
125
|
+
};
|
|
126
|
+
// A raised limit may admit queued attempts now rather than at their next recheck.
|
|
127
|
+
this.drainAdmissionWaiters();
|
|
128
|
+
}
|
|
129
|
+
hostLoadChildEnvironment() {
|
|
130
|
+
return this.hostLoadGovernor.enabled ? hostLoadChildEnvironment(this.stateRoot) : {};
|
|
131
|
+
}
|
|
85
132
|
async reap(options) {
|
|
133
|
+
// Heavy-step tokens whose owner died or whose lease lapsed are returned first.
|
|
134
|
+
await this.hostLoadGovernor.reclaim().catch(() => undefined);
|
|
86
135
|
await this.refreshKnownPromotions();
|
|
87
136
|
const recoveredAttempts = [];
|
|
88
137
|
const report = {
|
|
@@ -207,6 +256,11 @@ export class HostRuntimeLeaseManager {
|
|
|
207
256
|
// drop that met a lingering session) are removed once no live lease holds them.
|
|
208
257
|
// A degraded lease may still own running processes after a restart, so its database is kept.
|
|
209
258
|
await this.databaseBroker?.reapOrphans(id => this.active.has(id) || this.degraded.has(id)).catch(() => undefined);
|
|
259
|
+
// Heavy-step tokens of a dead owner with no recorded process tree (an attempt that
|
|
260
|
+
// ended with a crashed bridge or MCP server) are returned once no live lease holds
|
|
261
|
+
// their attempt; a degraded lease may still own the running step, so its tokens stay.
|
|
262
|
+
await this.hostLoadGovernor.releaseOrphaned(token => !token.dispatchAttemptId
|
|
263
|
+
|| (!this.active.has(token.dispatchAttemptId) && !this.degraded.has(token.dispatchAttemptId))).catch(() => undefined);
|
|
210
264
|
return report;
|
|
211
265
|
}
|
|
212
266
|
snapshot() {
|
|
@@ -924,6 +978,15 @@ export class HostRuntimeLeaseManager {
|
|
|
924
978
|
let attemptRootIdentity = null;
|
|
925
979
|
try {
|
|
926
980
|
const runtimeContract = await loadHostRuntimeContract(normalizedWorktreePath);
|
|
981
|
+
// Decision 0013 accept-time recheck. Readiness probes are exempt: they are how the
|
|
982
|
+
// API learns the requirements in the first place.
|
|
983
|
+
const unmetRequirements = dispatch.workItem.kind === "runtime_readiness"
|
|
984
|
+
? []
|
|
985
|
+
: this.requirementsCheck?.(runtimeContract.contract.requires) ?? [];
|
|
986
|
+
if (unmetRequirements.length > 0) {
|
|
987
|
+
// Typed, so the API receives the retryable code and re-places the work (not bridge.execution_failed).
|
|
988
|
+
throw new ForgeFailureError("placement_requirements_unmet", `placement_requirements_unmet: this host does not meet the project's requirements: ${unmetRequirements.join("; ")}.`);
|
|
989
|
+
}
|
|
927
990
|
if (runtimeContract.contract.runtime.hostConcurrency === "disabled") {
|
|
928
991
|
throw new Error("host_runtime_disabled: project runtime configuration requires Docker execution.");
|
|
929
992
|
}
|
|
@@ -1088,6 +1151,8 @@ export class HostRuntimeLeaseManager {
|
|
|
1088
1151
|
parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract) && dispatch.cycleRun.phase !== "prepared_readiness",
|
|
1089
1152
|
processSupervisor,
|
|
1090
1153
|
adapterCleanups: [],
|
|
1154
|
+
adapterCleanupsByPort: new Map(),
|
|
1155
|
+
restartingConfiguredProject: false,
|
|
1091
1156
|
pendingAdapterLaunches: new Map(),
|
|
1092
1157
|
runtimeResourcesReleased: false,
|
|
1093
1158
|
releasing: false,
|
|
@@ -1150,6 +1215,15 @@ export class HostRuntimeLeaseManager {
|
|
|
1150
1215
|
await this.writeLedger(renewed);
|
|
1151
1216
|
}
|
|
1152
1217
|
async startConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
|
|
1218
|
+
return await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, true);
|
|
1219
|
+
}
|
|
1220
|
+
/**
|
|
1221
|
+
* Launches the configured project. Only the first launch, from the admitted commit's clean
|
|
1222
|
+
* source, may record parallel-safety proof: a restart serves the workspace after the provider
|
|
1223
|
+
* edited it, and a proof observed there would be stored under the admitted commit and could
|
|
1224
|
+
* move this or a later attempt at that commit into shared admission for source it never ran.
|
|
1225
|
+
*/
|
|
1226
|
+
async launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, promote) {
|
|
1153
1227
|
const active = this.active.get(dispatchAttemptId);
|
|
1154
1228
|
if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
|
|
1155
1229
|
throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
|
|
@@ -1171,6 +1245,11 @@ export class HostRuntimeLeaseManager {
|
|
|
1171
1245
|
executionClass: active.executionClass,
|
|
1172
1246
|
};
|
|
1173
1247
|
}
|
|
1248
|
+
const playwrightConfig = active.runtimeContract.contract.runtime.playwright;
|
|
1249
|
+
// A host without the project's pinned browsers fails here, before any database,
|
|
1250
|
+
// build, launch, or promotion work that the attempt would otherwise waste.
|
|
1251
|
+
if (playwrightConfig)
|
|
1252
|
+
await this.playwrightAdapter.assertBrowserCacheReady(playwrightConfig, active.lease.worktreePath);
|
|
1174
1253
|
const owner = hostPortOwner(active.lease);
|
|
1175
1254
|
const logDirectory = active.lease.resources.paths.find(entry => entry.role === "logs")?.path;
|
|
1176
1255
|
if (!logDirectory)
|
|
@@ -1220,7 +1299,29 @@ export class HostRuntimeLeaseManager {
|
|
|
1220
1299
|
message: `Preparing the ASP.NET runtime for commit ${active.inputCommitSha.slice(0, 12)} before binding its assigned port.`,
|
|
1221
1300
|
data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath },
|
|
1222
1301
|
});
|
|
1223
|
-
|
|
1302
|
+
let hostLoadWaitMs = null;
|
|
1303
|
+
const build = await ensureAspNetRuntimePrebuilt(prebuild,
|
|
1304
|
+
// Only a real build (not a verified cache hit) takes a host load token.
|
|
1305
|
+
async (plan, buildSignal) => await runHostGovernedStep(this.hostLoadGovernor, {
|
|
1306
|
+
classification: aspNetPrebuildStepClass,
|
|
1307
|
+
label: prebuild.projectPath,
|
|
1308
|
+
dispatchAttemptId,
|
|
1309
|
+
priority: this.admissions.get(dispatchAttemptId)?.priority ?? "foreground",
|
|
1310
|
+
signal: buildSignal,
|
|
1311
|
+
onWaiting: async (decision) => await onProjectCheckpoint?.({
|
|
1312
|
+
code: "host_runtime_build_waiting_for_host_capacity",
|
|
1313
|
+
message: `The ASP.NET runtime build is waiting for host capacity: ${decision.detail}`,
|
|
1314
|
+
data: { status: "waiting_for_host_capacity", step_class: aspNetPrebuildStepClass.stepClass, reason: decision.reason },
|
|
1315
|
+
}),
|
|
1316
|
+
}, async (waitMs, control) => {
|
|
1317
|
+
hostLoadWaitMs = waitMs;
|
|
1318
|
+
// A reclaimed token stops the build: its capacity is no longer reserved. So does a
|
|
1319
|
+
// build whose process tree cannot be recorded on its token (a reclaim could not stop it).
|
|
1320
|
+
const unrecorded = new AbortController();
|
|
1321
|
+
const stepSignal = anySignal(buildSignal, control.fenced, unrecorded.signal);
|
|
1322
|
+
return await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, stepSignal, capabilitySecrets, async (metadataPath) => await attachSupervisedStepProcess(control, metadataPath)
|
|
1323
|
+
.catch((error) => { unrecorded.abort(error); }));
|
|
1324
|
+
}), signal);
|
|
1224
1325
|
await onProjectCheckpoint?.({
|
|
1225
1326
|
code: build.cacheHit ? "host_runtime_build_cached" : "host_runtime_build_completed",
|
|
1226
1327
|
message: build.cacheHit
|
|
@@ -1230,6 +1331,7 @@ export class HostRuntimeLeaseManager {
|
|
|
1230
1331
|
input_commit_sha: active.inputCommitSha,
|
|
1231
1332
|
build_fingerprint: build.fingerprint,
|
|
1232
1333
|
receipt_path: build.receiptPath,
|
|
1334
|
+
...(hostLoadWaitMs === null ? {} : { host_load_wait_ms: hostLoadWaitMs }),
|
|
1233
1335
|
},
|
|
1234
1336
|
});
|
|
1235
1337
|
}
|
|
@@ -1242,7 +1344,7 @@ export class HostRuntimeLeaseManager {
|
|
|
1242
1344
|
},
|
|
1243
1345
|
}, launcher, signal);
|
|
1244
1346
|
}
|
|
1245
|
-
const promotedLease = await this.promoteVerifiedRuntime(active, active.lease);
|
|
1347
|
+
const promotedLease = promote ? await this.promoteVerifiedRuntime(active, active.lease) : active.lease;
|
|
1246
1348
|
const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass, active.databaseCapability);
|
|
1247
1349
|
const playwright = active.runtimeContract.contract.runtime.playwright;
|
|
1248
1350
|
if (!playwright) {
|
|
@@ -1281,6 +1383,93 @@ export class HostRuntimeLeaseManager {
|
|
|
1281
1383
|
executionClass: active.executionClass,
|
|
1282
1384
|
};
|
|
1283
1385
|
}
|
|
1386
|
+
/**
|
|
1387
|
+
* Relaunches the configured project so it serves the current workspace. Every
|
|
1388
|
+
* configured process stops (the API port changes, so the dev server's proxy target
|
|
1389
|
+
* must change with it), its port reservation is released and dropped from the
|
|
1390
|
+
* persisted lease, and the regular start path runs again, including the ASP.NET
|
|
1391
|
+
* prebuild, whose receipt rebuilds only when the sources changed.
|
|
1392
|
+
*/
|
|
1393
|
+
async restartConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
|
|
1394
|
+
const active = this.active.get(dispatchAttemptId);
|
|
1395
|
+
if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
|
|
1396
|
+
throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
|
|
1397
|
+
}
|
|
1398
|
+
if (signal?.aborted)
|
|
1399
|
+
throw new Error(String(signal.reason ?? "Host runtime restart was cancelled."));
|
|
1400
|
+
if (active.restartingConfiguredProject) {
|
|
1401
|
+
throw new Error("host_runtime_project_conflict: a configured project restart is already in progress.");
|
|
1402
|
+
}
|
|
1403
|
+
active.restartingConfiguredProject = true;
|
|
1404
|
+
// Release cancels the whole restart through this controller and waits for it to settle.
|
|
1405
|
+
const controller = linkedAbortController(signal);
|
|
1406
|
+
const promise = this.runConfiguredProjectRestart(active, dispatchAttemptId, fencingToken, controller.signal, onProjectCheckpoint);
|
|
1407
|
+
const restart = { controller, promise };
|
|
1408
|
+
active.configuredProjectRestart = restart;
|
|
1409
|
+
try {
|
|
1410
|
+
return await promise;
|
|
1411
|
+
}
|
|
1412
|
+
finally {
|
|
1413
|
+
// The controller is not aborted on settle: adapters this restart launched keep it as their
|
|
1414
|
+
// parent signal for as long as they run, exactly as they would keep the caller's signal.
|
|
1415
|
+
if (active.configuredProjectRestart === restart)
|
|
1416
|
+
active.configuredProjectRestart = null;
|
|
1417
|
+
active.restartingConfiguredProject = false;
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
async runConfiguredProjectRestart(active, dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
|
|
1421
|
+
// The relaunch reuses the contract (commands, ports, environment, concurrency) admitted at
|
|
1422
|
+
// start. If the workspace now declares a different one, a restart would run stale settings;
|
|
1423
|
+
// the attempt fails retryably instead, so a fresh attempt admits the new contract.
|
|
1424
|
+
const currentContract = await loadHostRuntimeContract(active.lease.worktreePath);
|
|
1425
|
+
if (hostRuntimeContractFingerprint(currentContract) !== active.runtimeContractFingerprint) {
|
|
1426
|
+
throw new ForgeFailureError("host_runtime_contract_changed", "host_runtime_contract_changed: the workspace's runtime contract changed after this attempt's runtime was admitted; a fresh attempt is needed to run it.");
|
|
1427
|
+
}
|
|
1428
|
+
const portNames = active.executionClass === "analysis_only" ? [] : configuredLaunchPortNames(active.runtimeContract);
|
|
1429
|
+
const pendingPort = portNames.find(name => active.pendingAdapterLaunches.has(name));
|
|
1430
|
+
if (pendingPort) {
|
|
1431
|
+
throw new Error(`host_runtime_project_conflict: configured port '${pendingPort}' is still launching.`);
|
|
1432
|
+
}
|
|
1433
|
+
const temporaryDirectory = active.lease.resources.paths.find(entry => entry.role === "temporary")?.path;
|
|
1434
|
+
if (active.runtimeContract.contract.runtime.playwright && temporaryDirectory) {
|
|
1435
|
+
// The generated Playwright config targets the stack being stopped. If the restart fails, no
|
|
1436
|
+
// config may be left pointing at ports another attempt can now be assigned.
|
|
1437
|
+
await this.playwrightAdapter.discardOverlay(temporaryDirectory);
|
|
1438
|
+
}
|
|
1439
|
+
await this.stopConfiguredProject(active, portNames);
|
|
1440
|
+
// Keeps whatever admission the attempt holds; see launchConfiguredProject.
|
|
1441
|
+
const restarted = await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, false);
|
|
1442
|
+
if (active.releasing) {
|
|
1443
|
+
throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
|
|
1444
|
+
}
|
|
1445
|
+
return restarted;
|
|
1446
|
+
}
|
|
1447
|
+
/** Stops configured project processes in reverse launch order and releases their ports. */
|
|
1448
|
+
async stopConfiguredProject(active, portNames) {
|
|
1449
|
+
const launched = active.lease.resources.ports
|
|
1450
|
+
.map(port => port.name)
|
|
1451
|
+
.filter(name => portNames.includes(name))
|
|
1452
|
+
.reverse();
|
|
1453
|
+
for (const name of launched) {
|
|
1454
|
+
if (active.releasing) {
|
|
1455
|
+
throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
|
|
1456
|
+
}
|
|
1457
|
+
const cleanup = active.adapterCleanupsByPort.get(name);
|
|
1458
|
+
if (!cleanup) {
|
|
1459
|
+
throw new Error(`host_runtime_project_restart_unavailable: configured port '${name}' has no supervised process to stop.`);
|
|
1460
|
+
}
|
|
1461
|
+
// A failed stop keeps the cleanup and the port record for the fenced release retry.
|
|
1462
|
+
await cleanup();
|
|
1463
|
+
removeCleanup(active.adapterCleanups, cleanup);
|
|
1464
|
+
active.adapterCleanupsByPort.delete(name);
|
|
1465
|
+
const runtimeLease = withRuntimeIsolationResources(active.lease, {
|
|
1466
|
+
...active.lease.resources,
|
|
1467
|
+
ports: active.lease.resources.ports.filter(port => port.name !== name),
|
|
1468
|
+
});
|
|
1469
|
+
await this.writeLedger(runtimeLease);
|
|
1470
|
+
active.lease = runtimeLease;
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1284
1473
|
providerProcessRunner(dispatchAttemptId, fencingToken) {
|
|
1285
1474
|
const active = this.active.get(dispatchAttemptId);
|
|
1286
1475
|
if (!active || active.lease.fencingToken !== fencingToken || active.releasing)
|
|
@@ -1368,6 +1557,7 @@ export class HostRuntimeLeaseManager {
|
|
|
1368
1557
|
unlinkAbortController(controller, signal);
|
|
1369
1558
|
};
|
|
1370
1559
|
active.adapterCleanups.push(cleanup);
|
|
1560
|
+
active.adapterCleanupsByPort.set(portName, cleanup);
|
|
1371
1561
|
try {
|
|
1372
1562
|
if (active.releasing)
|
|
1373
1563
|
throw new Error("host_runtime_adapter_cancelled: host runtime release started during launch.");
|
|
@@ -1390,6 +1580,8 @@ export class HostRuntimeLeaseManager {
|
|
|
1390
1580
|
try {
|
|
1391
1581
|
await cleanup();
|
|
1392
1582
|
removeCleanup(active.adapterCleanups, cleanup);
|
|
1583
|
+
if (active.adapterCleanupsByPort.get(portName) === cleanup)
|
|
1584
|
+
active.adapterCleanupsByPort.delete(portName);
|
|
1393
1585
|
}
|
|
1394
1586
|
catch {
|
|
1395
1587
|
// Preserve the cleanup and broker claim for the fenced release retry.
|
|
@@ -1414,6 +1606,9 @@ export class HostRuntimeLeaseManager {
|
|
|
1414
1606
|
if (!preservePreparation)
|
|
1415
1607
|
this.pendingRenewals.delete(dispatchAttemptId);
|
|
1416
1608
|
if (!active) {
|
|
1609
|
+
// Queued steps are cancelled and running ones stopped; each returns its own
|
|
1610
|
+
// token once its processes are gone (never before, or capacity is reused early).
|
|
1611
|
+
this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
|
|
1417
1612
|
this.cancelAdmissionWaiters(dispatchAttemptId, fencingToken, "Managed host admission was released before acquisition.");
|
|
1418
1613
|
this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
|
|
1419
1614
|
this.releaseParallelProjects(dispatchAttemptId, fencingToken);
|
|
@@ -1423,10 +1618,20 @@ export class HostRuntimeLeaseManager {
|
|
|
1423
1618
|
if (active.lease.fencingToken !== fencingToken)
|
|
1424
1619
|
return null;
|
|
1425
1620
|
active.releasing = true;
|
|
1621
|
+
// Attempt teardown cancels the attempt's queued heavy steps and stops its running
|
|
1622
|
+
// ones. Each running step (an ASP.NET prebuild, an install, a validation step)
|
|
1623
|
+
// returns its own token only after its processes have exited, so the capacity is
|
|
1624
|
+
// not reused while, say, a build is still being terminated.
|
|
1625
|
+
this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
|
|
1426
1626
|
for (const pending of active.pendingAdapterLaunches.values()) {
|
|
1427
1627
|
pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
|
|
1428
1628
|
}
|
|
1429
1629
|
await Promise.allSettled([...active.pendingAdapterLaunches.values()].map(pending => pending.promise));
|
|
1630
|
+
const restart = active.configuredProjectRestart;
|
|
1631
|
+
if (restart) {
|
|
1632
|
+
restart.controller.abort("Host runtime release cancelled the configured project restart.");
|
|
1633
|
+
await restart.promise.catch(() => undefined);
|
|
1634
|
+
}
|
|
1430
1635
|
await active.databaseProvision?.catch(() => undefined);
|
|
1431
1636
|
let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
|
|
1432
1637
|
active.lease = releasing;
|
|
@@ -1434,7 +1639,17 @@ export class HostRuntimeLeaseManager {
|
|
|
1434
1639
|
try {
|
|
1435
1640
|
if (!active.runtimeResourcesReleased) {
|
|
1436
1641
|
await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
|
|
1642
|
+
// The attempt's MCP servers and process trees are stopped now; tokens they held
|
|
1643
|
+
// belong to dead owners and go back to the host budget at once, including any
|
|
1644
|
+
// without a recorded process tree (their steps were inside the stopped trees).
|
|
1645
|
+
await this.hostLoadGovernor.reclaim().catch(() => undefined);
|
|
1646
|
+
await this.hostLoadGovernor.releaseOrphaned(token => token.dispatchAttemptId === dispatchAttemptId)
|
|
1647
|
+
.catch(() => undefined);
|
|
1648
|
+
// This bridge's own steps whose trees only stopAll could prove gone (a supervised
|
|
1649
|
+
// validation step whose termination failed earlier) return their tokens now.
|
|
1650
|
+
await this.hostLoadGovernor.releaseRetainedAfterTeardown(dispatchAttemptId).catch(() => undefined);
|
|
1437
1651
|
await releaseAdapterResources(active.adapterCleanups);
|
|
1652
|
+
active.adapterCleanupsByPort.clear();
|
|
1438
1653
|
if (active.databaseCapability && this.databaseBroker) {
|
|
1439
1654
|
// A database the broker cannot drop now is reaped later; it must not hold host capacity.
|
|
1440
1655
|
await this.databaseBroker.release(dispatchAttemptId, fencingToken).catch(() => "retained");
|
|
@@ -1532,18 +1747,46 @@ export class HostRuntimeLeaseManager {
|
|
|
1532
1747
|
if (logsEntry.kind !== "directory") {
|
|
1533
1748
|
throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
|
|
1534
1749
|
}
|
|
1535
|
-
const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
|
|
1536
1750
|
const outcomes = [];
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
const
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1751
|
+
const failures = [];
|
|
1752
|
+
try {
|
|
1753
|
+
const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
|
|
1754
|
+
for (const entry of entries) {
|
|
1755
|
+
if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
|
|
1756
|
+
continue;
|
|
1757
|
+
const metadataPath = path.join(logsRoot, entry.name);
|
|
1758
|
+
const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
|
|
1759
|
+
if (!validHostProcessSupervisorMetadata(value, lease)) {
|
|
1760
|
+
throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
|
|
1761
|
+
}
|
|
1762
|
+
outcomes.push(await this.processRecovery.recover(value));
|
|
1544
1763
|
}
|
|
1545
|
-
outcomes.push(await this.processRecovery.recover(value));
|
|
1546
1764
|
}
|
|
1765
|
+
catch (error) {
|
|
1766
|
+
failures.push(error);
|
|
1767
|
+
}
|
|
1768
|
+
// Managed commands run in their own process groups and record their ownership apart
|
|
1769
|
+
// from the attempt's supervised children. They are recovered even when recovering a
|
|
1770
|
+
// supervised child failed, and both failures are reported together.
|
|
1771
|
+
try {
|
|
1772
|
+
const managed = await terminateAttemptManagedCommands({
|
|
1773
|
+
logDirectory: logsRoot,
|
|
1774
|
+
dispatchAttemptId: lease.dispatchAttemptId,
|
|
1775
|
+
runtimeLeaseId: lease.executionLeaseId,
|
|
1776
|
+
pinnedLogDirectory: logsEntry.identity,
|
|
1777
|
+
}, { reason: "attempt_teardown" });
|
|
1778
|
+
for (const command of managed) {
|
|
1779
|
+
if (command.outcome === "terminated" || command.outcome === "pid_reused")
|
|
1780
|
+
outcomes.push(command.outcome);
|
|
1781
|
+
}
|
|
1782
|
+
}
|
|
1783
|
+
catch (error) {
|
|
1784
|
+
failures.push(error);
|
|
1785
|
+
}
|
|
1786
|
+
if (failures.length === 1)
|
|
1787
|
+
throw failures[0];
|
|
1788
|
+
if (failures.length > 1)
|
|
1789
|
+
throw new AggregateError(failures, "host_runtime_reaper_recovery_failed");
|
|
1547
1790
|
return outcomes;
|
|
1548
1791
|
}
|
|
1549
1792
|
async markLedgerDegraded(ledger) {
|
|
@@ -1919,6 +2162,18 @@ class AttemptSupervisedProviderProcessRunner {
|
|
|
1919
2162
|
: new Set();
|
|
1920
2163
|
const child = await this.supervisor.startChildReady("provider", request, handlers, signal, { maxStartAttempts: request.stdin === undefined ? 1 : 3, retryDelayMs: 100 });
|
|
1921
2164
|
this.onProcessTreeStarted();
|
|
2165
|
+
try {
|
|
2166
|
+
return await this.awaitProviderResult(child, baselineListeners, signal);
|
|
2167
|
+
}
|
|
2168
|
+
finally {
|
|
2169
|
+
// The provider tree, and the MCP server inside it, is gone. A managed command that
|
|
2170
|
+
// server started now has no supervisor and no receipt writer, so it must not keep
|
|
2171
|
+
// running into the next provider generation. This never rejects; a command it
|
|
2172
|
+
// cannot prove stopped is left to attempt teardown, which fails closed.
|
|
2173
|
+
await this.supervisor.stopOrphanedManagedCommands();
|
|
2174
|
+
}
|
|
2175
|
+
}
|
|
2176
|
+
async awaitProviderResult(child, baselineListeners, signal) {
|
|
1922
2177
|
if (!this.enforceNoListeners)
|
|
1923
2178
|
return await child.result;
|
|
1924
2179
|
let settled = false;
|
|
@@ -2094,7 +2349,36 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
|
|
|
2094
2349
|
environment.FORGE_BASE_URL = resolvedBaseUrls[0];
|
|
2095
2350
|
return environment;
|
|
2096
2351
|
}
|
|
2097
|
-
|
|
2352
|
+
/**
|
|
2353
|
+
* Every environment key `hostRuntimeEnvironment` and the Playwright overlay derive from the
|
|
2354
|
+
* configured project's assigned ports. They name a live stack, so they are withheld while the
|
|
2355
|
+
* stack is down: after its ports are released another attempt may be assigned them.
|
|
2356
|
+
*/
|
|
2357
|
+
export function hostRuntimeStackEnvironmentKeys(runtimeContract) {
|
|
2358
|
+
const keys = new Set([
|
|
2359
|
+
"FORGE_E2E_API_URL",
|
|
2360
|
+
"FORGE_E2E_WEB_URL",
|
|
2361
|
+
"FORGE_BASE_URL",
|
|
2362
|
+
"FORGE_PLAYWRIGHT_BASE_URL",
|
|
2363
|
+
// The generated Playwright config embeds the base URL.
|
|
2364
|
+
"FORGE_PLAYWRIGHT_CONFIG",
|
|
2365
|
+
]);
|
|
2366
|
+
for (const port of runtimeContract.contract.runtime.ports) {
|
|
2367
|
+
const normalizedName = port.name.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_");
|
|
2368
|
+
keys.add(port.env);
|
|
2369
|
+
if (port.baseUrlEnv)
|
|
2370
|
+
keys.add(port.baseUrlEnv);
|
|
2371
|
+
keys.add(`FORGE_${normalizedName}_PORT`);
|
|
2372
|
+
keys.add(`FORGE_${normalizedName}_URL`);
|
|
2373
|
+
}
|
|
2374
|
+
return [...keys];
|
|
2375
|
+
}
|
|
2376
|
+
function anySignal(...signals) {
|
|
2377
|
+
return AbortSignal.any(signals.filter((signal) => signal !== undefined));
|
|
2378
|
+
}
|
|
2379
|
+
async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal, exactSecrets = [],
|
|
2380
|
+
/** Once the build's supervised tree is up: records it on the build's host load token. */
|
|
2381
|
+
onStarted) {
|
|
2098
2382
|
const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
|
|
2099
2383
|
const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
|
|
2100
2384
|
const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
|
|
@@ -2119,6 +2403,7 @@ async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal,
|
|
|
2119
2403
|
await append(stderrLogPath, line);
|
|
2120
2404
|
},
|
|
2121
2405
|
}, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
|
|
2406
|
+
await onStarted?.(child.metadataPath);
|
|
2122
2407
|
const result = await child.result;
|
|
2123
2408
|
return {
|
|
2124
2409
|
exitCode: result.exitCode,
|
|
@@ -2161,7 +2446,7 @@ function runtimeExecutionClass(dispatch) {
|
|
|
2161
2446
|
? "analysis_only"
|
|
2162
2447
|
: "managed_runtime";
|
|
2163
2448
|
}
|
|
2164
|
-
function runtimeAdmissionPriority(dispatch) {
|
|
2449
|
+
export function runtimeAdmissionPriority(dispatch) {
|
|
2165
2450
|
return dispatch.execution.lane.trim().toLowerCase() === "runtime_readiness"
|
|
2166
2451
|
|| dispatch.cycleRun.phase.trim().toLowerCase() === "readiness_probe"
|
|
2167
2452
|
? "background"
|
|
@@ -2233,6 +2518,18 @@ function configuredInteger(name, fallback, minimum, maximum) {
|
|
|
2233
2518
|
const parsed = Number.parseInt(process.env[name] ?? "", 10);
|
|
2234
2519
|
return Number.isFinite(parsed) ? Math.max(minimum, Math.min(maximum, parsed)) : fallback;
|
|
2235
2520
|
}
|
|
2521
|
+
/**
|
|
2522
|
+
* Today's max attempts and adaptive memory reserve for this host, before
|
|
2523
|
+
* FORGE_HOST_MAX_CONCURRENT_ATTEMPTS and FORGE_HOST_MEMORY_RESERVE_BYTES
|
|
2524
|
+
* (decision 0014 treats those as bounds on the server's values).
|
|
2525
|
+
*/
|
|
2526
|
+
export function hostCapacityLimitDefaults(capacityResourceSample) {
|
|
2527
|
+
const configuration = loadHostCapacityConfiguration(capacityResourceSample);
|
|
2528
|
+
return {
|
|
2529
|
+
maxConcurrentAttempts: configuration.defaultHardMaxAttempts,
|
|
2530
|
+
memoryReserveBytes: configuration.adaptiveHostReserveBytes,
|
|
2531
|
+
};
|
|
2532
|
+
}
|
|
2236
2533
|
function loadHostCapacityConfiguration(capacityResourceSample) {
|
|
2237
2534
|
const sampledCpuCount = capacityResourceSample
|
|
2238
2535
|
? Math.max(1, Math.floor(capacityResourceSample.totalCpuMillis / 1_000))
|
|
@@ -2240,23 +2537,41 @@ function loadHostCapacityConfiguration(capacityResourceSample) {
|
|
|
2240
2537
|
const totalMemoryBytes = capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
|
|
2241
2538
|
const reserveFloorBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_FLOOR_BYTES", 1024 ** 3, 512 * 1024 ** 2, 128 * 1024 ** 3);
|
|
2242
2539
|
const reserveCeilingBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_CEILING_BYTES", 4 * 1024 ** 3, reserveFloorBytes, 128 * 1024 ** 3);
|
|
2243
|
-
const
|
|
2244
|
-
explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
|
|
2540
|
+
const adaptiveOptions = {
|
|
2245
2541
|
floorBytes: reserveFloorBytes,
|
|
2246
2542
|
ceilingBytes: reserveCeilingBytes,
|
|
2247
2543
|
percent: configuredNumber("FORGE_HOST_MEMORY_RESERVE_PERCENT", 12.5, 1, 50),
|
|
2544
|
+
};
|
|
2545
|
+
const hostReserveBytes = resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, {
|
|
2546
|
+
...adaptiveOptions,
|
|
2547
|
+
explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
|
|
2248
2548
|
});
|
|
2249
|
-
const
|
|
2549
|
+
const defaultHardMaxAttempts = Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2)));
|
|
2550
|
+
const idleReserveOverride = Number.parseInt(process.env.FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES ?? "", 10);
|
|
2551
|
+
const idleReserveOverrideBytes = Number.isFinite(idleReserveOverride) ? idleReserveOverride : null;
|
|
2250
2552
|
return {
|
|
2251
|
-
hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS",
|
|
2553
|
+
hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", defaultHardMaxAttempts, 1, 32),
|
|
2252
2554
|
hostReserveBytes,
|
|
2253
|
-
idleHostReserveBytes:
|
|
2555
|
+
idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, { reserveFloorBytes, idleReserveOverrideBytes }),
|
|
2556
|
+
defaultHardMaxAttempts,
|
|
2557
|
+
adaptiveHostReserveBytes: resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, adaptiveOptions),
|
|
2558
|
+
reserveFloorBytes,
|
|
2559
|
+
idleReserveOverrideBytes,
|
|
2254
2560
|
cpuReserveMillis: configuredInteger("FORGE_HOST_CPU_RESERVE_MILLIS", 1000, 0, 32_000),
|
|
2255
2561
|
workspaceReserveBytes: configuredInteger("FORGE_HOST_WORKSPACE_RESERVE_BYTES", 10 * 1024 ** 3, 1024 ** 3, Number.MAX_SAFE_INTEGER),
|
|
2256
2562
|
memoryRecoverySamples: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLES", 2, 1, 10),
|
|
2257
2563
|
memoryRecoverySampleIntervalMs: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLE_INTERVAL_MS", 1_000, 100, 30_000),
|
|
2258
2564
|
};
|
|
2259
2565
|
}
|
|
2566
|
+
/**
|
|
2567
|
+
* The reserve kept while no attempt holds capacity: FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES
|
|
2568
|
+
* clamped to [512 MiB, reserve], else min(reserve, reserve floor). Never above the reserve.
|
|
2569
|
+
*/
|
|
2570
|
+
function idleHostReserveBytesFor(hostReserveBytes, configuration) {
|
|
2571
|
+
const fallback = Math.min(hostReserveBytes, configuration.reserveFloorBytes);
|
|
2572
|
+
const override = configuration.idleReserveOverrideBytes;
|
|
2573
|
+
return override === null ? fallback : Math.max(512 * 1024 ** 2, Math.min(hostReserveBytes, override));
|
|
2574
|
+
}
|
|
2260
2575
|
function configuredOptionalInteger(name, minimum, maximum) {
|
|
2261
2576
|
const raw = process.env[name];
|
|
2262
2577
|
if (raw === undefined || raw.trim().length === 0)
|
|
@@ -145,12 +145,24 @@ export function hostRuntimeContractFingerprint(runtimeContract) {
|
|
|
145
145
|
const canonical = JSON.stringify({
|
|
146
146
|
schemaVersion: runtimeContract.contract.schemaVersion,
|
|
147
147
|
runtime: runtimeContract.contract.runtime,
|
|
148
|
+
// Requirements join the fingerprint only when declared, so fingerprints of contracts
|
|
149
|
+
// written before decision 0013 (and their stored promotions) stay unchanged.
|
|
150
|
+
...requirementsFingerprintPart(runtimeContract.contract.requires),
|
|
148
151
|
derivedCandidateFingerprint: runtimeContract.source === "derived"
|
|
149
152
|
? runtimeContract.discovery?.candidateFingerprint ?? null
|
|
150
153
|
: null,
|
|
151
154
|
});
|
|
152
155
|
return `sha256:${createHash("sha256").update(canonical).digest("hex")}`;
|
|
153
156
|
}
|
|
157
|
+
// Cost hints are estimates, not placement constraints: they never change the fingerprint.
|
|
158
|
+
function requirementsFingerprintPart(requires) {
|
|
159
|
+
if (!requires)
|
|
160
|
+
return {};
|
|
161
|
+
const { costHints: _costHints, ...constraints } = requires;
|
|
162
|
+
const declared = constraints.minThreads !== null || constraints.minMemoryGiB !== null || constraints.toolchains.length > 0
|
|
163
|
+
|| constraints.docker || constraints.playwright !== null || constraints.testPostgres !== null;
|
|
164
|
+
return declared ? { requires: constraints } : {};
|
|
165
|
+
}
|
|
154
166
|
export function hostRuntimeParallelEligible(runtimeContract) {
|
|
155
167
|
const runtime = runtimeContract.contract.runtime;
|
|
156
168
|
const launchedPorts = runtime.ports.filter(port => port.launch !== null);
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { HostRuntimeRequirements } from "./host-runtime-requirements.js";
|
|
2
|
+
/** What this bridge host offers, for the accept-time requirements recheck (decision 0013). */
|
|
3
|
+
export interface HostRequirementFacts {
|
|
4
|
+
readonly logicalThreads: number;
|
|
5
|
+
readonly totalMemoryBytes: number;
|
|
6
|
+
readonly availableToolchains: readonly string[];
|
|
7
|
+
readonly dockerAvailable: boolean;
|
|
8
|
+
readonly browserLaunch: boolean;
|
|
9
|
+
readonly testPostgresSuperuser: boolean | null;
|
|
10
|
+
}
|
|
11
|
+
export type HostRequirementsCheck = (requires: HostRuntimeRequirements | null | undefined) => readonly string[];
|
|
12
|
+
/**
|
|
13
|
+
* Reasons this host fails a host-mode attempt's declared requirements. The API filters on
|
|
14
|
+
* stored requirements; this recheck closes the gap when they were not reported yet or the
|
|
15
|
+
* attempt's contract differs from the probed one. Mirrors the API's wording.
|
|
16
|
+
*/
|
|
17
|
+
export declare function unmetHostRuntimeRequirements(requires: HostRuntimeRequirements | null | undefined, facts: HostRequirementFacts): readonly string[];
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
const gib = 1024 * 1024 * 1024;
|
|
2
|
+
/**
|
|
3
|
+
* Reasons this host fails a host-mode attempt's declared requirements. The API filters on
|
|
4
|
+
* stored requirements; this recheck closes the gap when they were not reported yet or the
|
|
5
|
+
* attempt's contract differs from the probed one. Mirrors the API's wording.
|
|
6
|
+
*/
|
|
7
|
+
export function unmetHostRuntimeRequirements(requires, facts) {
|
|
8
|
+
if (!requires)
|
|
9
|
+
return [];
|
|
10
|
+
const unmet = [];
|
|
11
|
+
if (requires.minThreads !== null && facts.logicalThreads < requires.minThreads) {
|
|
12
|
+
unmet.push(`needs ≥ ${requires.minThreads} threads; this host has ${facts.logicalThreads}`);
|
|
13
|
+
}
|
|
14
|
+
if (requires.minMemoryGiB !== null && facts.totalMemoryBytes / gib < requires.minMemoryGiB) {
|
|
15
|
+
unmet.push(`needs ≥ ${requires.minMemoryGiB} GiB; this host has ${(Math.floor(facts.totalMemoryBytes / gib * 100) / 100)}`);
|
|
16
|
+
}
|
|
17
|
+
const available = new Set(facts.availableToolchains.map(name => name.toLowerCase()));
|
|
18
|
+
const missing = requires.toolchains.filter(name => !available.has(name));
|
|
19
|
+
if (missing.length > 0)
|
|
20
|
+
unmet.push(`needs ${missing.join(", ")}; this host does not have ${missing.length === 1 ? "it" : "them"}`);
|
|
21
|
+
if (requires.docker && !facts.dockerAvailable)
|
|
22
|
+
unmet.push("needs Docker; this host does not have it");
|
|
23
|
+
if (requires.testPostgres?.superuser && !facts.dockerAvailable && facts.testPostgresSuperuser !== true) {
|
|
24
|
+
unmet.push("needs Docker or a superuser test database; this host has neither");
|
|
25
|
+
}
|
|
26
|
+
if (requires.playwright && !facts.browserLaunch)
|
|
27
|
+
unmet.push("needs Playwright browsers; this host cannot launch them");
|
|
28
|
+
return unmet;
|
|
29
|
+
}
|