@loucompanion/forge-bridge 0.1.4-dev.e83e5bc6ecce → 0.1.4-dev.f22f5e3d01fe
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 +55 -0
- package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
- package/dist/bridge/bridge-chat-provider-command.js +125 -0
- package/dist/bridge/bridge.base.d.ts +9 -0
- package/dist/bridge/bridge.service.d.ts +71 -2
- package/dist/bridge/bridge.service.js +282 -114
- package/dist/bridge/bridge.types.d.ts +11 -0
- package/dist/bridge/local-yield-flag.d.ts +6 -0
- package/dist/bridge/local-yield-flag.js +34 -0
- package/dist/bridge/runner-host-capabilities.d.ts +3 -0
- package/dist/bridge/runner-host-capabilities.js +13 -0
- package/dist/cli/cli.help.js +18 -0
- package/dist/cli/cli.service.d.ts +16 -0
- package/dist/cli/cli.service.js +132 -14
- package/dist/cli/local-config.d.ts +4 -0
- package/dist/cli/local-config.js +26 -4
- package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
- package/dist/runtime/host-facts.d.ts +2 -1
- package/dist/runtime/host-load-admission.d.ts +18 -3
- package/dist/runtime/host-load-admission.js +19 -4
- package/dist/runtime/host-load-child-environment.d.ts +11 -6
- package/dist/runtime/host-load-child-environment.js +22 -11
- package/dist/runtime/host-load-governor-config.d.ts +19 -1
- package/dist/runtime/host-load-governor-config.js +37 -0
- package/dist/runtime/host-load-governor.d.ts +12 -0
- package/dist/runtime/host-load-governor.js +139 -26
- 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 +26 -3
- package/dist/runtime/host-load-sampler.js +61 -2
- package/dist/runtime/host-load-step-class.d.ts +3 -1
- package/dist/runtime/host-load-step-class.js +60 -5
- package/dist/runtime/host-load-test-slot.d.ts +43 -0
- package/dist/runtime/host-load-test-slot.js +81 -0
- package/dist/runtime/host-load-token-ledger.d.ts +26 -0
- package/dist/runtime/host-load-token-ledger.js +93 -61
- package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
- package/dist/runtime/host-load-windows-cpu.js +85 -0
- package/dist/runtime/host-runtime-lease.d.ts +59 -3
- package/dist/runtime/host-runtime-lease.js +199 -8
- package/dist/runtime/host-runtime-promotion.d.ts +23 -0
- package/dist/runtime/host-runtime-promotion.js +36 -0
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
- package/dist/runtime/runner-settings.d.ts +100 -0
- package/dist/runtime/runner-settings.js +214 -0
- package/dist/sandbox/host-capacity-broker.d.ts +7 -1
- package/dist/sandbox/host-capacity-broker.js +23 -4
- package/dist/session/architect-waits.d.ts +2 -0
- package/dist/session/architect-waits.js +138 -0
- package/dist/session/managed-attempt-tools.js +8 -9
- package/dist/session/managed-command-host-load.d.ts +2 -0
- package/dist/session/managed-command-host-load.js +2 -1
- package/dist/session/phase-completion.schemas.js +25 -23
- package/dist/session/phase-completion.validation.js +3 -1
- package/dist/session/pre-publication-pass.d.ts +61 -0
- package/dist/session/pre-publication-pass.js +148 -0
- package/dist/session/pre-publication-validation.d.ts +23 -11
- package/dist/session/pre-publication-validation.js +178 -107
- package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
- package/dist/session/provider-cli/claude-background-work.js +180 -0
- package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
- package/dist/session/provider-cli/pre-publication-repair.js +243 -0
- package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
- package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +13 -22
- package/dist/session/provider-cli/provider-cli.process.js +36 -337
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +2 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +49 -9
- package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
- package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
- package/dist/session/provider-cli/provider-cli.service.js +74 -151
- package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
- package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
- package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
- package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
- package/dist/session/provider-cli/provider-output-pipes.js +67 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
- package/dist/session/provider-cli/provider-output-state.js +6 -0
- package/dist/session/sandbox-host-capacity-gate.js +12 -3
- package/dist/session/session.base.d.ts +6 -1
- package/dist/session/session.service.d.ts +7 -2
- package/dist/session/session.service.js +100 -2
- package/dist/session/session.types.js +3 -3
- package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
- package/dist/session/workspace-runtime-fingerprint.js +138 -0
- package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
- package/dist/shared/process/windows-app-execution-alias.js +45 -0
- package/dist/shared/process/windows-launch.d.ts +18 -0
- package/dist/shared/process/windows-launch.js +68 -0
- package/dist/shared/provider-capabilities.js +5 -6
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host CPU use at which the estimate starts to report pressure. Waits for a CPU
|
|
3
|
+
* are rare below it on a many-core host. 0.6 puts the default backpressure
|
|
4
|
+
* threshold (50%) at 80% host CPU use, the default CPU budget.
|
|
5
|
+
*/
|
|
6
|
+
export const windowsCpuPressureKnee = 0.6;
|
|
7
|
+
/** Busy is user + nice + sys + irq; idle is not busy. Null when any CPU lacks its times. */
|
|
8
|
+
export function cpuTimeTotals(cpus) {
|
|
9
|
+
if (cpus.length === 0)
|
|
10
|
+
return null;
|
|
11
|
+
let busyMs = 0;
|
|
12
|
+
let idleMs = 0;
|
|
13
|
+
for (const cpu of cpus) {
|
|
14
|
+
const times = cpu.times;
|
|
15
|
+
if (!times)
|
|
16
|
+
return null;
|
|
17
|
+
const values = [times.user, times.nice, times.sys, times.irq, times.idle];
|
|
18
|
+
if (!values.every(value => Number.isFinite(value) && value >= 0))
|
|
19
|
+
return null;
|
|
20
|
+
busyMs += times.user + times.nice + times.sys + times.irq;
|
|
21
|
+
idleMs += times.idle;
|
|
22
|
+
}
|
|
23
|
+
return { busyMs, totalMs: busyMs + idleMs, cpuCount: cpus.length };
|
|
24
|
+
}
|
|
25
|
+
/** Busy share of all logical CPUs (0-1) between two readings; null across a CPU count change or a counter reset. */
|
|
26
|
+
export function cpuUtilisation(previous, current) {
|
|
27
|
+
if (!previous || !current || previous.cpuCount !== current.cpuCount)
|
|
28
|
+
return null;
|
|
29
|
+
const totalDelta = current.totalMs - previous.totalMs;
|
|
30
|
+
const busyDelta = current.busyMs - previous.busyMs;
|
|
31
|
+
if (totalDelta <= 0 || busyDelta < 0)
|
|
32
|
+
return null;
|
|
33
|
+
return Math.min(1, busyDelta / totalDelta);
|
|
34
|
+
}
|
|
35
|
+
/** Estimated share of wall time (percent) some runnable thread waited for a CPU, for one window. */
|
|
36
|
+
export function estimatedCpuStallPercent(utilisation) {
|
|
37
|
+
const share = (utilisation - windowsCpuPressureKnee) / (1 - windowsCpuPressureKnee);
|
|
38
|
+
return Math.min(1, Math.max(0, share)) * 100;
|
|
39
|
+
}
|
|
40
|
+
const averageWindowsSeconds = { avg10: 10, avg60: 60, avg300: 300 };
|
|
41
|
+
/**
|
|
42
|
+
* Keeps 10/60/300-second exponentially decaying averages of the estimate, the
|
|
43
|
+
* way the kernel keeps PSI averages, so the governor's threshold and pressure
|
|
44
|
+
* streak read it exactly like PSI. The first window seeds every average, so a
|
|
45
|
+
* host already busy when the bridge starts reports pressure at once.
|
|
46
|
+
*/
|
|
47
|
+
export class WindowsCpuPressureEstimator {
|
|
48
|
+
averages = null;
|
|
49
|
+
/** Folds in one window of host CPU use lasting `elapsedMs`. */
|
|
50
|
+
update(utilisation, elapsedMs) {
|
|
51
|
+
const stall = estimatedCpuStallPercent(utilisation);
|
|
52
|
+
const previous = this.averages;
|
|
53
|
+
this.averages = previous === null
|
|
54
|
+
? { avg10: stall, avg60: stall, avg300: stall }
|
|
55
|
+
: {
|
|
56
|
+
avg10: decay(previous.avg10, stall, elapsedMs, averageWindowsSeconds.avg10),
|
|
57
|
+
avg60: decay(previous.avg60, stall, elapsedMs, averageWindowsSeconds.avg60),
|
|
58
|
+
avg300: decay(previous.avg300, stall, elapsedMs, averageWindowsSeconds.avg300),
|
|
59
|
+
};
|
|
60
|
+
return this.current();
|
|
61
|
+
}
|
|
62
|
+
current() {
|
|
63
|
+
if (!this.averages)
|
|
64
|
+
return null;
|
|
65
|
+
return {
|
|
66
|
+
some: {
|
|
67
|
+
avg10: roundPercent(this.averages.avg10),
|
|
68
|
+
avg60: roundPercent(this.averages.avg60),
|
|
69
|
+
avg300: roundPercent(this.averages.avg300),
|
|
70
|
+
},
|
|
71
|
+
// `full` (every runnable thread stalled) is not meaningful for CPU and is not estimated.
|
|
72
|
+
full: null,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
reset() {
|
|
76
|
+
this.averages = null;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function decay(previous, sample, elapsedMs, windowSeconds) {
|
|
80
|
+
const weight = Math.exp(-Math.max(0, elapsedMs) / (windowSeconds * 1_000));
|
|
81
|
+
return sample + (previous - sample) * weight;
|
|
82
|
+
}
|
|
83
|
+
function roundPercent(value) {
|
|
84
|
+
return Math.round(value * 100) / 100;
|
|
85
|
+
}
|
|
@@ -15,6 +15,7 @@ import { HostParallelPromotionStore } from "./host-runtime-promotion.js";
|
|
|
15
15
|
import { type HostProcessRecovery } from "../shared/process/host-process-recovery.js";
|
|
16
16
|
import { HostLoadGovernor } from "./host-load-governor.js";
|
|
17
17
|
import { type HostLoadGovernorSource } from "./host-load-sampler.js";
|
|
18
|
+
import type { RunnerHostDefaults } from "./runner-settings.js";
|
|
18
19
|
export interface HostRuntimeLeaseStart {
|
|
19
20
|
readonly lease: RuntimeIsolationLease;
|
|
20
21
|
readonly environment: Readonly<Record<string, string>>;
|
|
@@ -28,7 +29,7 @@ export interface HostRuntimeAdmissionCheckpoint {
|
|
|
28
29
|
}
|
|
29
30
|
export type HostRuntimeAdmissionCheckpointHandler = (checkpoint: HostRuntimeAdmissionCheckpoint) => void | Promise<void>;
|
|
30
31
|
export interface HostRuntimeProjectCheckpoint {
|
|
31
|
-
readonly code: "host_runtime_build_started" | "host_runtime_build_waiting_for_host_capacity" | "host_runtime_build_cached" | "host_runtime_build_completed" | "host_runtime_database_provisioned";
|
|
32
|
+
readonly code: "host_runtime_build_started" | "host_runtime_build_waiting_for_host_capacity" | "host_runtime_build_cached" | "host_runtime_build_completed" | "host_runtime_database_provisioned" | "host_runtime_contract_readmitted";
|
|
32
33
|
readonly message: string;
|
|
33
34
|
readonly data?: Readonly<Record<string, unknown>>;
|
|
34
35
|
}
|
|
@@ -96,10 +97,20 @@ export interface HostNodeRuntimeLaunch<T> extends NodeRuntimeAdapterLaunch<T> {
|
|
|
96
97
|
}
|
|
97
98
|
export interface HostRuntimeLeaseRuntime {
|
|
98
99
|
setRequirementsCheck?(check: HostRequirementsCheck | null): void;
|
|
100
|
+
/** Decision 0014: today's max attempts and memory reserve defaults, before env bounds. */
|
|
101
|
+
capacityLimitDefaults?(): RunnerHostDefaults;
|
|
102
|
+
/** Decision 0014: the effective max attempts and memory reserve, from the next attempt admission. */
|
|
103
|
+
applyCapacityLimits?(limits: HostCapacityLimits): void;
|
|
99
104
|
acquirePreparation?(dispatch: RunOnceDispatchPacket, signal?: AbortSignal): Promise<readonly string[]>;
|
|
100
105
|
acquire(dispatch: RunOnceDispatchPacket, signal?: AbortSignal): Promise<readonly string[]>;
|
|
101
106
|
start(dispatch: RunOnceDispatchPacket, worktreePath: string, signal?: AbortSignal, onAdmissionCheckpoint?: HostRuntimeAdmissionCheckpointHandler): Promise<HostRuntimeLeaseStart>;
|
|
102
107
|
startConfiguredProject(dispatchAttemptId: string, fencingToken: string, signal?: AbortSignal, onProjectCheckpoint?: HostRuntimeProjectCheckpointHandler): Promise<HostRuntimeLeaseStart>;
|
|
108
|
+
/**
|
|
109
|
+
* Stops the attempt's configured project processes, releases their ports, and
|
|
110
|
+
* starts them again (rebuilding when sources changed) so the stack serves the
|
|
111
|
+
* current workspace. Returns the environment with the newly assigned URLs.
|
|
112
|
+
*/
|
|
113
|
+
restartConfiguredProject?(dispatchAttemptId: string, fencingToken: string, signal?: AbortSignal, onProjectCheckpoint?: HostRuntimeProjectCheckpointHandler): Promise<HostRuntimeLeaseStart>;
|
|
103
114
|
updateLease(dispatchAttemptId: string, fencingToken: string, expiresAt: string): Promise<void>;
|
|
104
115
|
providerProcessRunner?(dispatchAttemptId: string, fencingToken: string): ProviderProcessRunner | null;
|
|
105
116
|
providerMemoryTelemetry?(dispatchAttemptId: string, fencingToken: string): AttemptProcessTreeMemoryTelemetry | null;
|
|
@@ -147,15 +158,25 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
|
|
|
147
158
|
private workspaceAvailableBytes;
|
|
148
159
|
private readonly portBroker;
|
|
149
160
|
private readonly nodeAdapter;
|
|
150
|
-
|
|
161
|
+
/** Rebuilt by applyCapacityLimits (decision 0014); every admission reads the current one. */
|
|
162
|
+
private capacityConfiguration;
|
|
151
163
|
private readonly memoryAvailability;
|
|
152
164
|
private readonly executionRoot;
|
|
153
|
-
/** Host-wide admission for heavy steps (
|
|
165
|
+
/** Host-wide admission for heavy steps (decisions 0013, 0018): the host test slot, and the budget when on. */
|
|
154
166
|
readonly hostLoadGovernor: HostLoadGovernor;
|
|
155
167
|
private requirementsCheck;
|
|
156
168
|
/** Installs the decision 0013 accept-time requirements recheck for host attempts. */
|
|
157
169
|
setRequirementsCheck(check: HostRequirementsCheck | null): void;
|
|
158
170
|
constructor(stateRoot: string, portBroker?: HostPortBroker, nodeAdapter?: NodeHostRuntimeAdapter, processSupervisors?: AttemptProcessSupervisorRegistry, processRunner?: ProviderProcessRunner, listenerInspector?: HostListenerInspector, promotionStore?: HostParallelPromotionStore, playwrightAdapter?: PlaywrightHostRuntimeAdapter, processRecovery?: HostProcessRecovery, capacityResourceSample?: HostCapacityResourceSample | undefined, executionRoot?: string, databaseBroker?: AttemptDatabaseBroker | null, hostLoad?: HostLoadGovernorSource | null);
|
|
171
|
+
/** Today's defaults for the limits the server can push, before any env bound (decision 0014). */
|
|
172
|
+
capacityLimitDefaults(): RunnerHostDefaults;
|
|
173
|
+
/**
|
|
174
|
+
* Decision 0014: the bridge's effective max attempts and memory reserve. They
|
|
175
|
+
* apply from the next attempt admission; admitted attempts keep their
|
|
176
|
+
* reservations and are never preempted, even when the new limit is lower than
|
|
177
|
+
* what already runs. The idle reserve follows the reserve as at startup.
|
|
178
|
+
*/
|
|
179
|
+
applyCapacityLimits(limits: HostCapacityLimits): void;
|
|
159
180
|
hostLoadChildEnvironment(): Readonly<Record<string, string>>;
|
|
160
181
|
reap(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport>;
|
|
161
182
|
snapshot(): HostRuntimeCapacitySnapshot;
|
|
@@ -178,6 +199,24 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
|
|
|
178
199
|
start(dispatch: RunOnceDispatchPacket, worktreePath: string, signal?: AbortSignal, onAdmissionCheckpoint?: HostRuntimeAdmissionCheckpointHandler): Promise<HostRuntimeLeaseStart>;
|
|
179
200
|
updateLease(dispatchAttemptId: string, fencingToken: string, expiresAt: string): Promise<void>;
|
|
180
201
|
startConfiguredProject(dispatchAttemptId: string, fencingToken: string, signal?: AbortSignal, onProjectCheckpoint?: HostRuntimeProjectCheckpointHandler): Promise<HostRuntimeLeaseStart>;
|
|
202
|
+
/**
|
|
203
|
+
* Launches the configured project. Only the first launch, from the admitted commit's clean
|
|
204
|
+
* source, may record parallel-safety proof: a restart serves the workspace after the provider
|
|
205
|
+
* edited it, and a proof observed there would be stored under the admitted commit and could
|
|
206
|
+
* move this or a later attempt at that commit into shared admission for source it never ran.
|
|
207
|
+
*/
|
|
208
|
+
private launchConfiguredProject;
|
|
209
|
+
/**
|
|
210
|
+
* Relaunches the configured project so it serves the current workspace. Every
|
|
211
|
+
* configured process stops (the API port changes, so the dev server's proxy target
|
|
212
|
+
* must change with it), its port reservation is released and dropped from the
|
|
213
|
+
* persisted lease, and the regular start path runs again, including the ASP.NET
|
|
214
|
+
* prebuild, whose receipt rebuilds only when the sources changed.
|
|
215
|
+
*/
|
|
216
|
+
restartConfiguredProject(dispatchAttemptId: string, fencingToken: string, signal?: AbortSignal, onProjectCheckpoint?: HostRuntimeProjectCheckpointHandler): Promise<HostRuntimeLeaseStart>;
|
|
217
|
+
private runConfiguredProjectRestart;
|
|
218
|
+
/** Stops configured project processes in reverse launch order and releases their ports. */
|
|
219
|
+
private stopConfiguredProject;
|
|
181
220
|
providerProcessRunner(dispatchAttemptId: string, fencingToken: string): ProviderProcessRunner | null;
|
|
182
221
|
private markCapacityReservationRunning;
|
|
183
222
|
providerMemoryTelemetry(dispatchAttemptId: string, fencingToken: string): AttemptProcessTreeMemoryTelemetry | null;
|
|
@@ -228,4 +267,21 @@ export declare class HostRuntimeCapacityRequestImpossibleError extends Error {
|
|
|
228
267
|
}
|
|
229
268
|
export declare function hostRuntimeEventResources(lease: RuntimeIsolationLease, runtimeContract?: LoadedHostRuntimeContract, executionClass?: HostRuntimeExecutionClass): Record<string, unknown>;
|
|
230
269
|
export declare function hostRuntimeSingletonKeys(dispatch: RunOnceDispatchPacket): readonly string[];
|
|
270
|
+
/**
|
|
271
|
+
* Every environment key `hostRuntimeEnvironment` and the Playwright overlay derive from the
|
|
272
|
+
* configured project's assigned ports. They name a live stack, so they are withheld while the
|
|
273
|
+
* stack is down: after its ports are released another attempt may be assigned them.
|
|
274
|
+
*/
|
|
275
|
+
export declare function hostRuntimeStackEnvironmentKeys(runtimeContract: LoadedHostRuntimeContract): readonly string[];
|
|
231
276
|
export declare function runtimeAdmissionPriority(dispatch: RunOnceDispatchPacket): HostRuntimeAdmissionPriority;
|
|
277
|
+
/** The pushed attempt limits (decision 0014), already resolved against host env bounds. */
|
|
278
|
+
export interface HostCapacityLimits {
|
|
279
|
+
readonly maxConcurrentAttempts: number;
|
|
280
|
+
readonly memoryReserveBytes: number;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Today's max attempts and adaptive memory reserve for this host, before
|
|
284
|
+
* FORGE_HOST_MAX_CONCURRENT_ATTEMPTS and FORGE_HOST_MEMORY_RESERVE_BYTES
|
|
285
|
+
* (decision 0014 treats those as bounds on the server's values).
|
|
286
|
+
*/
|
|
287
|
+
export declare function hostCapacityLimitDefaults(capacityResourceSample?: HostCapacityResourceSample): RunnerHostDefaults;
|
|
@@ -23,7 +23,7 @@ import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
|
|
|
23
23
|
import { HostListenerInspector } from "./host-listener-inspector.js";
|
|
24
24
|
import { RecoveryStabilizedMemory, buildMemoryAdmissionDiagnostics, resolveAdaptiveMemoryReserveBytes, } from "./memory-capacity.js";
|
|
25
25
|
import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
|
|
26
|
-
import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "./host-runtime-promotion.js";
|
|
26
|
+
import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, readmitHostRuntimeContract, } from "./host-runtime-promotion.js";
|
|
27
27
|
import { ExactHostProcessRecovery, } from "../shared/process/host-process-recovery.js";
|
|
28
28
|
import { resetGeneratedOutputs } from "./generated-output-reset.js";
|
|
29
29
|
import { assertCanonicalDirectory, createCanonicalDirectory } from "./attempt-private-directory.js";
|
|
@@ -67,10 +67,11 @@ export class HostRuntimeLeaseManager {
|
|
|
67
67
|
workspaceAvailableBytes = Number.MAX_SAFE_INTEGER;
|
|
68
68
|
portBroker;
|
|
69
69
|
nodeAdapter;
|
|
70
|
+
/** Rebuilt by applyCapacityLimits (decision 0014); every admission reads the current one. */
|
|
70
71
|
capacityConfiguration;
|
|
71
72
|
memoryAvailability;
|
|
72
73
|
executionRoot;
|
|
73
|
-
/** Host-wide admission for heavy steps (
|
|
74
|
+
/** Host-wide admission for heavy steps (decisions 0013, 0018): the host test slot, and the budget when on. */
|
|
74
75
|
hostLoadGovernor;
|
|
75
76
|
requirementsCheck = null;
|
|
76
77
|
/** Installs the decision 0013 accept-time requirements recheck for host attempts. */
|
|
@@ -97,6 +98,34 @@ export class HostRuntimeLeaseManager {
|
|
|
97
98
|
this.capacityConfiguration = loadHostCapacityConfiguration(capacityResourceSample);
|
|
98
99
|
this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
|
|
99
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
|
+
}
|
|
100
129
|
hostLoadChildEnvironment() {
|
|
101
130
|
return this.hostLoadGovernor.enabled ? hostLoadChildEnvironment(this.stateRoot) : {};
|
|
102
131
|
}
|
|
@@ -1122,6 +1151,8 @@ export class HostRuntimeLeaseManager {
|
|
|
1122
1151
|
parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract) && dispatch.cycleRun.phase !== "prepared_readiness",
|
|
1123
1152
|
processSupervisor,
|
|
1124
1153
|
adapterCleanups: [],
|
|
1154
|
+
adapterCleanupsByPort: new Map(),
|
|
1155
|
+
restartingConfiguredProject: false,
|
|
1125
1156
|
pendingAdapterLaunches: new Map(),
|
|
1126
1157
|
runtimeResourcesReleased: false,
|
|
1127
1158
|
releasing: false,
|
|
@@ -1184,6 +1215,15 @@ export class HostRuntimeLeaseManager {
|
|
|
1184
1215
|
await this.writeLedger(renewed);
|
|
1185
1216
|
}
|
|
1186
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) {
|
|
1187
1227
|
const active = this.active.get(dispatchAttemptId);
|
|
1188
1228
|
if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
|
|
1189
1229
|
throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
|
|
@@ -1304,7 +1344,7 @@ export class HostRuntimeLeaseManager {
|
|
|
1304
1344
|
},
|
|
1305
1345
|
}, launcher, signal);
|
|
1306
1346
|
}
|
|
1307
|
-
const promotedLease = await this.promoteVerifiedRuntime(active, active.lease);
|
|
1347
|
+
const promotedLease = promote ? await this.promoteVerifiedRuntime(active, active.lease) : active.lease;
|
|
1308
1348
|
const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass, active.databaseCapability);
|
|
1309
1349
|
const playwright = active.runtimeContract.contract.runtime.playwright;
|
|
1310
1350
|
if (!playwright) {
|
|
@@ -1343,6 +1383,94 @@ export class HostRuntimeLeaseManager {
|
|
|
1343
1383
|
executionClass: active.executionClass,
|
|
1344
1384
|
};
|
|
1345
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 keeps the admission granted at start. A workspace contract that changed only its
|
|
1422
|
+
// launch environment is adopted; any other change throws host_runtime_contract_changed.
|
|
1423
|
+
const readmitted = readmitHostRuntimeContract(active, await loadHostRuntimeContract(active.lease.worktreePath));
|
|
1424
|
+
active.runtimeContract = readmitted.runtimeContract;
|
|
1425
|
+
active.runtimeContractFingerprint = readmitted.runtimeContractFingerprint;
|
|
1426
|
+
if (readmitted.changed) {
|
|
1427
|
+
await onProjectCheckpoint?.({ code: "host_runtime_contract_readmitted", message: "The workspace's runtime contract changed only its launch environment; the restart runs it under the admission granted at start." });
|
|
1428
|
+
}
|
|
1429
|
+
const portNames = active.executionClass === "analysis_only" ? [] : configuredLaunchPortNames(active.runtimeContract);
|
|
1430
|
+
const pendingPort = portNames.find(name => active.pendingAdapterLaunches.has(name));
|
|
1431
|
+
if (pendingPort) {
|
|
1432
|
+
throw new Error(`host_runtime_project_conflict: configured port '${pendingPort}' is still launching.`);
|
|
1433
|
+
}
|
|
1434
|
+
const temporaryDirectory = active.lease.resources.paths.find(entry => entry.role === "temporary")?.path;
|
|
1435
|
+
if (active.runtimeContract.contract.runtime.playwright && temporaryDirectory) {
|
|
1436
|
+
// The generated Playwright config targets the stack being stopped. If the restart fails, no
|
|
1437
|
+
// config may be left pointing at ports another attempt can now be assigned.
|
|
1438
|
+
await this.playwrightAdapter.discardOverlay(temporaryDirectory);
|
|
1439
|
+
}
|
|
1440
|
+
await this.stopConfiguredProject(active, portNames);
|
|
1441
|
+
// Keeps whatever admission the attempt holds; see launchConfiguredProject.
|
|
1442
|
+
const restarted = await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, false);
|
|
1443
|
+
if (active.releasing) {
|
|
1444
|
+
throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
|
|
1445
|
+
}
|
|
1446
|
+
return restarted;
|
|
1447
|
+
}
|
|
1448
|
+
/** Stops configured project processes in reverse launch order and releases their ports. */
|
|
1449
|
+
async stopConfiguredProject(active, portNames) {
|
|
1450
|
+
const launched = active.lease.resources.ports
|
|
1451
|
+
.map(port => port.name)
|
|
1452
|
+
.filter(name => portNames.includes(name))
|
|
1453
|
+
.reverse();
|
|
1454
|
+
for (const name of launched) {
|
|
1455
|
+
if (active.releasing) {
|
|
1456
|
+
throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
|
|
1457
|
+
}
|
|
1458
|
+
const cleanup = active.adapterCleanupsByPort.get(name);
|
|
1459
|
+
if (!cleanup) {
|
|
1460
|
+
throw new Error(`host_runtime_project_restart_unavailable: configured port '${name}' has no supervised process to stop.`);
|
|
1461
|
+
}
|
|
1462
|
+
// A failed stop keeps the cleanup and the port record for the fenced release retry.
|
|
1463
|
+
await cleanup();
|
|
1464
|
+
removeCleanup(active.adapterCleanups, cleanup);
|
|
1465
|
+
active.adapterCleanupsByPort.delete(name);
|
|
1466
|
+
const runtimeLease = withRuntimeIsolationResources(active.lease, {
|
|
1467
|
+
...active.lease.resources,
|
|
1468
|
+
ports: active.lease.resources.ports.filter(port => port.name !== name),
|
|
1469
|
+
});
|
|
1470
|
+
await this.writeLedger(runtimeLease);
|
|
1471
|
+
active.lease = runtimeLease;
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1346
1474
|
providerProcessRunner(dispatchAttemptId, fencingToken) {
|
|
1347
1475
|
const active = this.active.get(dispatchAttemptId);
|
|
1348
1476
|
if (!active || active.lease.fencingToken !== fencingToken || active.releasing)
|
|
@@ -1430,6 +1558,7 @@ export class HostRuntimeLeaseManager {
|
|
|
1430
1558
|
unlinkAbortController(controller, signal);
|
|
1431
1559
|
};
|
|
1432
1560
|
active.adapterCleanups.push(cleanup);
|
|
1561
|
+
active.adapterCleanupsByPort.set(portName, cleanup);
|
|
1433
1562
|
try {
|
|
1434
1563
|
if (active.releasing)
|
|
1435
1564
|
throw new Error("host_runtime_adapter_cancelled: host runtime release started during launch.");
|
|
@@ -1452,6 +1581,8 @@ export class HostRuntimeLeaseManager {
|
|
|
1452
1581
|
try {
|
|
1453
1582
|
await cleanup();
|
|
1454
1583
|
removeCleanup(active.adapterCleanups, cleanup);
|
|
1584
|
+
if (active.adapterCleanupsByPort.get(portName) === cleanup)
|
|
1585
|
+
active.adapterCleanupsByPort.delete(portName);
|
|
1455
1586
|
}
|
|
1456
1587
|
catch {
|
|
1457
1588
|
// Preserve the cleanup and broker claim for the fenced release retry.
|
|
@@ -1497,6 +1628,11 @@ export class HostRuntimeLeaseManager {
|
|
|
1497
1628
|
pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
|
|
1498
1629
|
}
|
|
1499
1630
|
await Promise.allSettled([...active.pendingAdapterLaunches.values()].map(pending => pending.promise));
|
|
1631
|
+
const restart = active.configuredProjectRestart;
|
|
1632
|
+
if (restart) {
|
|
1633
|
+
restart.controller.abort("Host runtime release cancelled the configured project restart.");
|
|
1634
|
+
await restart.promise.catch(() => undefined);
|
|
1635
|
+
}
|
|
1500
1636
|
await active.databaseProvision?.catch(() => undefined);
|
|
1501
1637
|
let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
|
|
1502
1638
|
active.lease = releasing;
|
|
@@ -1514,6 +1650,7 @@ export class HostRuntimeLeaseManager {
|
|
|
1514
1650
|
// validation step whose termination failed earlier) return their tokens now.
|
|
1515
1651
|
await this.hostLoadGovernor.releaseRetainedAfterTeardown(dispatchAttemptId).catch(() => undefined);
|
|
1516
1652
|
await releaseAdapterResources(active.adapterCleanups);
|
|
1653
|
+
active.adapterCleanupsByPort.clear();
|
|
1517
1654
|
if (active.databaseCapability && this.databaseBroker) {
|
|
1518
1655
|
// A database the broker cannot drop now is reaped later; it must not hold host capacity.
|
|
1519
1656
|
await this.databaseBroker.release(dispatchAttemptId, fencingToken).catch(() => "retained");
|
|
@@ -2213,6 +2350,30 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
|
|
|
2213
2350
|
environment.FORGE_BASE_URL = resolvedBaseUrls[0];
|
|
2214
2351
|
return environment;
|
|
2215
2352
|
}
|
|
2353
|
+
/**
|
|
2354
|
+
* Every environment key `hostRuntimeEnvironment` and the Playwright overlay derive from the
|
|
2355
|
+
* configured project's assigned ports. They name a live stack, so they are withheld while the
|
|
2356
|
+
* stack is down: after its ports are released another attempt may be assigned them.
|
|
2357
|
+
*/
|
|
2358
|
+
export function hostRuntimeStackEnvironmentKeys(runtimeContract) {
|
|
2359
|
+
const keys = new Set([
|
|
2360
|
+
"FORGE_E2E_API_URL",
|
|
2361
|
+
"FORGE_E2E_WEB_URL",
|
|
2362
|
+
"FORGE_BASE_URL",
|
|
2363
|
+
"FORGE_PLAYWRIGHT_BASE_URL",
|
|
2364
|
+
// The generated Playwright config embeds the base URL.
|
|
2365
|
+
"FORGE_PLAYWRIGHT_CONFIG",
|
|
2366
|
+
]);
|
|
2367
|
+
for (const port of runtimeContract.contract.runtime.ports) {
|
|
2368
|
+
const normalizedName = port.name.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_");
|
|
2369
|
+
keys.add(port.env);
|
|
2370
|
+
if (port.baseUrlEnv)
|
|
2371
|
+
keys.add(port.baseUrlEnv);
|
|
2372
|
+
keys.add(`FORGE_${normalizedName}_PORT`);
|
|
2373
|
+
keys.add(`FORGE_${normalizedName}_URL`);
|
|
2374
|
+
}
|
|
2375
|
+
return [...keys];
|
|
2376
|
+
}
|
|
2216
2377
|
function anySignal(...signals) {
|
|
2217
2378
|
return AbortSignal.any(signals.filter((signal) => signal !== undefined));
|
|
2218
2379
|
}
|
|
@@ -2358,6 +2519,18 @@ function configuredInteger(name, fallback, minimum, maximum) {
|
|
|
2358
2519
|
const parsed = Number.parseInt(process.env[name] ?? "", 10);
|
|
2359
2520
|
return Number.isFinite(parsed) ? Math.max(minimum, Math.min(maximum, parsed)) : fallback;
|
|
2360
2521
|
}
|
|
2522
|
+
/**
|
|
2523
|
+
* Today's max attempts and adaptive memory reserve for this host, before
|
|
2524
|
+
* FORGE_HOST_MAX_CONCURRENT_ATTEMPTS and FORGE_HOST_MEMORY_RESERVE_BYTES
|
|
2525
|
+
* (decision 0014 treats those as bounds on the server's values).
|
|
2526
|
+
*/
|
|
2527
|
+
export function hostCapacityLimitDefaults(capacityResourceSample) {
|
|
2528
|
+
const configuration = loadHostCapacityConfiguration(capacityResourceSample);
|
|
2529
|
+
return {
|
|
2530
|
+
maxConcurrentAttempts: configuration.defaultHardMaxAttempts,
|
|
2531
|
+
memoryReserveBytes: configuration.adaptiveHostReserveBytes,
|
|
2532
|
+
};
|
|
2533
|
+
}
|
|
2361
2534
|
function loadHostCapacityConfiguration(capacityResourceSample) {
|
|
2362
2535
|
const sampledCpuCount = capacityResourceSample
|
|
2363
2536
|
? Math.max(1, Math.floor(capacityResourceSample.totalCpuMillis / 1_000))
|
|
@@ -2365,23 +2538,41 @@ function loadHostCapacityConfiguration(capacityResourceSample) {
|
|
|
2365
2538
|
const totalMemoryBytes = capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
|
|
2366
2539
|
const reserveFloorBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_FLOOR_BYTES", 1024 ** 3, 512 * 1024 ** 2, 128 * 1024 ** 3);
|
|
2367
2540
|
const reserveCeilingBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_CEILING_BYTES", 4 * 1024 ** 3, reserveFloorBytes, 128 * 1024 ** 3);
|
|
2368
|
-
const
|
|
2369
|
-
explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
|
|
2541
|
+
const adaptiveOptions = {
|
|
2370
2542
|
floorBytes: reserveFloorBytes,
|
|
2371
2543
|
ceilingBytes: reserveCeilingBytes,
|
|
2372
2544
|
percent: configuredNumber("FORGE_HOST_MEMORY_RESERVE_PERCENT", 12.5, 1, 50),
|
|
2545
|
+
};
|
|
2546
|
+
const hostReserveBytes = resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, {
|
|
2547
|
+
...adaptiveOptions,
|
|
2548
|
+
explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
|
|
2373
2549
|
});
|
|
2374
|
-
const
|
|
2550
|
+
const defaultHardMaxAttempts = Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2)));
|
|
2551
|
+
const idleReserveOverride = Number.parseInt(process.env.FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES ?? "", 10);
|
|
2552
|
+
const idleReserveOverrideBytes = Number.isFinite(idleReserveOverride) ? idleReserveOverride : null;
|
|
2375
2553
|
return {
|
|
2376
|
-
hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS",
|
|
2554
|
+
hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", defaultHardMaxAttempts, 1, 32),
|
|
2377
2555
|
hostReserveBytes,
|
|
2378
|
-
idleHostReserveBytes:
|
|
2556
|
+
idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, { reserveFloorBytes, idleReserveOverrideBytes }),
|
|
2557
|
+
defaultHardMaxAttempts,
|
|
2558
|
+
adaptiveHostReserveBytes: resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, adaptiveOptions),
|
|
2559
|
+
reserveFloorBytes,
|
|
2560
|
+
idleReserveOverrideBytes,
|
|
2379
2561
|
cpuReserveMillis: configuredInteger("FORGE_HOST_CPU_RESERVE_MILLIS", 1000, 0, 32_000),
|
|
2380
2562
|
workspaceReserveBytes: configuredInteger("FORGE_HOST_WORKSPACE_RESERVE_BYTES", 10 * 1024 ** 3, 1024 ** 3, Number.MAX_SAFE_INTEGER),
|
|
2381
2563
|
memoryRecoverySamples: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLES", 2, 1, 10),
|
|
2382
2564
|
memoryRecoverySampleIntervalMs: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLE_INTERVAL_MS", 1_000, 100, 30_000),
|
|
2383
2565
|
};
|
|
2384
2566
|
}
|
|
2567
|
+
/**
|
|
2568
|
+
* The reserve kept while no attempt holds capacity: FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES
|
|
2569
|
+
* clamped to [512 MiB, reserve], else min(reserve, reserve floor). Never above the reserve.
|
|
2570
|
+
*/
|
|
2571
|
+
function idleHostReserveBytesFor(hostReserveBytes, configuration) {
|
|
2572
|
+
const fallback = Math.min(hostReserveBytes, configuration.reserveFloorBytes);
|
|
2573
|
+
const override = configuration.idleReserveOverrideBytes;
|
|
2574
|
+
return override === null ? fallback : Math.max(512 * 1024 ** 2, Math.min(hostReserveBytes, override));
|
|
2575
|
+
}
|
|
2385
2576
|
function configuredOptionalInteger(name, minimum, maximum) {
|
|
2386
2577
|
const raw = process.env[name];
|
|
2387
2578
|
if (raw === undefined || raw.trim().length === 0)
|
|
@@ -28,5 +28,28 @@ export declare class HostParallelPromotionStore {
|
|
|
28
28
|
private recordPath;
|
|
29
29
|
}
|
|
30
30
|
export declare function hostRuntimeContractFingerprint(runtimeContract: LoadedHostRuntimeContract): string;
|
|
31
|
+
export interface ReadmittedHostRuntimeContract {
|
|
32
|
+
readonly runtimeContract: LoadedHostRuntimeContract;
|
|
33
|
+
readonly runtimeContractFingerprint: string;
|
|
34
|
+
readonly changed: boolean;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Decides whether a restart may run the workspace's current runtime contract under the admission
|
|
38
|
+
* granted at start. A restart relaunches from the workspace in any case, so a contract whose only
|
|
39
|
+
* change is the values its ports launch with (launch environment, or discovery inputs that leave
|
|
40
|
+
* the contract itself unchanged) is adopted. This is how a conflict repair survives its own merge:
|
|
41
|
+
* merging the target branch can rename a variable in a derived launch profile, or change a
|
|
42
|
+
* manifest or project file, without changing anything admission granted. Every other part of the
|
|
43
|
+
* contract is admission: source, concurrency, ports (names, adapters, environment names, URL
|
|
44
|
+
* formats, and the command, arguments and working directory that launch them), Playwright, browser
|
|
45
|
+
* profile, singleton resources and declared requirements. Changing any of those throws the
|
|
46
|
+
* retryable host_runtime_contract_changed, so only a fresh attempt runs that contract. An attempt
|
|
47
|
+
* admitted to run in parallel keeps that admission, as it does when a merge changes only source;
|
|
48
|
+
* a restart never promotes, so the adopted contract earns no parallel-safety proof of its own here.
|
|
49
|
+
*/
|
|
50
|
+
export declare function readmitHostRuntimeContract(admitted: {
|
|
51
|
+
readonly runtimeContract: LoadedHostRuntimeContract;
|
|
52
|
+
readonly runtimeContractFingerprint: string;
|
|
53
|
+
}, current: LoadedHostRuntimeContract): ReadmittedHostRuntimeContract;
|
|
31
54
|
export declare function hostRuntimeParallelEligible(runtimeContract: LoadedHostRuntimeContract): boolean;
|
|
32
55
|
export declare function configuredLaunchPortNames(runtimeContract: LoadedHostRuntimeContract): readonly string[];
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
2
|
import fs from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
|
+
import { ForgeFailureError } from "../session/session.types.js";
|
|
4
5
|
/** Persists only observed, contract-bound host parallel-safety evidence. */
|
|
5
6
|
export class HostParallelPromotionStore {
|
|
6
7
|
stateRoot;
|
|
@@ -154,6 +155,41 @@ export function hostRuntimeContractFingerprint(runtimeContract) {
|
|
|
154
155
|
});
|
|
155
156
|
return `sha256:${createHash("sha256").update(canonical).digest("hex")}`;
|
|
156
157
|
}
|
|
158
|
+
/**
|
|
159
|
+
* Decides whether a restart may run the workspace's current runtime contract under the admission
|
|
160
|
+
* granted at start. A restart relaunches from the workspace in any case, so a contract whose only
|
|
161
|
+
* change is the values its ports launch with (launch environment, or discovery inputs that leave
|
|
162
|
+
* the contract itself unchanged) is adopted. This is how a conflict repair survives its own merge:
|
|
163
|
+
* merging the target branch can rename a variable in a derived launch profile, or change a
|
|
164
|
+
* manifest or project file, without changing anything admission granted. Every other part of the
|
|
165
|
+
* contract is admission: source, concurrency, ports (names, adapters, environment names, URL
|
|
166
|
+
* formats, and the command, arguments and working directory that launch them), Playwright, browser
|
|
167
|
+
* profile, singleton resources and declared requirements. Changing any of those throws the
|
|
168
|
+
* retryable host_runtime_contract_changed, so only a fresh attempt runs that contract. An attempt
|
|
169
|
+
* admitted to run in parallel keeps that admission, as it does when a merge changes only source;
|
|
170
|
+
* a restart never promotes, so the adopted contract earns no parallel-safety proof of its own here.
|
|
171
|
+
*/
|
|
172
|
+
export function readmitHostRuntimeContract(admitted, current) {
|
|
173
|
+
const runtimeContractFingerprint = hostRuntimeContractFingerprint(current);
|
|
174
|
+
// The fingerprint leaves out the source of a project or default contract, but parallel
|
|
175
|
+
// eligibility depends on it, so an unchanged fingerprint alone does not prove the same admission.
|
|
176
|
+
if (runtimeContractFingerprint === admitted.runtimeContractFingerprint && current.source === admitted.runtimeContract.source) {
|
|
177
|
+
return { runtimeContract: admitted.runtimeContract, runtimeContractFingerprint, changed: false };
|
|
178
|
+
}
|
|
179
|
+
if (hostRuntimeAdmissionShape(current) !== hostRuntimeAdmissionShape(admitted.runtimeContract)) {
|
|
180
|
+
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.");
|
|
181
|
+
}
|
|
182
|
+
return { runtimeContract: current, runtimeContractFingerprint, changed: true };
|
|
183
|
+
}
|
|
184
|
+
function hostRuntimeAdmissionShape(runtimeContract) {
|
|
185
|
+
const runtime = runtimeContract.contract.runtime;
|
|
186
|
+
return JSON.stringify({
|
|
187
|
+
source: runtimeContract.source,
|
|
188
|
+
schemaVersion: runtimeContract.contract.schemaVersion,
|
|
189
|
+
runtime: { ...runtime, ports: runtime.ports.map(port => ({ ...port, launch: port.launch && { ...port.launch, environment: undefined } })) },
|
|
190
|
+
...requirementsFingerprintPart(runtimeContract.contract.requires),
|
|
191
|
+
});
|
|
192
|
+
}
|
|
157
193
|
// Cost hints are estimates, not placement constraints: they never change the fingerprint.
|
|
158
194
|
function requirementsFingerprintPart(requires) {
|
|
159
195
|
if (!requires)
|
|
@@ -28,5 +28,12 @@ export declare class PlaywrightHostRuntimeAdapter {
|
|
|
28
28
|
*/
|
|
29
29
|
assertBrowserCacheReady(config: HostRuntimePlaywrightConfig, worktreePath: string): Promise<void>;
|
|
30
30
|
private readyBrowserCache;
|
|
31
|
+
/**
|
|
32
|
+
* Removes the generated config, which names the base URL of the stack it was prepared for. A
|
|
33
|
+
* stopped stack's config must not survive: its port may be reassigned to another attempt, and a
|
|
34
|
+
* provider that remembers the config's path would otherwise run Playwright against that port.
|
|
35
|
+
* The next `prepare` writes a fresh one.
|
|
36
|
+
*/
|
|
37
|
+
discardOverlay(temporaryDirectory: string): Promise<void>;
|
|
31
38
|
prepare(config: HostRuntimePlaywrightConfig, context: PlaywrightHostRuntimeContext): Promise<PreparedPlaywrightHostRuntime>;
|
|
32
39
|
}
|
|
@@ -35,6 +35,17 @@ export class PlaywrightHostRuntimeAdapter {
|
|
|
35
35
|
}
|
|
36
36
|
return { cache: resolution.cache, installCommand };
|
|
37
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* Removes the generated config, which names the base URL of the stack it was prepared for. A
|
|
40
|
+
* stopped stack's config must not survive: its port may be reassigned to another attempt, and a
|
|
41
|
+
* provider that remembers the config's path would otherwise run Playwright against that port.
|
|
42
|
+
* The next `prepare` writes a fresh one.
|
|
43
|
+
*/
|
|
44
|
+
async discardOverlay(temporaryDirectory) {
|
|
45
|
+
if (!await assertCanonicalDirectory(temporaryDirectory, true))
|
|
46
|
+
return;
|
|
47
|
+
await fs.rm(path.join(path.resolve(temporaryDirectory), playwrightOverlayFileName), { force: true });
|
|
48
|
+
}
|
|
38
49
|
async prepare(config, context) {
|
|
39
50
|
const { realWorktree, realSource } = await projectConfigLocation(config, context.worktreePath);
|
|
40
51
|
const sourceConfig = path.resolve(path.resolve(context.worktreePath), config.config);
|
|
@@ -62,7 +73,7 @@ export class PlaywrightHostRuntimeAdapter {
|
|
|
62
73
|
if (!/^[0-9a-f]{32}$/u.test(context.ownershipToken)) {
|
|
63
74
|
throw new Error("playwright_runtime_adapter_invalid: ownership token must be a normalized dispatch attempt UUID.");
|
|
64
75
|
}
|
|
65
|
-
const overlayPath = path.join(temporaryDirectory,
|
|
76
|
+
const overlayPath = path.join(temporaryDirectory, playwrightOverlayFileName);
|
|
66
77
|
const { cache: readyCache, installCommand: browserInstallCommand } = await this.readyBrowserCache(context.worktreePath, realWorktree, path.dirname(realSource));
|
|
67
78
|
const browserCache = readyCache
|
|
68
79
|
? { path: readyCache, ready: true }
|
|
@@ -135,6 +146,7 @@ async function ensureAttemptWritableDirectories(targets, realWorktree) {
|
|
|
135
146
|
for (const target of resolvedTargets)
|
|
136
147
|
await createPrivateCanonicalDirectory(target);
|
|
137
148
|
}
|
|
149
|
+
const playwrightOverlayFileName = "forge.playwright.config.mjs";
|
|
138
150
|
async function writeAttemptOverlay(target, content) {
|
|
139
151
|
const parent = path.dirname(target);
|
|
140
152
|
const identity = await assertCanonicalDirectory(parent);
|