@loucompanion/forge-bridge 0.1.4-dev.fb770705136a → 0.2.1-dev.c3166221b6e7
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 +144 -3
- package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
- package/dist/bridge/bridge-chat-provider-command.js +132 -0
- package/dist/bridge/bridge-chat.types.d.ts +10 -0
- package/dist/bridge/bridge-chat.types.js +16 -1
- package/dist/bridge/bridge-state-file.d.ts +161 -0
- package/dist/bridge/bridge-state-file.js +376 -0
- package/dist/bridge/bridge-state-io.d.ts +11 -0
- package/dist/bridge/bridge-state-io.js +50 -0
- package/dist/bridge/bridge-state-lock.d.ts +11 -0
- package/dist/bridge/bridge-state-lock.js +102 -0
- package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
- package/dist/bridge/bridge-state-unpublished.js +111 -0
- package/dist/bridge/bridge.base.d.ts +9 -0
- package/dist/bridge/bridge.service.d.ts +90 -14
- package/dist/bridge/bridge.service.js +436 -350
- package/dist/bridge/bridge.types.d.ts +21 -0
- package/dist/bridge/in-flight-registry.d.ts +62 -0
- package/dist/bridge/in-flight-registry.js +207 -0
- package/dist/bridge/local-yield-flag.d.ts +6 -0
- package/dist/bridge/local-yield-flag.js +34 -0
- package/dist/bridge/readiness-result-outbox.d.ts +5 -1
- package/dist/bridge/readiness-result-outbox.js +20 -0
- package/dist/bridge/runner-host-capabilities.d.ts +5 -0
- package/dist/bridge/runner-host-capabilities.js +17 -0
- package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
- package/dist/bridge/sandbox-resource-accounting.js +150 -0
- package/dist/bridge/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- package/dist/cleanup/cleanup-wip.d.ts +12 -0
- package/dist/cleanup/cleanup-wip.js +66 -0
- package/dist/cleanup/cleanup.service.d.ts +20 -1
- package/dist/cleanup/cleanup.service.js +150 -169
- package/dist/cleanup/cleanup.types.d.ts +6 -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 +7 -0
- package/dist/cleanup/host-runtime-ledger.js +130 -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 +74 -12
- package/dist/cli/cli.service.d.ts +19 -10
- package/dist/cli/cli.service.js +152 -187
- package/dist/cli/idle-status.d.ts +84 -0
- package/dist/cli/idle-status.js +181 -0
- package/dist/cli/local-config.d.ts +6 -0
- package/dist/cli/local-config.js +32 -4
- package/dist/cli/provider-cli-detection.d.ts +10 -0
- package/dist/cli/provider-cli-detection.js +160 -0
- package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
- package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
- package/dist/runtime/attempt-database-broker.d.ts +1 -1
- package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
- package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
- package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
- package/dist/runtime/attempt-process-supervisor.js +12 -6
- package/dist/runtime/docker-engine-probe.d.ts +5 -0
- package/dist/runtime/docker-engine-probe.js +7 -0
- package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
- package/dist/runtime/dotnet-build-outputs.js +402 -0
- package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
- package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
- package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
- package/dist/runtime/ephemeral-test-postgres.js +303 -0
- package/dist/runtime/host-facts.d.ts +2 -1
- package/dist/runtime/host-listener-inspector.d.ts +26 -0
- package/dist/runtime/host-listener-inspector.js +84 -3
- package/dist/runtime/host-load-admission.d.ts +67 -0
- package/dist/runtime/host-load-admission.js +99 -0
- package/dist/runtime/host-load-child-environment.d.ts +27 -0
- package/dist/runtime/host-load-child-environment.js +76 -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 +52 -0
- package/dist/runtime/host-load-governor-config.js +83 -0
- package/dist/runtime/host-load-governor.d.ts +186 -0
- package/dist/runtime/host-load-governor.js +632 -0
- package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
- package/dist/runtime/host-load-ledger-lock.js +187 -0
- package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
- package/dist/runtime/host-load-runtime-settings.js +80 -0
- package/dist/runtime/host-load-sampler.d.ts +75 -2
- package/dist/runtime/host-load-sampler.js +142 -8
- package/dist/runtime/host-load-step-class.d.ts +70 -0
- package/dist/runtime/host-load-step-class.js +161 -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-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 +200 -0
- package/dist/runtime/host-load-token-ledger.js +453 -0
- 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-pressure-stall.d.ts +21 -1
- package/dist/runtime/host-pressure-stall.js +48 -1
- package/dist/runtime/host-runtime-contract.d.ts +15 -0
- package/dist/runtime/host-runtime-contract.js +33 -2
- package/dist/runtime/host-runtime-lease.d.ts +101 -6
- package/dist/runtime/host-runtime-lease.js +408 -294
- package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
- package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
- package/dist/runtime/host-runtime-promotion.d.ts +101 -2
- package/dist/runtime/host-runtime-promotion.js +355 -14
- 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.js +5 -16
- package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
- package/dist/runtime/native-test-postgres-fallback.js +60 -8
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
- package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
- package/dist/runtime/prepared-runtime-identity.js +130 -9
- package/dist/runtime/prepared-runtime-readiness.d.ts +13 -1
- package/dist/runtime/prepared-runtime-readiness.js +63 -16
- package/dist/runtime/runner-settings.d.ts +104 -0
- package/dist/runtime/runner-settings.js +236 -0
- package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
- package/dist/runtime/supervised-runtime-build-guard.js +112 -0
- package/dist/sandbox/host-capacity-broker.d.ts +115 -0
- package/dist/sandbox/host-capacity-broker.js +336 -0
- package/dist/sandbox/managed-branch.d.ts +13 -0
- package/dist/sandbox/managed-branch.js +90 -0
- package/dist/sandbox/provider-auth/codex.js +11 -11
- package/dist/sandbox/runtime.d.ts +10 -1
- package/dist/sandbox/runtime.js +47 -8
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/session/architect-waits.d.ts +2 -0
- package/dist/session/architect-waits.js +138 -0
- package/dist/session/managed-attempt-tools.d.ts +2 -7
- package/dist/session/managed-attempt-tools.js +207 -121
- package/dist/session/managed-build-coordinator.d.ts +16 -0
- package/dist/session/managed-build-coordinator.js +10 -0
- package/dist/session/managed-build-receipt.d.ts +5 -0
- package/dist/session/managed-build-receipt.js +8 -3
- package/dist/session/managed-command-host-load.d.ts +47 -0
- package/dist/session/managed-command-host-load.js +83 -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 +96 -26
- 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 +12 -0
- package/dist/session/phase-completion.helpers.js +13 -12
- package/dist/session/phase-completion.js +5 -0
- package/dist/session/phase-completion.mcp-args.d.ts +9 -0
- package/dist/session/phase-completion.mcp-args.js +156 -0
- package/dist/session/phase-completion.prompts.js +6 -1
- package/dist/session/phase-completion.runtime.d.ts +5 -11
- package/dist/session/phase-completion.runtime.js +91 -215
- 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 +208 -231
- package/dist/session/phase-completion.validation.d.ts +2 -3
- package/dist/session/phase-completion.validation.js +49 -93
- 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-native-postgres.d.ts +30 -0
- package/dist/session/pre-publication-native-postgres.js +111 -0
- package/dist/session/pre-publication-pass.d.ts +61 -0
- package/dist/session/pre-publication-pass.js +148 -0
- package/dist/session/pre-publication-process.d.ts +3 -0
- package/dist/session/pre-publication-process.js +31 -19
- package/dist/session/pre-publication-step-execution.d.ts +12 -0
- package/dist/session/pre-publication-step-execution.js +50 -0
- package/dist/session/pre-publication-validation.d.ts +37 -21
- package/dist/session/pre-publication-validation.js +221 -182
- package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
- package/dist/session/provider-cli/claude-background-work.js +181 -0
- package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
- package/dist/session/provider-cli/host-build-lock.js +30 -0
- package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
- package/dist/session/provider-cli/pre-publication-repair.js +276 -0
- package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
- package/dist/session/provider-cli/provider-cli.child-environment.js +75 -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 +15 -36
- package/dist/session/provider-cli/provider-cli.process.js +41 -432
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +72 -32
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
- package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
- package/dist/session/provider-cli/provider-cli.service.js +98 -173
- package/dist/session/provider-cli/provider-cli.types.d.ts +30 -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-cli.windows-launch.d.ts +23 -0
- package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -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/provider-cli/provider-user-config-isolation.d.ts +69 -0
- package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
- package/dist/session/qa-sidecar-validation.d.ts +6 -0
- package/dist/session/qa-sidecar-validation.js +28 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
- package/dist/session/sandbox-host-capacity-gate.js +257 -0
- package/dist/session/session-redaction.js +31 -181
- package/dist/session/session.base.d.ts +9 -1
- package/dist/session/session.service.d.ts +15 -2
- package/dist/session/session.service.js +242 -88
- package/dist/session/session.types.d.ts +3 -0
- package/dist/session/session.types.js +5 -5
- package/dist/session/sidecar-json-shape.d.ts +31 -0
- package/dist/session/sidecar-json-shape.js +217 -0
- package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
- package/dist/session/workspace-runtime-fingerprint.js +138 -0
- package/dist/shared/fs/file-identity.d.ts +10 -0
- package/dist/shared/fs/file-identity.js +15 -0
- package/dist/shared/fs/replace-file.d.ts +7 -0
- package/dist/shared/fs/replace-file.js +33 -0
- package/dist/shared/process/host-process-recovery.d.ts +14 -3
- package/dist/shared/process/host-process-recovery.js +23 -3
- package/dist/shared/process/host-process-supervisor.d.ts +14 -1
- package/dist/shared/process/host-process-supervisor.js +67 -15
- package/dist/shared/process/process-tree.d.ts +52 -0
- package/dist/shared/process/process-tree.js +144 -0
- package/dist/shared/process/process.d.ts +67 -0
- package/dist/shared/process/process.js +213 -11
- package/dist/shared/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 +14 -7
- 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/orphan-relink.d.ts +19 -0
- package/dist/worktree/orphan-relink.js +106 -0
- package/dist/worktree/wip-git.d.ts +33 -0
- package/dist/worktree/wip-git.js +122 -0
- package/dist/worktree/wip-refs.d.ts +62 -0
- package/dist/worktree/wip-refs.js +119 -0
- package/dist/worktree/wip-restore.d.ts +38 -0
- package/dist/worktree/wip-restore.js +190 -0
- package/dist/worktree/wip-snapshot.d.ts +50 -0
- package/dist/worktree/wip-snapshot.js +268 -0
- package/dist/worktree/worktree-inputs.d.ts +8 -0
- package/dist/worktree/worktree-inputs.js +134 -0
- package/dist/worktree/worktree-origin-sync.d.ts +34 -0
- package/dist/worktree/worktree-origin-sync.js +127 -0
- package/dist/worktree/worktree-wip-events.d.ts +18 -0
- package/dist/worktree/worktree-wip-events.js +98 -0
- package/dist/worktree/worktree-wip.d.ts +50 -0
- package/dist/worktree/worktree-wip.js +185 -0
- package/dist/worktree/worktree.base.d.ts +7 -1
- package/dist/worktree/worktree.service.d.ts +36 -5
- package/dist/worktree/worktree.service.js +124 -155
- package/dist/worktree/worktree.types.d.ts +38 -0
- package/package.json +2 -2
- package/runtime/windows-listener-owner.ps1 +12 -1
|
@@ -0,0 +1,632 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import { ForgeFailureError } from "../session/session.types.js";
|
|
4
|
+
import { monotonicNowMs } from "../shared/time/monotonic.js";
|
|
5
|
+
import { decideHostLoadAdmission, } from "./host-load-admission.js";
|
|
6
|
+
import { hostLoadGovernorEnabled, loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
|
|
7
|
+
import { HostCapacityLedgerUnavailableError } from "./host-load-ledger-lock.js";
|
|
8
|
+
import { HostLoadRuntimeSettingsReader } from "./host-load-runtime-settings.js";
|
|
9
|
+
import { decideHostTestSlot, takesHostTestSlot } from "./host-load-test-slot.js";
|
|
10
|
+
import { terminateHostLoadStepProcess } from "./host-load-step-reaper.js";
|
|
11
|
+
import { HostCapacityTokenFencedError, HostLoadTokenLedger, } from "./host-load-token-ledger.js";
|
|
12
|
+
export class HostCapacityTimeoutError extends ForgeFailureError {
|
|
13
|
+
stepClass;
|
|
14
|
+
label;
|
|
15
|
+
waitMs;
|
|
16
|
+
code = "host_capacity_timeout";
|
|
17
|
+
constructor(stepClass, label, waitMs, detail) {
|
|
18
|
+
super("host_capacity_timeout", `host_capacity_timeout: ${label} (${stepClass}) waited ${Math.round(waitMs / 1000)}s for host capacity without being admitted: ${detail} This is a retryable host-load condition, not a test failure.`, "bridge");
|
|
19
|
+
this.stepClass = stepClass;
|
|
20
|
+
this.label = label;
|
|
21
|
+
this.waitMs = waitMs;
|
|
22
|
+
this.name = "HostCapacityTimeoutError";
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Host-wide admission for heavy steps (decision 0013). Waiters queue
|
|
27
|
+
* foreground before background and FIFO within a class; a waiter that fits may
|
|
28
|
+
* overtake an unfit head until the head has waited past the anti-starvation
|
|
29
|
+
* window. Running steps are never preempted. Reserved cost comes from the
|
|
30
|
+
* shared token ledger, so other processes' steps count against the same budget.
|
|
31
|
+
* The host test slot (decision 0018) comes first: a heavy step waits for it in
|
|
32
|
+
* the host-wide queue the ledger keeps, then for the budget when that is on.
|
|
33
|
+
*/
|
|
34
|
+
export class HostLoadGovernor {
|
|
35
|
+
options;
|
|
36
|
+
enabled;
|
|
37
|
+
config;
|
|
38
|
+
ledger;
|
|
39
|
+
waiters = [];
|
|
40
|
+
held = new Map();
|
|
41
|
+
recheckTimer = null;
|
|
42
|
+
renewTimer = null;
|
|
43
|
+
draining = null;
|
|
44
|
+
drainAgain = false;
|
|
45
|
+
/** Own cgroup anonymous memory with no heavy step running: the bridge's baseline. */
|
|
46
|
+
idleOwnMemoryBytes = null;
|
|
47
|
+
/** The bridge's pushed settings (decision 0014), shared with every governor on this state root. */
|
|
48
|
+
runtimeSettings;
|
|
49
|
+
constructor(options) {
|
|
50
|
+
this.options = options;
|
|
51
|
+
this.config = options.config ?? loadHostLoadGovernorConfig();
|
|
52
|
+
this.enabled = hostLoadGovernorEnabled(this.config);
|
|
53
|
+
this.runtimeSettings = new HostLoadRuntimeSettingsReader(options.stateRoot);
|
|
54
|
+
this.ledger = new HostLoadTokenLedger({
|
|
55
|
+
stateRoot: options.stateRoot,
|
|
56
|
+
leaseMs: this.config.leaseMs,
|
|
57
|
+
now: options.now,
|
|
58
|
+
liveness: options.liveness,
|
|
59
|
+
owner: options.owner,
|
|
60
|
+
terminateStep: options.terminateStep,
|
|
61
|
+
suspendedMs: options.suspendedMs,
|
|
62
|
+
// Every ledger transaction renews the steps this governor is running.
|
|
63
|
+
heldTokens: () => [...this.held.values()].map(entry => entry.token),
|
|
64
|
+
// ...and keeps its waiters' places in the host test slot queue.
|
|
65
|
+
waitingTickets: () => this.waiters.flatMap(waiter => waiter.ticket && !waiter.settled ? [waiter.ticket] : []),
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
get maxWaitMs() {
|
|
69
|
+
return this.config.maxWaitMs;
|
|
70
|
+
}
|
|
71
|
+
async acquire(request, options = {}) {
|
|
72
|
+
if (!this.enabled) {
|
|
73
|
+
throw new Error("host_load_governor_disabled: acquire() requires a host test slot or FORGE_HOST_LOAD_GOVERNOR=on.");
|
|
74
|
+
}
|
|
75
|
+
const { signal } = options;
|
|
76
|
+
if (signal?.aborted)
|
|
77
|
+
throw abortError(signal);
|
|
78
|
+
// With the budget off, a step that takes no slot needs nothing from the ledger:
|
|
79
|
+
// a ledger fault cannot fail a `git status` or a dependency install.
|
|
80
|
+
if (this.config.mode !== "on" && !takesHostTestSlot(request.stepClass))
|
|
81
|
+
return slotFreeAdmission(request);
|
|
82
|
+
// Only the budget reads load samples.
|
|
83
|
+
if (this.config.mode === "on")
|
|
84
|
+
await this.options.load.start().catch(() => undefined);
|
|
85
|
+
if (signal?.aborted)
|
|
86
|
+
throw abortError(signal);
|
|
87
|
+
return await new Promise((resolve, reject) => {
|
|
88
|
+
const waiter = {
|
|
89
|
+
request,
|
|
90
|
+
enqueuedAtMs: monotonicNowMs(),
|
|
91
|
+
signal,
|
|
92
|
+
onWaiting: options.onWaiting,
|
|
93
|
+
resolve,
|
|
94
|
+
reject,
|
|
95
|
+
abort: () => this.settle(waiter, () => reject(abortError(signal))),
|
|
96
|
+
deadline: null,
|
|
97
|
+
lastDecision: null,
|
|
98
|
+
settled: false,
|
|
99
|
+
ticket: this.config.testSlots > 0 && takesHostTestSlot(request.stepClass)
|
|
100
|
+
? {
|
|
101
|
+
ticketId: randomUUID(),
|
|
102
|
+
stepClass: request.stepClass,
|
|
103
|
+
label: request.label,
|
|
104
|
+
dispatchAttemptId: request.dispatchAttemptId,
|
|
105
|
+
priority: request.priority,
|
|
106
|
+
enqueuedAt: new Date(this.options.now?.() ?? Date.now()).toISOString(),
|
|
107
|
+
}
|
|
108
|
+
: null,
|
|
109
|
+
};
|
|
110
|
+
waiter.deadline = setTimeout(() => this.settle(waiter, () => reject(new HostCapacityTimeoutError(request.stepClass, request.label, monotonicNowMs() - waiter.enqueuedAtMs, waiter.lastDecision?.detail ?? "the host stayed at capacity."))), this.config.maxWaitMs);
|
|
111
|
+
waiter.deadline.unref?.();
|
|
112
|
+
signal?.addEventListener("abort", waiter.abort, { once: true });
|
|
113
|
+
// Foreground goes ahead of background, except background that has already
|
|
114
|
+
// waited past the anti-starvation window: steady foreground load cannot starve it.
|
|
115
|
+
const backgroundIndex = request.priority === "foreground"
|
|
116
|
+
? this.waiters.findIndex(candidate => candidate.request.priority === "background"
|
|
117
|
+
&& waiter.enqueuedAtMs - candidate.enqueuedAtMs < this.config.antiStarvationMs)
|
|
118
|
+
: -1;
|
|
119
|
+
if (backgroundIndex < 0)
|
|
120
|
+
this.waiters.push(waiter);
|
|
121
|
+
else
|
|
122
|
+
this.waiters.splice(backgroundIndex, 0, waiter);
|
|
123
|
+
this.armRecheck();
|
|
124
|
+
void this.drain();
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
/** Reclaims tokens whose owner is gone or whose lease expired (bridge startup). */
|
|
128
|
+
async reclaim() {
|
|
129
|
+
if (!this.enabled)
|
|
130
|
+
return [];
|
|
131
|
+
const outcome = await this.ledger.transaction(() => undefined);
|
|
132
|
+
this.applyHeldOutcome(outcome);
|
|
133
|
+
if (outcome.reclaimed.length > 0)
|
|
134
|
+
void this.drain();
|
|
135
|
+
return outcome.reclaimed;
|
|
136
|
+
}
|
|
137
|
+
/** Returns dead owners' unrecorded tokens the caller proved stopped (see the ledger). */
|
|
138
|
+
async releaseOrphaned(belongs) {
|
|
139
|
+
if (!this.enabled)
|
|
140
|
+
return [];
|
|
141
|
+
const released = await this.ledger.releaseOrphaned(belongs);
|
|
142
|
+
if (released.length > 0)
|
|
143
|
+
void this.drain();
|
|
144
|
+
return released;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Attempt teardown: cancels the attempt's queued steps and stops its running
|
|
148
|
+
* ones (their `fenced` signal aborts with dispatch_cancelled). A running step
|
|
149
|
+
* keeps its token, and its cost, until the step itself returns it once its
|
|
150
|
+
* processes are gone, so the capacity is never reused while it still runs.
|
|
151
|
+
*/
|
|
152
|
+
stopAttempt(dispatchAttemptId) {
|
|
153
|
+
if (!this.enabled)
|
|
154
|
+
return;
|
|
155
|
+
this.cancelAttemptWaiters(dispatchAttemptId);
|
|
156
|
+
for (const entry of this.held.values()) {
|
|
157
|
+
if (entry.token.dispatchAttemptId !== dispatchAttemptId)
|
|
158
|
+
continue;
|
|
159
|
+
this.lose(entry, new ForgeFailureError("dispatch_cancelled", "dispatch_cancelled: the attempt was torn down while this step ran; it was stopped before its host capacity was returned.", "bridge"));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Cancels the attempt's queued steps and returns every token it holds at
|
|
164
|
+
* once. Only for callers that know the attempt's steps are no longer running;
|
|
165
|
+
* attempt teardown uses stopAttempt.
|
|
166
|
+
*/
|
|
167
|
+
async releaseAttempt(dispatchAttemptId) {
|
|
168
|
+
if (!this.enabled)
|
|
169
|
+
return;
|
|
170
|
+
this.cancelAttemptWaiters(dispatchAttemptId);
|
|
171
|
+
const owned = [...this.held.values()].filter(entry => entry.token.dispatchAttemptId === dispatchAttemptId);
|
|
172
|
+
await Promise.allSettled(owned.map(entry => this.releaseHeld(entry)));
|
|
173
|
+
}
|
|
174
|
+
cancelAttemptWaiters(dispatchAttemptId) {
|
|
175
|
+
for (const waiter of [...this.waiters]) {
|
|
176
|
+
if (waiter.request.dispatchAttemptId !== dispatchAttemptId)
|
|
177
|
+
continue;
|
|
178
|
+
this.settle(waiter, () => waiter.reject(new ForgeFailureError("dispatch_cancelled", "dispatch_cancelled: the attempt was torn down while its step waited for host capacity.", "bridge")));
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
/** Waiting and admitted steps of this process, for diagnostics. */
|
|
182
|
+
snapshot() {
|
|
183
|
+
return { waiting: this.waiters.length, held: [...this.held.values()].map(entry => entry.token) };
|
|
184
|
+
}
|
|
185
|
+
async drain() {
|
|
186
|
+
if (this.draining) {
|
|
187
|
+
this.drainAgain = true;
|
|
188
|
+
return await this.draining;
|
|
189
|
+
}
|
|
190
|
+
this.draining = (async () => {
|
|
191
|
+
do {
|
|
192
|
+
this.drainAgain = false;
|
|
193
|
+
await this.drainOnce().catch(error => this.failWaiters(error));
|
|
194
|
+
} while (this.drainAgain && this.waiters.length > 0);
|
|
195
|
+
})().finally(() => {
|
|
196
|
+
this.draining = null;
|
|
197
|
+
});
|
|
198
|
+
return await this.draining;
|
|
199
|
+
}
|
|
200
|
+
async drainOnce() {
|
|
201
|
+
if (this.waiters.length === 0)
|
|
202
|
+
return;
|
|
203
|
+
const budget = this.config.mode === "on" ? await this.budgetPass() : null;
|
|
204
|
+
if (this.waiters.length === 0)
|
|
205
|
+
return;
|
|
206
|
+
const nowMs = monotonicNowMs();
|
|
207
|
+
const outcomes = [];
|
|
208
|
+
const outcome = await this.ledger.transaction(transaction => {
|
|
209
|
+
const runningMemoryBytes = budget ? this.runningStepsMemoryBytes(transaction.tokens) : 0;
|
|
210
|
+
const head = this.waiters[0];
|
|
211
|
+
const headStarving = head !== undefined && nowMs - head.enqueuedAtMs >= this.config.antiStarvationMs;
|
|
212
|
+
for (const waiter of this.waiters) {
|
|
213
|
+
if (waiter.settled)
|
|
214
|
+
continue;
|
|
215
|
+
const decision = this.decide(waiter, transaction, budget, runningMemoryBytes);
|
|
216
|
+
if (decision.admitted && waiter.ticket) {
|
|
217
|
+
// The ticket leaves the host queue in the same commit that issues the token.
|
|
218
|
+
transaction.removeTicket(waiter.ticket.ticketId);
|
|
219
|
+
waiter.ticket = null;
|
|
220
|
+
}
|
|
221
|
+
outcomes.push({ waiter, decision, token: decision.admitted ? transaction.issue(waiter.request) : null });
|
|
222
|
+
// A starving head blocks the budget so running steps drain and it can start. A
|
|
223
|
+
// slot wait does not: the host queue already orders slot waiters, and steps
|
|
224
|
+
// behind this one locally may be ahead of it there, or take no slot.
|
|
225
|
+
if (waiter === head && headStarving && !decision.admitted && decision.reason !== "host_test_slot")
|
|
226
|
+
break;
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
this.applyHeldOutcome(outcome);
|
|
230
|
+
for (const { waiter, token, decision } of outcomes) {
|
|
231
|
+
if (!token) {
|
|
232
|
+
const first = waiter.lastDecision === null;
|
|
233
|
+
waiter.lastDecision = decision;
|
|
234
|
+
if (first && !waiter.settled)
|
|
235
|
+
void Promise.resolve(waiter.onWaiting?.(decision)).catch(() => undefined);
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
const entry = {
|
|
239
|
+
token,
|
|
240
|
+
fencedController: new AbortController(),
|
|
241
|
+
fencedError: null,
|
|
242
|
+
renewedAtMs: monotonicNowMs(),
|
|
243
|
+
releasing: false,
|
|
244
|
+
releaseInFlight: null,
|
|
245
|
+
gone: false,
|
|
246
|
+
retainedUntil: null,
|
|
247
|
+
retainCheck: null,
|
|
248
|
+
};
|
|
249
|
+
this.held.set(token.tokenId, entry);
|
|
250
|
+
this.armRenewal();
|
|
251
|
+
if (waiter.settled) {
|
|
252
|
+
// Cancelled or timed out while the decision was being made.
|
|
253
|
+
void this.releaseHeld(entry).catch(() => undefined);
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
const waitMs = Math.max(0, monotonicNowMs() - waiter.enqueuedAtMs);
|
|
257
|
+
this.settle(waiter, () => waiter.resolve({
|
|
258
|
+
tokenId: token.tokenId,
|
|
259
|
+
fencingToken: token.fencingToken,
|
|
260
|
+
stepClass: token.stepClass,
|
|
261
|
+
waitMs,
|
|
262
|
+
decision,
|
|
263
|
+
fenced: entry.fencedController.signal,
|
|
264
|
+
attachProcess: stepProcess => this.attachProcess(entry, stepProcess),
|
|
265
|
+
release: () => this.releaseHeld(entry),
|
|
266
|
+
retainUntilStopped: (stillGone, reason) => this.retainUntilStopped(entry, stillGone, reason),
|
|
267
|
+
}));
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Decision 0014: the CPU budget (or yield budget) and the heavy-step limit the
|
|
272
|
+
* bridge has in force apply from the next admission; running steps keep theirs.
|
|
273
|
+
* The operator's env ceilings hold with or without the file, and over whatever it says.
|
|
274
|
+
*/
|
|
275
|
+
async budgetPass() {
|
|
276
|
+
const overrides = await this.runtimeSettings.read();
|
|
277
|
+
const cpuBudgetFraction = Math.min(overrides?.cpuBudgetFraction ?? this.config.cpuBudgetFraction, this.config.cpuBudgetCeilingFraction ?? 1);
|
|
278
|
+
return {
|
|
279
|
+
config: cpuBudgetFraction === this.config.cpuBudgetFraction ? this.config : { ...this.config, cpuBudgetFraction },
|
|
280
|
+
maxHeavySteps: lowestLimit(overrides?.maxHeavySteps ?? null, this.config.maxHeavyStepsCeiling ?? null),
|
|
281
|
+
signals: this.readSignals(),
|
|
282
|
+
logicalCpus: this.logicalCpus(),
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
/** The host test slot first (decision 0018), then the budget when it is on. */
|
|
286
|
+
decide(waiter, transaction, budget, runningMemoryBytes) {
|
|
287
|
+
const slot = waiter.ticket
|
|
288
|
+
? decideHostTestSlot({
|
|
289
|
+
ticket: waiter.ticket,
|
|
290
|
+
queue: transaction.queue,
|
|
291
|
+
tokens: transaction.tokens,
|
|
292
|
+
testSlots: this.config.testSlots,
|
|
293
|
+
nowMs: this.options.now?.() ?? Date.now(),
|
|
294
|
+
antiStarvationMs: this.config.antiStarvationMs,
|
|
295
|
+
})
|
|
296
|
+
: null;
|
|
297
|
+
const decision = slot && !slot.admitted ? slot : budget
|
|
298
|
+
? decideHostLoadAdmission({
|
|
299
|
+
request: waiter.request.cost,
|
|
300
|
+
running: transaction.tokens.map(token => token.cost),
|
|
301
|
+
runningMemoryBytes,
|
|
302
|
+
logicalCpus: budget.logicalCpus,
|
|
303
|
+
signals: budget.signals,
|
|
304
|
+
config: budget.config,
|
|
305
|
+
maxHeavySteps: budget.maxHeavySteps,
|
|
306
|
+
})
|
|
307
|
+
: slot ?? slotFreeDecision;
|
|
308
|
+
if (!transaction.recoveringUntil)
|
|
309
|
+
return decision;
|
|
310
|
+
return {
|
|
311
|
+
...decision,
|
|
312
|
+
admitted: false,
|
|
313
|
+
reason: "ledger_recovering",
|
|
314
|
+
detail: `The host load ledger was corrupt and was quarantined; admissions resume at ${transaction.recoveringUntil}, once running steps have restored their reservations.`,
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
readSignals() {
|
|
318
|
+
const snapshot = this.options.load.current();
|
|
319
|
+
const cpu = snapshot?.systemPressure?.cpu?.some;
|
|
320
|
+
const sampledAtMs = snapshot ? Date.parse(snapshot.sampledAt) : Number.NaN;
|
|
321
|
+
const now = this.options.now?.() ?? Date.now();
|
|
322
|
+
if (!snapshot?.psiAvailable || !cpu || !Number.isFinite(sampledAtMs) || now - sampledAtMs > this.config.sampleStaleMs) {
|
|
323
|
+
return null;
|
|
324
|
+
}
|
|
325
|
+
// Own-cgroup numbers are trusted only for a dedicated cgroup (step 1's ownCgroupDedicated).
|
|
326
|
+
const attribution = snapshot.ownCgroupDedicated ? this.options.load.cpuAttribution?.() ?? null : null;
|
|
327
|
+
return {
|
|
328
|
+
cpuSomeAvg10: cpu.avg10,
|
|
329
|
+
cpuPressuredSamples: this.pressureStreak(sampledAtMs, cpu.avg10),
|
|
330
|
+
memoryFullAvg10: snapshot.systemPressure?.memory?.full?.avg10 ?? null,
|
|
331
|
+
memoryAvailableBytes: tighterMemory(snapshot.memoryAvailableBytes, this.options.load.cgroupMemoryHeadroomBytes?.() ?? null),
|
|
332
|
+
externalCpuCores: attribution?.sampledAt === snapshot.sampledAt ? attribution.externalCoresInUse : null,
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Consecutive pressured samples ending with the latest one, read from the
|
|
337
|
+
* sampler's history so samples taken while nothing waited still count. A gap
|
|
338
|
+
* in sampling (sampler stopped, host suspended) breaks the streak.
|
|
339
|
+
*/
|
|
340
|
+
pressureStreak(latestAtMs, latestAvg10) {
|
|
341
|
+
if (latestAvg10 < this.config.cpuPressureThreshold)
|
|
342
|
+
return 0;
|
|
343
|
+
let streak = 1;
|
|
344
|
+
let laterAtMs = latestAtMs;
|
|
345
|
+
const history = this.options.load.recent();
|
|
346
|
+
for (let index = history.length - 1; index >= 0 && streak < this.config.backpressureSamples; index -= 1) {
|
|
347
|
+
const sample = history[index];
|
|
348
|
+
const atMs = Date.parse(sample.sampledAt);
|
|
349
|
+
if (!Number.isFinite(atMs) || atMs >= laterAtMs)
|
|
350
|
+
continue;
|
|
351
|
+
if (laterAtMs - atMs > this.config.sampleIntervalMs * 1.5)
|
|
352
|
+
break;
|
|
353
|
+
const avg10 = sample.psiAvailable ? sample.systemPressure?.cpu?.some?.avg10 : undefined;
|
|
354
|
+
if (avg10 === undefined || avg10 < this.config.cpuPressureThreshold)
|
|
355
|
+
break;
|
|
356
|
+
streak += 1;
|
|
357
|
+
laterAtMs = atMs;
|
|
358
|
+
}
|
|
359
|
+
return streak;
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Memory the running steps already use, which MemAvailable already reflects,
|
|
363
|
+
* so the budget does not count it twice. Measured from the dedicated cgroup
|
|
364
|
+
* above its idle baseline; without one, a step admitted longer than the ramp
|
|
365
|
+
* window ago is assumed to hold its reservation. Never above the reservations.
|
|
366
|
+
*/
|
|
367
|
+
runningStepsMemoryBytes(tokens) {
|
|
368
|
+
const snapshot = this.options.load.current();
|
|
369
|
+
const ownMemory = snapshot?.ownCgroupDedicated ? snapshot.ownCgroup?.memoryAnonBytes ?? null : null;
|
|
370
|
+
if (tokens.length === 0) {
|
|
371
|
+
if (ownMemory !== null)
|
|
372
|
+
this.idleOwnMemoryBytes = ownMemory;
|
|
373
|
+
return 0;
|
|
374
|
+
}
|
|
375
|
+
const reserved = tokens.reduce((sum, token) => sum + token.cost.memoryBytes, 0);
|
|
376
|
+
if (ownMemory !== null && this.idleOwnMemoryBytes !== null) {
|
|
377
|
+
return Math.min(reserved, Math.max(0, ownMemory - this.idleOwnMemoryBytes));
|
|
378
|
+
}
|
|
379
|
+
const now = this.options.now?.() ?? Date.now();
|
|
380
|
+
return tokens
|
|
381
|
+
.filter(token => now - Date.parse(token.admittedAt) >= this.config.memoryRampMs)
|
|
382
|
+
.reduce((sum, token) => sum + token.cost.memoryBytes, 0);
|
|
383
|
+
}
|
|
384
|
+
logicalCpus() {
|
|
385
|
+
const reported = this.options.load.facts()?.logicalThreads;
|
|
386
|
+
if (reported && reported > 0)
|
|
387
|
+
return reported;
|
|
388
|
+
return Math.max(1, typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length);
|
|
389
|
+
}
|
|
390
|
+
settle(waiter, complete) {
|
|
391
|
+
if (waiter.settled)
|
|
392
|
+
return;
|
|
393
|
+
waiter.settled = true;
|
|
394
|
+
if (waiter.deadline)
|
|
395
|
+
clearTimeout(waiter.deadline);
|
|
396
|
+
waiter.signal?.removeEventListener("abort", waiter.abort);
|
|
397
|
+
const index = this.waiters.indexOf(waiter);
|
|
398
|
+
if (index >= 0)
|
|
399
|
+
this.waiters.splice(index, 1);
|
|
400
|
+
if (this.waiters.length === 0)
|
|
401
|
+
this.disarmRecheck();
|
|
402
|
+
// A waiter that left without admission gives up its place now, not when its ticket lapses.
|
|
403
|
+
if (waiter.ticket)
|
|
404
|
+
void this.ledger.transaction(() => undefined).then(outcome => this.applyHeldOutcome(outcome), () => undefined);
|
|
405
|
+
waiter.ticket = null;
|
|
406
|
+
complete();
|
|
407
|
+
}
|
|
408
|
+
/** Renewed tokens reset their lease clock; fenced ones stop their steps (they keep their cost until released). */
|
|
409
|
+
applyHeldOutcome(outcome) {
|
|
410
|
+
const nowMs = monotonicNowMs();
|
|
411
|
+
for (const token of outcome.renewed) {
|
|
412
|
+
const entry = this.held.get(token.tokenId);
|
|
413
|
+
if (entry?.token.fencingToken === token.fencingToken)
|
|
414
|
+
entry.renewedAtMs = nowMs;
|
|
415
|
+
}
|
|
416
|
+
for (const token of outcome.fenced) {
|
|
417
|
+
const entry = this.held.get(token.tokenId);
|
|
418
|
+
if (!entry || entry.token.fencingToken !== token.fencingToken)
|
|
419
|
+
continue;
|
|
420
|
+
entry.fencedError ??= new HostCapacityTokenFencedError(token.tokenId, "renew");
|
|
421
|
+
this.lose(entry, entry.fencedError);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
/** The step must stop: its reservation is no longer guaranteed. */
|
|
425
|
+
lose(entry, reason) {
|
|
426
|
+
if (entry.gone || entry.releasing || entry.fencedController.signal.aborted)
|
|
427
|
+
return;
|
|
428
|
+
entry.fencedController.abort(reason);
|
|
429
|
+
}
|
|
430
|
+
/** Ledger failures reach every queued step instead of leaving it to time out. */
|
|
431
|
+
failWaiters(error) {
|
|
432
|
+
const failure = error instanceof HostCapacityLedgerUnavailableError
|
|
433
|
+
? error
|
|
434
|
+
: new HostCapacityLedgerUnavailableError(`the admission decision failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
435
|
+
for (const waiter of [...this.waiters])
|
|
436
|
+
this.settle(waiter, () => waiter.reject(failure));
|
|
437
|
+
}
|
|
438
|
+
async attachProcess(entry, stepProcess) {
|
|
439
|
+
if (entry.fencedError)
|
|
440
|
+
throw entry.fencedError;
|
|
441
|
+
if (entry.gone || entry.releasing)
|
|
442
|
+
return;
|
|
443
|
+
const outcome = await this.ledger.transaction(transaction => transaction.attach(entry.token.tokenId, entry.token.fencingToken, stepProcess));
|
|
444
|
+
this.applyHeldOutcome(outcome);
|
|
445
|
+
if (outcome.result)
|
|
446
|
+
entry.token = outcome.result;
|
|
447
|
+
else
|
|
448
|
+
throw entry.fencedError ?? new HostCapacityTokenFencedError(entry.token.tokenId, "renew");
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* Returns a step's token. It stays held (and renewed) until the ledger takes
|
|
452
|
+
* it back, so a ledger outage cannot leave it to lapse into a fenced
|
|
453
|
+
* reservation; the renewal timer retries the release. A fenced token is
|
|
454
|
+
* removed too (its step is over) and the release reports the fence.
|
|
455
|
+
*/
|
|
456
|
+
async releaseHeld(entry) {
|
|
457
|
+
if (entry.gone)
|
|
458
|
+
return;
|
|
459
|
+
entry.releasing = true;
|
|
460
|
+
entry.releaseInFlight ??= (async () => {
|
|
461
|
+
try {
|
|
462
|
+
await this.ledger.release(entry.token.tokenId, entry.token.fencingToken);
|
|
463
|
+
this.forget(entry);
|
|
464
|
+
}
|
|
465
|
+
catch (error) {
|
|
466
|
+
if (error instanceof HostCapacityTokenFencedError)
|
|
467
|
+
this.forget(entry);
|
|
468
|
+
throw error;
|
|
469
|
+
}
|
|
470
|
+
finally {
|
|
471
|
+
entry.releaseInFlight = null;
|
|
472
|
+
void this.drain();
|
|
473
|
+
}
|
|
474
|
+
})();
|
|
475
|
+
return await entry.releaseInFlight;
|
|
476
|
+
}
|
|
477
|
+
forget(entry) {
|
|
478
|
+
entry.gone = true;
|
|
479
|
+
this.held.delete(entry.token.tokenId);
|
|
480
|
+
if (this.held.size === 0)
|
|
481
|
+
this.disarmRenewal();
|
|
482
|
+
}
|
|
483
|
+
armRecheck() {
|
|
484
|
+
if (this.recheckTimer)
|
|
485
|
+
return;
|
|
486
|
+
// Capacity can return without a local release: another process's token, a
|
|
487
|
+
// new pressure sample, or external load ending.
|
|
488
|
+
this.recheckTimer = setInterval(() => void this.drain(), this.config.recheckIntervalMs);
|
|
489
|
+
this.recheckTimer.unref?.();
|
|
490
|
+
}
|
|
491
|
+
disarmRecheck() {
|
|
492
|
+
if (this.recheckTimer)
|
|
493
|
+
clearInterval(this.recheckTimer);
|
|
494
|
+
this.recheckTimer = null;
|
|
495
|
+
}
|
|
496
|
+
armRenewal() {
|
|
497
|
+
if (this.renewTimer)
|
|
498
|
+
return;
|
|
499
|
+
this.renewTimer = setInterval(() => void this.renewHeld(), Math.max(10, Math.floor(this.config.leaseMs / 4)));
|
|
500
|
+
this.renewTimer.unref?.();
|
|
501
|
+
}
|
|
502
|
+
disarmRenewal() {
|
|
503
|
+
if (this.renewTimer)
|
|
504
|
+
clearInterval(this.renewTimer);
|
|
505
|
+
this.renewTimer = null;
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* The step ended but part of its process tree may still run: its token stays
|
|
509
|
+
* held and renewed, with its cost, and the step's own termination check is
|
|
510
|
+
* retried on every renewal tick until it proves the tree gone.
|
|
511
|
+
*/
|
|
512
|
+
retainUntilStopped(entry, stillGone, reason) {
|
|
513
|
+
if (entry.gone || entry.releasing)
|
|
514
|
+
return;
|
|
515
|
+
this.lose(entry, reason);
|
|
516
|
+
const terminate = this.options.terminateStep ?? terminateHostLoadStepProcess;
|
|
517
|
+
entry.retainedUntil = stillGone
|
|
518
|
+
// The tree recorded on the token (supervised builds, installs) is stopped and checked.
|
|
519
|
+
?? (entry.token.stepProcess ? async () => await terminate(entry.token.stepProcess) : "attempt_teardown");
|
|
520
|
+
this.armRenewal();
|
|
521
|
+
// Recorded in the ledger so the attempt's own next steps, in any process, do not
|
|
522
|
+
// wait for the slot this token keeps until the step's remains are gone.
|
|
523
|
+
void this.ledger.transaction(transaction => transaction.retain(entry.token.tokenId, entry.token.fencingToken))
|
|
524
|
+
.then(outcome => {
|
|
525
|
+
// Kept on the held entry too: a ledger rebuilt from held tokens must not lose the marker.
|
|
526
|
+
if (outcome.result)
|
|
527
|
+
entry.token = outcome.result;
|
|
528
|
+
this.applyHeldOutcome(outcome);
|
|
529
|
+
void this.drain();
|
|
530
|
+
})
|
|
531
|
+
.catch(() => undefined);
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Attempt teardown stopped the attempt's processes (its process supervisor
|
|
535
|
+
* proved them gone): tokens kept for a tree nothing else can check are returned.
|
|
536
|
+
*/
|
|
537
|
+
async releaseRetainedAfterTeardown(dispatchAttemptId) {
|
|
538
|
+
if (!this.enabled)
|
|
539
|
+
return;
|
|
540
|
+
const settled = [...this.held.values()].filter(entry => entry.token.dispatchAttemptId === dispatchAttemptId && entry.retainedUntil === "attempt_teardown");
|
|
541
|
+
for (const entry of settled)
|
|
542
|
+
entry.retainedUntil = null;
|
|
543
|
+
await Promise.allSettled(settled.map(entry => this.releaseHeld(entry)));
|
|
544
|
+
}
|
|
545
|
+
checkRetained(entry) {
|
|
546
|
+
if (!entry.retainedUntil || entry.retainedUntil === "attempt_teardown" || entry.retainCheck)
|
|
547
|
+
return;
|
|
548
|
+
const stillGone = entry.retainedUntil;
|
|
549
|
+
entry.retainCheck = (async () => {
|
|
550
|
+
try {
|
|
551
|
+
if (await stillGone().catch(() => false)) {
|
|
552
|
+
entry.retainedUntil = null;
|
|
553
|
+
await this.releaseHeld(entry).catch(() => undefined);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
finally {
|
|
557
|
+
entry.retainCheck = null;
|
|
558
|
+
}
|
|
559
|
+
})();
|
|
560
|
+
}
|
|
561
|
+
async renewHeld() {
|
|
562
|
+
if (this.held.size === 0)
|
|
563
|
+
return;
|
|
564
|
+
for (const entry of this.held.values()) {
|
|
565
|
+
// A release the ledger could not take is retried until it lands.
|
|
566
|
+
if (entry.releasing && !entry.releaseInFlight)
|
|
567
|
+
void this.releaseHeld(entry).catch(() => undefined);
|
|
568
|
+
this.checkRetained(entry);
|
|
569
|
+
}
|
|
570
|
+
try {
|
|
571
|
+
// The ledger renews every held token at the start of each transaction and
|
|
572
|
+
// reports the fenced ones.
|
|
573
|
+
this.applyHeldOutcome(await this.ledger.transaction(() => undefined));
|
|
574
|
+
}
|
|
575
|
+
catch (error) {
|
|
576
|
+
// A brief outage is retried on the next tick. Once a whole lease passes
|
|
577
|
+
// without a renewal, another process may already have fenced the token.
|
|
578
|
+
const nowMs = monotonicNowMs();
|
|
579
|
+
for (const entry of this.held.values()) {
|
|
580
|
+
if (nowMs - entry.renewedAtMs < this.config.leaseMs)
|
|
581
|
+
continue;
|
|
582
|
+
this.lose(entry, error instanceof HostCapacityLedgerUnavailableError
|
|
583
|
+
? error
|
|
584
|
+
: new HostCapacityLedgerUnavailableError("the host load token could not be renewed.", { cause: error }));
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
/** The cgroup limit's headroom when one is set, never above host MemAvailable. */
|
|
590
|
+
function tighterMemory(hostAvailable, cgroupHeadroom) {
|
|
591
|
+
if (cgroupHeadroom === null)
|
|
592
|
+
return hostAvailable;
|
|
593
|
+
return hostAvailable === null ? cgroupHeadroom : Math.min(hostAvailable, cgroupHeadroom);
|
|
594
|
+
}
|
|
595
|
+
function abortError(signal) {
|
|
596
|
+
if (signal.reason instanceof Error)
|
|
597
|
+
return signal.reason;
|
|
598
|
+
const error = new Error(typeof signal.reason === "string" ? signal.reason : "The host capacity wait was cancelled.");
|
|
599
|
+
error.name = "AbortError";
|
|
600
|
+
return error;
|
|
601
|
+
}
|
|
602
|
+
/** The lower of two optional limits; null when neither is set. */
|
|
603
|
+
function lowestLimit(a, b) {
|
|
604
|
+
if (a === null)
|
|
605
|
+
return b;
|
|
606
|
+
if (b === null)
|
|
607
|
+
return a;
|
|
608
|
+
return Math.min(a, b);
|
|
609
|
+
}
|
|
610
|
+
const slotFreeDecision = {
|
|
611
|
+
admitted: true,
|
|
612
|
+
reason: "admitted",
|
|
613
|
+
cpuBudgetCores: null,
|
|
614
|
+
memoryBudgetBytes: null,
|
|
615
|
+
reservedCpuCores: 0,
|
|
616
|
+
reservedMemoryBytes: 0,
|
|
617
|
+
detail: "The step takes no host test slot and the host budget is off.",
|
|
618
|
+
};
|
|
619
|
+
/** Admits a slot-free step at once, without a ledger token: nothing would count it. */
|
|
620
|
+
function slotFreeAdmission(request) {
|
|
621
|
+
return {
|
|
622
|
+
tokenId: `slot-free-${randomUUID()}`,
|
|
623
|
+
fencingToken: 0,
|
|
624
|
+
stepClass: request.stepClass,
|
|
625
|
+
waitMs: 0,
|
|
626
|
+
decision: slotFreeDecision,
|
|
627
|
+
fenced: new AbortController().signal,
|
|
628
|
+
attachProcess: async () => undefined,
|
|
629
|
+
release: async () => undefined,
|
|
630
|
+
retainUntilStopped: () => undefined,
|
|
631
|
+
};
|
|
632
|
+
}
|