@loucompanion/forge-bridge 0.1.4-dev.bbb61d3d6127 → 0.1.4-dev.c1ae24134918
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge/bridge.service.js +10 -4
- package/dist/cli/cli.service.js +1 -1
- package/dist/runtime/host-load-child-environment.d.ts +22 -0
- package/dist/runtime/host-load-child-environment.js +65 -0
- package/dist/runtime/host-load-forge-cgroups.d.ts +41 -0
- package/dist/runtime/host-load-forge-cgroups.js +93 -4
- package/dist/runtime/host-load-governor.d.ts +60 -11
- package/dist/runtime/host-load-governor.js +145 -41
- package/dist/runtime/host-load-sampler.d.ts +5 -0
- package/dist/runtime/host-load-sampler.js +12 -4
- package/dist/runtime/host-load-step-class.d.ts +35 -0
- package/dist/runtime/host-load-step-class.js +60 -0
- package/dist/runtime/host-load-step-reaper.d.ts +27 -0
- package/dist/runtime/host-load-step-reaper.js +95 -0
- package/dist/runtime/host-load-step-run.d.ts +73 -0
- package/dist/runtime/host-load-step-run.js +102 -0
- package/dist/runtime/host-load-token-ledger.d.ts +58 -19
- package/dist/runtime/host-load-token-ledger.js +111 -35
- package/dist/runtime/host-runtime-lease.d.ts +4 -1
- package/dist/runtime/host-runtime-lease.js +59 -5
- package/dist/sandbox/host-capacity-broker.d.ts +107 -0
- package/dist/sandbox/host-capacity-broker.js +315 -0
- package/dist/sandbox/runtime.d.ts +10 -1
- package/dist/sandbox/runtime.js +45 -2
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/session/managed-attempt-tools.js +120 -24
- package/dist/session/managed-command-host-load.d.ts +45 -0
- package/dist/session/managed-command-host-load.js +82 -0
- package/dist/session/phase-completion.d.ts +2 -0
- package/dist/session/phase-completion.runtime.d.ts +1 -1
- package/dist/session/phase-completion.runtime.js +14 -6
- package/dist/session/pre-publication-host-load.js +31 -16
- package/dist/session/pre-publication-process.d.ts +3 -0
- package/dist/session/pre-publication-process.js +23 -11
- package/dist/session/pre-publication-validation.js +4 -0
- package/dist/session/provider-cli/provider-cli.process.js +2 -2
- package/dist/session/provider-cli/provider-cli.service.js +20 -12
- package/dist/session/provider-cli/provider-cli.types.d.ts +4 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
- package/dist/session/sandbox-host-capacity-gate.js +229 -0
- package/dist/session/session.service.js +16 -4
- package/dist/shared/process/host-process-supervisor.d.ts +1 -0
- package/dist/shared/process/host-process-supervisor.js +1 -1
- package/dist/shared/process/process-tree.d.ts +52 -0
- package/dist/shared/process/process-tree.js +144 -0
- package/dist/shared/process/process.d.ts +67 -0
- package/dist/shared/process/process.js +213 -11
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/dependency-warmer.d.ts +25 -0
- package/dist/worktree/dependency-warmer.js +46 -10
- package/dist/worktree/worktree.service.d.ts +6 -1
- package/dist/worktree/worktree.service.js +14 -2
- package/dist/worktree/worktree.types.d.ts +7 -0
- package/package.json +1 -1
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { HostLoadAdmissionDecision } from "./host-load-admission.js";
|
|
2
|
+
import type { HostLoadAdmission, HostLoadStepGate } from "./host-load-governor.js";
|
|
3
|
+
import type { HostLoadStepProcess } from "./host-load-step-reaper.js";
|
|
4
|
+
import type { HostLoadStepClassification } from "./host-load-step-class.js";
|
|
5
|
+
import type { HostLoadTokenPriority } from "./host-load-token-ledger.js";
|
|
6
|
+
export interface HostGovernedStep {
|
|
7
|
+
readonly classification: HostLoadStepClassification;
|
|
8
|
+
/** What the step is, for diagnostics. */
|
|
9
|
+
readonly label: string;
|
|
10
|
+
readonly dispatchAttemptId: string | null;
|
|
11
|
+
readonly priority: HostLoadTokenPriority;
|
|
12
|
+
readonly signal?: AbortSignal;
|
|
13
|
+
/** Called once, when the step first has to wait for capacity. */
|
|
14
|
+
readonly onWaiting?: (decision: HostLoadAdmissionDecision) => void | Promise<void>;
|
|
15
|
+
/**
|
|
16
|
+
* The step records its own fenced outcome (a managed command's receipt). Otherwise a
|
|
17
|
+
* step whose token was reclaimed while it ran fails with host_capacity_token_fenced.
|
|
18
|
+
*/
|
|
19
|
+
readonly reportsOwnFence?: boolean;
|
|
20
|
+
/** Called when the token could not be returned; it then lapses with its lease. */
|
|
21
|
+
readonly onReleaseFailed?: (error: unknown) => void | Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
/** Queue time, or null when the governor is off and nothing was queued. */
|
|
24
|
+
export type HostLoadWait = number | null;
|
|
25
|
+
/** What an admitted step gets from its token; both absent while the governor is off. */
|
|
26
|
+
export interface HostLoadStepControl {
|
|
27
|
+
/** Aborted when the token was reclaimed: the step must stop. */
|
|
28
|
+
readonly fenced?: AbortSignal;
|
|
29
|
+
/** Records the step's process tree so a reclaim stops it before reusing its capacity. */
|
|
30
|
+
readonly attachProcess?: (stepProcess: HostLoadStepProcess) => Promise<void>;
|
|
31
|
+
/**
|
|
32
|
+
* For a step that reports its own outcome (a managed command's receipt) when its
|
|
33
|
+
* process tree could not be proven gone: the token is kept, not returned, until
|
|
34
|
+
* `stillGone` proves it (null: see HostLoadAdmission.retainUntilStopped).
|
|
35
|
+
*/
|
|
36
|
+
readonly holdUntilStopped?: (stillGone: (() => Promise<boolean>) | null, reason: Error) => void;
|
|
37
|
+
}
|
|
38
|
+
/** Why a step's token is kept after it ended, and what proves its tree gone. */
|
|
39
|
+
export interface HostLoadRetention {
|
|
40
|
+
readonly stillGone: (() => Promise<boolean>) | null;
|
|
41
|
+
readonly reason: Error;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The retention a step's failure calls for: a tree that could not be proven gone,
|
|
45
|
+
* whether the runner said so with its own check (ProcessTreeTerminationError) or a
|
|
46
|
+
* supervisor did (host_process_supervisor_termination_failed, possibly wrapped).
|
|
47
|
+
*/
|
|
48
|
+
export declare function retentionFor(error: unknown): HostLoadRetention | null;
|
|
49
|
+
/**
|
|
50
|
+
* With the governor off (or no gate), `run` is called directly with a null
|
|
51
|
+
* wait, so behavior is unchanged. With it on, `run` starts only after
|
|
52
|
+
* admission, so the step's own timers never include queue time, and the token
|
|
53
|
+
* is returned when `run` settles, whether it succeeded, failed or was stopped.
|
|
54
|
+
*/
|
|
55
|
+
export declare function runHostGovernedStep<T>(gate: HostLoadStepGate | undefined, step: HostGovernedStep, run: (hostLoadWaitMs: HostLoadWait, control: HostLoadStepControl) => Promise<T>): Promise<T>;
|
|
56
|
+
/**
|
|
57
|
+
* Returns a step's token, unless part of its process tree could not be proven
|
|
58
|
+
* gone: the token (and its cost) is then kept until the tree is.
|
|
59
|
+
*/
|
|
60
|
+
export declare function returnHostLoadToken(admission: HostLoadAdmission, retention: HostLoadRetention | null, onReleaseFailed?: (error: unknown) => void | Promise<void>): Promise<void>;
|
|
61
|
+
/**
|
|
62
|
+
* A step stopped because its token was reclaimed reports host_capacity_token_fenced
|
|
63
|
+
* (retryable), not the exit status or error it died with.
|
|
64
|
+
*/
|
|
65
|
+
export declare function throwIfFenced<T>(fenced: AbortSignal, outcome: T): T;
|
|
66
|
+
/**
|
|
67
|
+
* Records a supervised step's process tree on its host load token, from the
|
|
68
|
+
* metadata its process supervisor wrote (`FORGE_PROCESS_SUPERVISOR_METADATA_PATH`):
|
|
69
|
+
* a reclaim then stops exactly this tree before reusing its capacity. Rejects when
|
|
70
|
+
* the tree cannot be read or recorded; the caller must then stop the step, since
|
|
71
|
+
* it would otherwise run on without a reservation the host can account for.
|
|
72
|
+
*/
|
|
73
|
+
export declare function attachSupervisedStepProcess(control: HostLoadStepControl, metadataPath: string): Promise<void>;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import { isProcessTreeTerminationUnproven, ProcessTreeTerminationError } from "../shared/process/process.js";
|
|
3
|
+
/**
|
|
4
|
+
* The retention a step's failure calls for: a tree that could not be proven gone,
|
|
5
|
+
* whether the runner said so with its own check (ProcessTreeTerminationError) or a
|
|
6
|
+
* supervisor did (host_process_supervisor_termination_failed, possibly wrapped).
|
|
7
|
+
*/
|
|
8
|
+
export function retentionFor(error) {
|
|
9
|
+
if (error instanceof ProcessTreeTerminationError)
|
|
10
|
+
return { stillGone: error.stillGone, reason: error };
|
|
11
|
+
if (!isProcessTreeTerminationUnproven(error))
|
|
12
|
+
return null;
|
|
13
|
+
return { stillGone: null, reason: error instanceof Error ? error : new Error(String(error)) };
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* With the governor off (or no gate), `run` is called directly with a null
|
|
17
|
+
* wait, so behavior is unchanged. With it on, `run` starts only after
|
|
18
|
+
* admission, so the step's own timers never include queue time, and the token
|
|
19
|
+
* is returned when `run` settles, whether it succeeded, failed or was stopped.
|
|
20
|
+
*/
|
|
21
|
+
export async function runHostGovernedStep(gate, step, run) {
|
|
22
|
+
if (!gate?.enabled)
|
|
23
|
+
return await run(null, {});
|
|
24
|
+
const admission = await gate.acquire({
|
|
25
|
+
stepClass: step.classification.stepClass,
|
|
26
|
+
label: step.label,
|
|
27
|
+
cost: step.classification.cost,
|
|
28
|
+
dispatchAttemptId: step.dispatchAttemptId,
|
|
29
|
+
priority: step.priority,
|
|
30
|
+
}, { signal: step.signal, onWaiting: step.onWaiting });
|
|
31
|
+
let retention = null;
|
|
32
|
+
try {
|
|
33
|
+
let outcome;
|
|
34
|
+
try {
|
|
35
|
+
outcome = await run(Math.round(admission.waitMs), {
|
|
36
|
+
fenced: admission.fenced,
|
|
37
|
+
attachProcess: async (stepProcess) => await admission.attachProcess(stepProcess),
|
|
38
|
+
holdUntilStopped: (stillGone, reason) => { retention = { stillGone, reason }; },
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
// Part of the step may still run: that, not a fence, is what the step failed with.
|
|
43
|
+
const unproven = retentionFor(error);
|
|
44
|
+
if (unproven) {
|
|
45
|
+
retention = unproven;
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
if (step.reportsOwnFence !== true)
|
|
49
|
+
throwIfFenced(admission.fenced, undefined);
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
return step.reportsOwnFence === true ? outcome : throwIfFenced(admission.fenced, outcome);
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
await returnHostLoadToken(admission, retention, step.onReleaseFailed);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Returns a step's token, unless part of its process tree could not be proven
|
|
60
|
+
* gone: the token (and its cost) is then kept until the tree is.
|
|
61
|
+
*/
|
|
62
|
+
export async function returnHostLoadToken(admission, retention, onReleaseFailed) {
|
|
63
|
+
if (retention) {
|
|
64
|
+
admission.retainUntilStopped(retention.stillGone, retention.reason);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
await admission.release();
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
await Promise.resolve(onReleaseFailed?.(error)).catch(() => undefined);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* A step stopped because its token was reclaimed reports host_capacity_token_fenced
|
|
76
|
+
* (retryable), not the exit status or error it died with.
|
|
77
|
+
*/
|
|
78
|
+
export function throwIfFenced(fenced, outcome) {
|
|
79
|
+
if (fenced.aborted)
|
|
80
|
+
throw fenced.reason;
|
|
81
|
+
return outcome;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Records a supervised step's process tree on its host load token, from the
|
|
85
|
+
* metadata its process supervisor wrote (`FORGE_PROCESS_SUPERVISOR_METADATA_PATH`):
|
|
86
|
+
* a reclaim then stops exactly this tree before reusing its capacity. Rejects when
|
|
87
|
+
* the tree cannot be read or recorded; the caller must then stop the step, since
|
|
88
|
+
* it would otherwise run on without a reservation the host can account for.
|
|
89
|
+
*/
|
|
90
|
+
export async function attachSupervisedStepProcess(control, metadataPath) {
|
|
91
|
+
if (!control.attachProcess)
|
|
92
|
+
return;
|
|
93
|
+
const metadata = JSON.parse(await fs.readFile(metadataPath, "utf8"));
|
|
94
|
+
if (typeof metadata.rootPid !== "number" || !Number.isSafeInteger(metadata.rootPid) || metadata.rootPid <= 1) {
|
|
95
|
+
throw new Error(`the step's process supervisor recorded no usable root process in ${metadataPath}.`);
|
|
96
|
+
}
|
|
97
|
+
await control.attachProcess({
|
|
98
|
+
rootPid: metadata.rootPid,
|
|
99
|
+
rootIdentity: typeof metadata.rootIdentity === "string" ? metadata.rootIdentity : null,
|
|
100
|
+
processGroup: metadata.strategy === "unix_process_group",
|
|
101
|
+
});
|
|
102
|
+
}
|
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
import { ForgeFailureError } from "../session/session.types.js";
|
|
2
2
|
import type { HostLoadStepCost } from "./host-load-step-class.js";
|
|
3
|
+
import { type HostLoadStepProcess, type HostLoadStepTerminator } from "./host-load-step-reaper.js";
|
|
3
4
|
/**
|
|
4
5
|
* File-backed token ledger for the host load governor (decision 0013). Every
|
|
5
6
|
* process on the host that runs heavy steps shares it through the coordinator
|
|
6
7
|
* state root. Each token names its owner (pid, OS process birth marker and a
|
|
7
8
|
* per-process instance id), carries a fencing token, and holds an `expiresAt`
|
|
8
|
-
* lease the owner renews. A
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
9
|
+
* lease the owner renews. A lapsed lease with a live owner fences the token:
|
|
10
|
+
* it keeps its reserved cost (the owner's step may still be running), renewals
|
|
11
|
+
* are refused so the owner stops that step, and the capacity returns when the
|
|
12
|
+
* owner releases it or is gone. A dead owner's token is reclaimed only once its
|
|
13
|
+
* step's recorded process tree is stopped and confirmed gone; until then it
|
|
14
|
+
* stays `degraded` and keeps its reserved cost.
|
|
13
15
|
*/
|
|
14
16
|
export type HostLoadTokenPriority = "foreground" | "background";
|
|
15
17
|
export interface HostLoadTokenOwner {
|
|
@@ -30,6 +32,12 @@ export interface HostLoadToken {
|
|
|
30
32
|
readonly owner: HostLoadTokenOwner;
|
|
31
33
|
readonly admittedAt: string;
|
|
32
34
|
readonly expiresAt: string;
|
|
35
|
+
/** The step's process tree, recorded once it launches; the reaper stops it before reuse. */
|
|
36
|
+
readonly stepProcess?: HostLoadStepProcess | null;
|
|
37
|
+
/** The host's suspend counter (hostSuspendedMs) when the lease was last renewed. */
|
|
38
|
+
readonly suspendedMsAtRenewal?: number;
|
|
39
|
+
/** When an expired token's step could not be proven stopped; it keeps its cost meanwhile. */
|
|
40
|
+
readonly degradedAt?: string | null;
|
|
33
41
|
/** Set when the lease lapsed while the owner was still live: cost kept, renewal refused. */
|
|
34
42
|
readonly fencedAt?: string | null;
|
|
35
43
|
}
|
|
@@ -51,6 +59,20 @@ export interface HostLoadLedgerTransaction {
|
|
|
51
59
|
issue(request: HostLoadTokenRequest): HostLoadToken;
|
|
52
60
|
renew(tokenId: string, fencingToken: number): HostLoadToken | null;
|
|
53
61
|
remove(tokenId: string, fencingToken: number): boolean;
|
|
62
|
+
/** Records the step's process tree on its token; null when the token is fenced. */
|
|
63
|
+
attach(tokenId: string, fencingToken: number, stepProcess: HostLoadStepProcess): HostLoadToken | null;
|
|
64
|
+
}
|
|
65
|
+
export interface HostLoadTransactionOutcome<T> {
|
|
66
|
+
readonly result: T;
|
|
67
|
+
readonly reclaimed: readonly HostLoadToken[];
|
|
68
|
+
/**
|
|
69
|
+
* Tokens this owner holds that are fenced (lease lapsed, or lost from the
|
|
70
|
+
* ledger and put back fenced): their steps must stop. They keep their cost
|
|
71
|
+
* until released.
|
|
72
|
+
*/
|
|
73
|
+
readonly fenced: readonly HostLoadToken[];
|
|
74
|
+
/** Tokens this owner holds whose lease this transaction renewed. */
|
|
75
|
+
readonly renewed: readonly HostLoadToken[];
|
|
54
76
|
}
|
|
55
77
|
export interface HostLoadOwnerLiveness {
|
|
56
78
|
isLive(owner: HostLoadTokenOwner): boolean;
|
|
@@ -65,18 +87,14 @@ export interface HostLoadTokenLedgerOptions {
|
|
|
65
87
|
readonly lockTimeoutMs?: number;
|
|
66
88
|
/**
|
|
67
89
|
* Tokens this owner still holds for running steps. Each transaction renews
|
|
68
|
-
* them
|
|
69
|
-
*
|
|
90
|
+
* them before it reclaims anything. One missing from the ledger keeps its
|
|
91
|
+
* cost: it is put back (fenced, unless a quarantine is still recovering).
|
|
70
92
|
*/
|
|
71
93
|
readonly heldTokens?: () => readonly HostLoadToken[];
|
|
72
|
-
/**
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
readonly onHeldTokens?: (outcome: {
|
|
77
|
-
readonly renewed: readonly HostLoadToken[];
|
|
78
|
-
readonly fenced: readonly HostLoadToken[];
|
|
79
|
-
}) => void;
|
|
94
|
+
/** Stops a reclaimed token's step; defaults to the exact process-tree reaper. */
|
|
95
|
+
readonly terminateStep?: HostLoadStepTerminator;
|
|
96
|
+
/** Host suspend counter (test seam); defaults to hostSuspendedMs. */
|
|
97
|
+
readonly suspendedMs?: () => number;
|
|
80
98
|
/** Test seam passed to the ledger lock. */
|
|
81
99
|
readonly beforeStaleLockBreak?: () => Promise<void>;
|
|
82
100
|
}
|
|
@@ -93,6 +111,11 @@ export declare class HostCapacityTokenFencedError extends ForgeFailureError {
|
|
|
93
111
|
export declare function currentHostLoadTokenOwner(): HostLoadTokenOwner;
|
|
94
112
|
/** Owner liveness from the OS: dead pid, or a pid reused by a different process, is gone. */
|
|
95
113
|
export declare const processHostLoadOwnerLiveness: HostLoadOwnerLiveness;
|
|
114
|
+
/**
|
|
115
|
+
* Total time the host has been suspended (Linux: boot-time uptime minus the
|
|
116
|
+
* monotonic clock, which stops while suspended). Zero where it is unknown.
|
|
117
|
+
*/
|
|
118
|
+
export declare function hostSuspendedMs(): number;
|
|
96
119
|
export declare class HostLoadTokenLedger {
|
|
97
120
|
private readonly options;
|
|
98
121
|
private readonly root;
|
|
@@ -103,16 +126,14 @@ export declare class HostLoadTokenLedger {
|
|
|
103
126
|
private readonly lock;
|
|
104
127
|
private tail;
|
|
105
128
|
constructor(options: HostLoadTokenLedgerOptions);
|
|
129
|
+
private suspendedMs;
|
|
106
130
|
private get owner();
|
|
107
131
|
/**
|
|
108
132
|
* Runs `action` under the cross-process ledger lock against the live token
|
|
109
133
|
* set. Dead or expired tokens are reclaimed first, so every admission
|
|
110
134
|
* decision sees only real reservations.
|
|
111
135
|
*/
|
|
112
|
-
transaction<T>(action: (transaction: HostLoadLedgerTransaction) => T | Promise<T>): Promise<
|
|
113
|
-
readonly result: T;
|
|
114
|
-
readonly reclaimed: readonly HostLoadToken[];
|
|
115
|
-
}>;
|
|
136
|
+
transaction<T>(action: (transaction: HostLoadLedgerTransaction) => T | Promise<T>): Promise<HostLoadTransactionOutcome<T>>;
|
|
116
137
|
reclaim(): Promise<readonly HostLoadToken[]>;
|
|
117
138
|
list(): Promise<readonly HostLoadToken[]>;
|
|
118
139
|
/** Extends a token's lease. A fenced, reclaimed or superseded token is rejected. */
|
|
@@ -124,6 +145,24 @@ export declare class HostLoadTokenLedger {
|
|
|
124
145
|
*/
|
|
125
146
|
release(tokenId: string, fencingToken: number): Promise<void>;
|
|
126
147
|
private lockedTransaction;
|
|
148
|
+
/**
|
|
149
|
+
* Decides every token another owner can no longer vouch for (decision 0013):
|
|
150
|
+
* - owner alive but its lease lapsed (it stalled): the token is fenced, never
|
|
151
|
+
* killed, and keeps its cost; the owner stops its own step when it next
|
|
152
|
+
* touches the ledger and returns the capacity when it releases the token;
|
|
153
|
+
* - owner gone with a recorded process tree: the tree is stopped and confirmed
|
|
154
|
+
* gone first, otherwise the token stays degraded and keeps its cost;
|
|
155
|
+
* - owner gone with no recorded tree: degraded, keeping its cost, until the
|
|
156
|
+
* attempt's teardown or the bridge's restart reap proves the step stopped
|
|
157
|
+
* (releaseOrphaned).
|
|
158
|
+
*/
|
|
159
|
+
private reapExpired;
|
|
160
|
+
/**
|
|
161
|
+
* Returns dead owners' tokens that have no recorded process tree once the
|
|
162
|
+
* caller has proven their steps stopped (attempt teardown after its process
|
|
163
|
+
* trees are stopped, or the restart reap after attempt recovery).
|
|
164
|
+
*/
|
|
165
|
+
releaseOrphaned(belongs: (token: HostLoadToken) => boolean): Promise<readonly HostLoadToken[]>;
|
|
127
166
|
private read;
|
|
128
167
|
/**
|
|
129
168
|
* A corrupt ledger is kept aside for inspection and none of its tokens are
|
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
2
3
|
import fs from "node:fs/promises";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import { ForgeFailureError } from "../session/session.types.js";
|
|
5
6
|
import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
|
|
6
7
|
import { HostCapacityLedgerUnavailableError, HostLoadLedgerLock } from "./host-load-ledger-lock.js";
|
|
8
|
+
import { terminateHostLoadStepProcess, validHostLoadStepProcess, } from "./host-load-step-reaper.js";
|
|
7
9
|
const processInstanceId = randomUUID();
|
|
8
10
|
const maximumLedgerBytes = 1024 * 1024;
|
|
11
|
+
/** A degraded token's tree is retried at most this often, so a stuck process cannot stall every admission. */
|
|
12
|
+
const degradedRetryMs = 30_000;
|
|
9
13
|
export class HostCapacityTokenFencedError extends ForgeFailureError {
|
|
10
14
|
tokenId;
|
|
11
15
|
code = "host_capacity_token_fenced";
|
|
@@ -52,6 +56,30 @@ export const processHostLoadOwnerLiveness = {
|
|
|
52
56
|
function linuxProcessIdentity(pid) {
|
|
53
57
|
return process.platform === "linux" ? captureHostProcessIdentity(pid, "linux") : null;
|
|
54
58
|
}
|
|
59
|
+
/** Lapsed: past its lease even after taking away the time the host was suspended since renewal. */
|
|
60
|
+
function leaseLapsed(token, nowMs, suspendedMs) {
|
|
61
|
+
const expiresAtMs = Date.parse(token.expiresAt);
|
|
62
|
+
if (!Number.isFinite(expiresAtMs))
|
|
63
|
+
return true;
|
|
64
|
+
const asleepMs = Math.max(0, suspendedMs - (token.suspendedMsAtRenewal ?? suspendedMs));
|
|
65
|
+
return expiresAtMs + asleepMs <= nowMs;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Total time the host has been suspended (Linux: boot-time uptime minus the
|
|
69
|
+
* monotonic clock, which stops while suspended). Zero where it is unknown.
|
|
70
|
+
*/
|
|
71
|
+
export function hostSuspendedMs() {
|
|
72
|
+
if (process.platform !== "linux")
|
|
73
|
+
return 0;
|
|
74
|
+
try {
|
|
75
|
+
const uptimeMs = Number(readFileSync("/proc/uptime", "utf8").split(/\s+/u)[0]) * 1000;
|
|
76
|
+
const monotonicMs = Number(process.hrtime.bigint() / 1000000n);
|
|
77
|
+
return Number.isFinite(uptimeMs) ? Math.max(0, Math.round(uptimeMs - monotonicMs)) : 0;
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return 0;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
55
83
|
export class HostLoadTokenLedger {
|
|
56
84
|
options;
|
|
57
85
|
root;
|
|
@@ -76,6 +104,9 @@ export class HostLoadTokenLedger {
|
|
|
76
104
|
beforeStaleBreak: options.beforeStaleLockBreak,
|
|
77
105
|
});
|
|
78
106
|
}
|
|
107
|
+
suspendedMs() {
|
|
108
|
+
return (this.options.suspendedMs ?? hostSuspendedMs)();
|
|
109
|
+
}
|
|
79
110
|
get owner() {
|
|
80
111
|
this.resolvedOwner ??= currentHostLoadTokenOwner();
|
|
81
112
|
return this.resolvedOwner;
|
|
@@ -130,42 +161,33 @@ export class HostLoadTokenLedger {
|
|
|
130
161
|
const nowMs = this.now();
|
|
131
162
|
const nowIso = new Date(nowMs).toISOString();
|
|
132
163
|
const expiresAt = () => new Date(this.now() + this.options.leaseMs).toISOString();
|
|
164
|
+
const suspendedMs = this.suspendedMs();
|
|
165
|
+
// Each lease records the host's suspend counter, so time asleep never counts as a missed renewal.
|
|
166
|
+
const lease = () => ({ expiresAt: expiresAt(), suspendedMsAtRenewal: suspendedMs });
|
|
133
167
|
const recoveringUntil = ledger.recoveringUntil && Date.parse(ledger.recoveringUntil) > nowMs
|
|
134
168
|
? ledger.recoveringUntil
|
|
135
169
|
: null;
|
|
170
|
+
// Running steps of this owner are renewed before anything is reclaimed.
|
|
136
171
|
const key = (token) => `${token.tokenId}:${token.fencingToken}`;
|
|
137
|
-
// Running steps of this owner are renewed (or restored) before anything is reclaimed.
|
|
138
172
|
const held = this.options.heldTokens?.() ?? [];
|
|
139
|
-
const
|
|
140
|
-
const
|
|
173
|
+
const heldIds = new Set(held.map(key));
|
|
174
|
+
const ledgerIds = new Set(ledger.tokens.map(key));
|
|
141
175
|
// A held token missing from the ledger keeps its cost. While a quarantined
|
|
142
176
|
// ledger is recovering no step was admitted against the gap, so it is put
|
|
143
177
|
// back as is; otherwise capacity may have been reused, so it comes back fenced.
|
|
144
178
|
const restored = held
|
|
145
|
-
.filter(token => !
|
|
146
|
-
.map(token => ({
|
|
147
|
-
...token,
|
|
148
|
-
expiresAt: expiresAt(),
|
|
149
|
-
fencedAt: token.fencedAt ?? (recoveringUntil ? null : nowIso),
|
|
150
|
-
}));
|
|
179
|
+
.filter(token => !ledgerIds.has(key(token)))
|
|
180
|
+
.map(token => ({ ...token, ...lease(), fencedAt: token.fencedAt ?? (recoveringUntil ? null : nowIso) }));
|
|
151
181
|
const current = [
|
|
152
|
-
...ledger.tokens.map(token =>
|
|
182
|
+
...ledger.tokens.map(token => heldIds.has(key(token)) && !token.fencedAt ? { ...token, ...lease() } : token),
|
|
153
183
|
...restored,
|
|
154
184
|
];
|
|
155
|
-
|
|
156
|
-
// fences the token and keeps its cost: its step may still be running.
|
|
157
|
-
const reclaimed = current.filter(token => !this.liveness.isLive(token.owner));
|
|
158
|
-
let fencedNow = 0;
|
|
185
|
+
const { reclaimed, degraded, fencedNow } = await this.reapExpired(current, nowMs, suspendedMs, nowIso);
|
|
159
186
|
let tokens = current
|
|
160
187
|
.filter(token => !reclaimed.includes(token))
|
|
161
|
-
.map(token =>
|
|
162
|
-
if (token.fencedAt || !leaseLapsed(token, nowMs))
|
|
163
|
-
return token;
|
|
164
|
-
fencedNow += 1;
|
|
165
|
-
return { ...token, fencedAt: nowIso };
|
|
166
|
-
});
|
|
188
|
+
.map(token => degraded.get(token) ?? fencedNow.get(token) ?? token);
|
|
167
189
|
let nextFencingToken = Math.max(ledger.nextFencingToken, ...restored.map(token => token.fencingToken + 1));
|
|
168
|
-
let changed = quarantined || reclaimed.length > 0 || fencedNow > 0 || held.length > 0
|
|
190
|
+
let changed = quarantined || reclaimed.length > 0 || degraded.size > 0 || fencedNow.size > 0 || held.length > 0
|
|
169
191
|
|| (ledger.recoveringUntil !== undefined && recoveringUntil === null);
|
|
170
192
|
const transaction = {
|
|
171
193
|
get tokens() { return tokens; },
|
|
@@ -181,7 +203,7 @@ export class HostLoadTokenLedger {
|
|
|
181
203
|
priority: request.priority,
|
|
182
204
|
owner: this.owner,
|
|
183
205
|
admittedAt: new Date(this.now()).toISOString(),
|
|
184
|
-
|
|
206
|
+
...lease(),
|
|
185
207
|
};
|
|
186
208
|
nextFencingToken += 1;
|
|
187
209
|
tokens = [...tokens, token];
|
|
@@ -192,11 +214,20 @@ export class HostLoadTokenLedger {
|
|
|
192
214
|
const index = tokens.findIndex(token => token.tokenId === tokenId && token.fencingToken === fencingToken);
|
|
193
215
|
if (index < 0 || tokens[index].fencedAt)
|
|
194
216
|
return null;
|
|
195
|
-
const renewed = { ...tokens[index],
|
|
217
|
+
const renewed = { ...tokens[index], ...lease() };
|
|
196
218
|
tokens = tokens.map((token, position) => position === index ? renewed : token);
|
|
197
219
|
changed = true;
|
|
198
220
|
return renewed;
|
|
199
221
|
},
|
|
222
|
+
attach: (tokenId, fencingToken, stepProcess) => {
|
|
223
|
+
const index = tokens.findIndex(token => token.tokenId === tokenId && token.fencingToken === fencingToken);
|
|
224
|
+
if (index < 0 || tokens[index].fencedAt)
|
|
225
|
+
return null;
|
|
226
|
+
const attached = { ...tokens[index], stepProcess };
|
|
227
|
+
tokens = tokens.map((token, position) => position === index ? attached : token);
|
|
228
|
+
changed = true;
|
|
229
|
+
return attached;
|
|
230
|
+
},
|
|
200
231
|
remove: (tokenId, fencingToken) => {
|
|
201
232
|
const before = tokens.length;
|
|
202
233
|
tokens = tokens.filter(token => !(token.tokenId === tokenId && token.fencingToken === fencingToken));
|
|
@@ -217,19 +248,65 @@ export class HostLoadTokenLedger {
|
|
|
217
248
|
...recoveringUntil ? { recoveringUntil } : {},
|
|
218
249
|
});
|
|
219
250
|
}
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
}
|
|
227
|
-
return { result, reclaimed };
|
|
251
|
+
const heldNow = tokens.filter(token => heldIds.has(key(token)));
|
|
252
|
+
return {
|
|
253
|
+
result,
|
|
254
|
+
reclaimed,
|
|
255
|
+
fenced: heldNow.filter(token => Boolean(token.fencedAt)),
|
|
256
|
+
renewed: heldNow.filter(token => !token.fencedAt),
|
|
257
|
+
};
|
|
228
258
|
}
|
|
229
259
|
finally {
|
|
230
260
|
await this.lock.release(lockToken);
|
|
231
261
|
}
|
|
232
262
|
}
|
|
263
|
+
/**
|
|
264
|
+
* Decides every token another owner can no longer vouch for (decision 0013):
|
|
265
|
+
* - owner alive but its lease lapsed (it stalled): the token is fenced, never
|
|
266
|
+
* killed, and keeps its cost; the owner stops its own step when it next
|
|
267
|
+
* touches the ledger and returns the capacity when it releases the token;
|
|
268
|
+
* - owner gone with a recorded process tree: the tree is stopped and confirmed
|
|
269
|
+
* gone first, otherwise the token stays degraded and keeps its cost;
|
|
270
|
+
* - owner gone with no recorded tree: degraded, keeping its cost, until the
|
|
271
|
+
* attempt's teardown or the bridge's restart reap proves the step stopped
|
|
272
|
+
* (releaseOrphaned).
|
|
273
|
+
*/
|
|
274
|
+
async reapExpired(current, nowMs, suspendedMs, nowIso) {
|
|
275
|
+
const reclaimed = [];
|
|
276
|
+
const degraded = new Map();
|
|
277
|
+
const fencedNow = new Map();
|
|
278
|
+
const terminate = this.options.terminateStep ?? terminateHostLoadStepProcess;
|
|
279
|
+
for (const token of current) {
|
|
280
|
+
if (this.liveness.isLive(token.owner)) {
|
|
281
|
+
// Its step may still be running: fence it, but never free its capacity.
|
|
282
|
+
if (!token.fencedAt && leaseLapsed(token, nowMs, suspendedMs))
|
|
283
|
+
fencedNow.set(token, { ...token, fencedAt: nowIso });
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
const lastDegraded = token.degradedAt ? Date.parse(token.degradedAt) : Number.NaN;
|
|
287
|
+
if (Number.isFinite(lastDegraded) && nowMs - lastDegraded < degradedRetryMs)
|
|
288
|
+
continue;
|
|
289
|
+
const gone = Boolean(token.stepProcess) && await terminate(token.stepProcess).catch(() => false);
|
|
290
|
+
if (gone)
|
|
291
|
+
reclaimed.push(token);
|
|
292
|
+
else
|
|
293
|
+
degraded.set(token, { ...token, degradedAt: new Date(nowMs).toISOString() });
|
|
294
|
+
}
|
|
295
|
+
return { reclaimed, degraded, fencedNow };
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Returns dead owners' tokens that have no recorded process tree once the
|
|
299
|
+
* caller has proven their steps stopped (attempt teardown after its process
|
|
300
|
+
* trees are stopped, or the restart reap after attempt recovery).
|
|
301
|
+
*/
|
|
302
|
+
async releaseOrphaned(belongs) {
|
|
303
|
+
return (await this.transaction(transaction => {
|
|
304
|
+
const orphaned = transaction.tokens.filter(token => !token.stepProcess && belongs(token) && !this.liveness.isLive(token.owner));
|
|
305
|
+
for (const token of orphaned)
|
|
306
|
+
transaction.remove(token.tokenId, token.fencingToken);
|
|
307
|
+
return orphaned;
|
|
308
|
+
})).result;
|
|
309
|
+
}
|
|
233
310
|
async read() {
|
|
234
311
|
let content;
|
|
235
312
|
try {
|
|
@@ -306,10 +383,6 @@ export class HostLoadTokenLedger {
|
|
|
306
383
|
}
|
|
307
384
|
}
|
|
308
385
|
}
|
|
309
|
-
function leaseLapsed(token, nowMs) {
|
|
310
|
-
const expiresAtMs = Date.parse(token.expiresAt);
|
|
311
|
-
return !Number.isFinite(expiresAtMs) || expiresAtMs <= nowMs;
|
|
312
|
-
}
|
|
313
386
|
function emptyLedger() {
|
|
314
387
|
return { schemaVersion: 1, nextFencingToken: 1, tokens: [] };
|
|
315
388
|
}
|
|
@@ -341,5 +414,8 @@ function validToken(value) {
|
|
|
341
414
|
&& validOwner(token.owner)
|
|
342
415
|
&& typeof token.admittedAt === "string"
|
|
343
416
|
&& typeof token.expiresAt === "string"
|
|
417
|
+
&& (token.stepProcess === undefined || token.stepProcess === null || validHostLoadStepProcess(token.stepProcess))
|
|
418
|
+
&& (token.suspendedMsAtRenewal === undefined || Number.isFinite(token.suspendedMsAtRenewal))
|
|
419
|
+
&& (token.degradedAt === undefined || token.degradedAt === null || typeof token.degradedAt === "string")
|
|
344
420
|
&& (token.fencedAt === undefined || token.fencedAt === null || typeof token.fencedAt === "string");
|
|
345
421
|
}
|
|
@@ -28,7 +28,7 @@ export interface HostRuntimeAdmissionCheckpoint {
|
|
|
28
28
|
}
|
|
29
29
|
export type HostRuntimeAdmissionCheckpointHandler = (checkpoint: HostRuntimeAdmissionCheckpoint) => void | Promise<void>;
|
|
30
30
|
export interface HostRuntimeProjectCheckpoint {
|
|
31
|
-
readonly code: "host_runtime_build_started" | "host_runtime_build_cached" | "host_runtime_build_completed" | "host_runtime_database_provisioned";
|
|
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
32
|
readonly message: string;
|
|
33
33
|
readonly data?: Readonly<Record<string, unknown>>;
|
|
34
34
|
}
|
|
@@ -108,6 +108,8 @@ export interface HostRuntimeLeaseRuntime {
|
|
|
108
108
|
hasForegroundDemand?(): boolean;
|
|
109
109
|
reap?(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport>;
|
|
110
110
|
snapshot?(): HostRuntimeCapacitySnapshot;
|
|
111
|
+
/** Variables that let the completion MCP server share this host's load governor. */
|
|
112
|
+
hostLoadChildEnvironment?(): Readonly<Record<string, string>>;
|
|
111
113
|
}
|
|
112
114
|
export type HostRuntimeAdmissionPriority = "foreground" | "background";
|
|
113
115
|
export interface HostCapacityResourceSample {
|
|
@@ -154,6 +156,7 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
|
|
|
154
156
|
/** Installs the decision 0013 accept-time requirements recheck for host attempts. */
|
|
155
157
|
setRequirementsCheck(check: HostRequirementsCheck | null): void;
|
|
156
158
|
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);
|
|
159
|
+
hostLoadChildEnvironment(): Readonly<Record<string, string>>;
|
|
157
160
|
reap(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport>;
|
|
158
161
|
snapshot(): HostRuntimeCapacitySnapshot;
|
|
159
162
|
hasForegroundDemand(): boolean;
|