@loucompanion/forge-bridge 0.1.4-dev.19e5db286f12 → 0.1.4-dev.1ec1b222a073

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.
Files changed (90) hide show
  1. package/dist/bridge/bridge.service.d.ts +2 -0
  2. package/dist/bridge/bridge.service.js +28 -4
  3. package/dist/bridge/bridge.types.d.ts +5 -0
  4. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  5. package/dist/bridge/runner-host-capabilities.js +4 -0
  6. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  7. package/dist/bridge/test-postgres-capability.js +120 -0
  8. package/dist/cli/cli.service.js +1 -1
  9. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  10. package/dist/runtime/host-load-child-environment.js +65 -0
  11. package/dist/runtime/host-load-forge-cgroups.d.ts +41 -0
  12. package/dist/runtime/host-load-forge-cgroups.js +93 -4
  13. package/dist/runtime/host-load-governor.d.ts +60 -11
  14. package/dist/runtime/host-load-governor.js +145 -41
  15. package/dist/runtime/host-load-sampler.d.ts +5 -0
  16. package/dist/runtime/host-load-sampler.js +12 -4
  17. package/dist/runtime/host-load-step-class.d.ts +35 -0
  18. package/dist/runtime/host-load-step-class.js +60 -0
  19. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  20. package/dist/runtime/host-load-step-reaper.js +95 -0
  21. package/dist/runtime/host-load-step-run.d.ts +73 -0
  22. package/dist/runtime/host-load-step-run.js +102 -0
  23. package/dist/runtime/host-load-token-ledger.d.ts +58 -19
  24. package/dist/runtime/host-load-token-ledger.js +111 -35
  25. package/dist/runtime/host-runtime-contract.d.ts +3 -0
  26. package/dist/runtime/host-runtime-contract.js +4 -1
  27. package/dist/runtime/host-runtime-lease.d.ts +10 -2
  28. package/dist/runtime/host-runtime-lease.js +74 -5
  29. package/dist/runtime/host-runtime-promotion.js +12 -0
  30. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  31. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  32. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  33. package/dist/runtime/host-runtime-requirements.js +117 -0
  34. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  35. package/dist/sandbox/host-capacity-broker.js +315 -0
  36. package/dist/sandbox/runtime.d.ts +10 -1
  37. package/dist/sandbox/runtime.js +45 -2
  38. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  39. package/dist/sandbox/sandbox-cgroups.js +42 -0
  40. package/dist/session/managed-attempt-tools.d.ts +2 -0
  41. package/dist/session/managed-attempt-tools.js +156 -37
  42. package/dist/session/managed-command-host-load.d.ts +45 -0
  43. package/dist/session/managed-command-host-load.js +82 -0
  44. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  45. package/dist/session/mcp-argument-coercion.js +121 -0
  46. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  47. package/dist/session/phase-completion.artifacts.js +94 -25
  48. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  49. package/dist/session/phase-completion.command-validation.js +77 -0
  50. package/dist/session/phase-completion.d.ts +4 -0
  51. package/dist/session/phase-completion.helpers.js +13 -12
  52. package/dist/session/phase-completion.js +4 -0
  53. package/dist/session/phase-completion.prompts.js +6 -1
  54. package/dist/session/phase-completion.runtime.d.ts +5 -3
  55. package/dist/session/phase-completion.runtime.js +49 -19
  56. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  57. package/dist/session/phase-completion.schema-parts.js +188 -0
  58. package/dist/session/phase-completion.schemas.d.ts +3 -3
  59. package/dist/session/phase-completion.schemas.js +184 -209
  60. package/dist/session/phase-completion.validation.d.ts +2 -3
  61. package/dist/session/phase-completion.validation.js +46 -92
  62. package/dist/session/pre-publication-host-load.js +31 -16
  63. package/dist/session/pre-publication-process.d.ts +3 -0
  64. package/dist/session/pre-publication-process.js +23 -11
  65. package/dist/session/pre-publication-validation.js +4 -0
  66. package/dist/session/provider-cli/provider-cli.process.js +2 -2
  67. package/dist/session/provider-cli/provider-cli.prompts.js +1 -1
  68. package/dist/session/provider-cli/provider-cli.service.js +20 -12
  69. package/dist/session/provider-cli/provider-cli.types.d.ts +4 -0
  70. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  71. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  72. package/dist/session/session.base.d.ts +3 -0
  73. package/dist/session/session.service.d.ts +2 -0
  74. package/dist/session/session.service.js +21 -4
  75. package/dist/session/session.types.d.ts +3 -0
  76. package/dist/session/session.types.js +1 -1
  77. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  78. package/dist/shared/process/host-process-supervisor.js +1 -1
  79. package/dist/shared/process/process-tree.d.ts +52 -0
  80. package/dist/shared/process/process-tree.js +144 -0
  81. package/dist/shared/process/process.d.ts +67 -0
  82. package/dist/shared/process/process.js +213 -11
  83. package/dist/version.d.ts +1 -1
  84. package/dist/version.js +1 -1
  85. package/dist/worktree/dependency-warmer.d.ts +25 -0
  86. package/dist/worktree/dependency-warmer.js +46 -10
  87. package/dist/worktree/worktree.service.d.ts +6 -1
  88. package/dist/worktree/worktree.service.js +14 -2
  89. package/dist/worktree/worktree.types.d.ts +7 -0
  90. package/package.json +1 -1
@@ -3,6 +3,7 @@ import { type HostLoadAdmissionDecision } from "./host-load-admission.js";
3
3
  import { type HostLoadGovernorConfig } from "./host-load-governor-config.js";
4
4
  import type { HostLoadGovernorSource } from "./host-load-sampler.js";
5
5
  import type { HostLoadStepCost } from "./host-load-step-class.js";
6
+ import { type HostLoadStepProcess, type HostLoadStepTerminator } from "./host-load-step-reaper.js";
6
7
  import { type HostLoadOwnerLiveness, type HostLoadToken, type HostLoadTokenOwner, type HostLoadTokenPriority } from "./host-load-token-ledger.js";
7
8
  export interface HostLoadStepRequest {
8
9
  readonly stepClass: string;
@@ -25,17 +26,31 @@ export interface HostLoadAdmission {
25
26
  readonly waitMs: number;
26
27
  readonly decision: HostLoadAdmissionDecision;
27
28
  /**
28
- * Aborted when the reservation is lost while the step runs: the token was
29
- * fenced (its lease lapsed and another process saw it), or the ledger could
30
- * not renew it for a whole lease. The reason is the failure; the step must stop.
29
+ * Aborted when the reservation is lost while the step runs: with
30
+ * host_capacity_token_fenced when the token was fenced (this owner stalled
31
+ * past its lease and another process saw it), or with
32
+ * host_capacity_ledger_unavailable when it could not be renewed for a whole
33
+ * lease. The step must stop; the token keeps its cost until it is released.
31
34
  */
32
- readonly signal: AbortSignal;
35
+ readonly fenced: AbortSignal;
36
+ /** Records the step's process tree, so a reclaim stops it before reusing its capacity. */
37
+ attachProcess(stepProcess: HostLoadStepProcess): Promise<void>;
33
38
  /** Returns the token. Rejects with host_capacity_token_fenced if it was fenced or reclaimed. */
34
39
  release(): Promise<void>;
40
+ /**
41
+ * Instead of release: the step ended but part of its process tree could not
42
+ * be proven gone. The token stays held, with its cost, and is returned only
43
+ * once `stillGone` (re-checked on every renewal) resolves true. Without a
44
+ * check, the token's recorded process tree is checked instead; with neither,
45
+ * the token is kept until attempt teardown has stopped the attempt's processes.
46
+ */
47
+ retainUntilStopped(stillGone: (() => Promise<boolean>) | null, reason: Error): void;
35
48
  }
36
49
  /** The gate heavy steps call before launching. */
37
50
  export interface HostLoadStepGate {
38
51
  readonly enabled: boolean;
52
+ /** The longest a step may queue before host_capacity_timeout, when the gate knows it. */
53
+ readonly maxWaitMs?: number;
39
54
  acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
40
55
  }
41
56
  export declare class HostCapacityTimeoutError extends ForgeFailureError {
@@ -53,6 +68,10 @@ export interface HostLoadGovernorOptions {
53
68
  /** Owner recorded on tokens (tests model separate processes); defaults to this process. */
54
69
  readonly owner?: HostLoadTokenOwner;
55
70
  readonly now?: () => number;
71
+ /** Test seam for the ledger's process-tree reaper. */
72
+ readonly terminateStep?: HostLoadStepTerminator;
73
+ /** Test seam for the host suspend counter. */
74
+ readonly suspendedMs?: () => number;
56
75
  }
57
76
  /**
58
77
  * Host-wide admission for heavy steps (decision 0013). Waiters queue
@@ -75,11 +94,26 @@ export declare class HostLoadGovernor implements HostLoadStepGate {
75
94
  /** Own cgroup anonymous memory with no heavy step running: the bridge's baseline. */
76
95
  private idleOwnMemoryBytes;
77
96
  constructor(options: HostLoadGovernorOptions);
97
+ get maxWaitMs(): number;
78
98
  acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
79
99
  /** Reclaims tokens whose owner is gone or whose lease expired (bridge startup). */
80
100
  reclaim(): Promise<readonly HostLoadToken[]>;
81
- /** Attempt teardown: cancels the attempt's waiters and returns every token it holds. */
101
+ /** Returns dead owners' unrecorded tokens the caller proved stopped (see the ledger). */
102
+ releaseOrphaned(belongs: (token: HostLoadToken) => boolean): Promise<readonly HostLoadToken[]>;
103
+ /**
104
+ * Attempt teardown: cancels the attempt's queued steps and stops its running
105
+ * ones (their `fenced` signal aborts with dispatch_cancelled). A running step
106
+ * keeps its token, and its cost, until the step itself returns it once its
107
+ * processes are gone, so the capacity is never reused while it still runs.
108
+ */
109
+ stopAttempt(dispatchAttemptId: string): void;
110
+ /**
111
+ * Cancels the attempt's queued steps and returns every token it holds at
112
+ * once. Only for callers that know the attempt's steps are no longer running;
113
+ * attempt teardown uses stopAttempt.
114
+ */
82
115
  releaseAttempt(dispatchAttemptId: string): Promise<void>;
116
+ private cancelAttemptWaiters;
83
117
  /** Waiting and admitted steps of this process, for diagnostics. */
84
118
  snapshot(): {
85
119
  readonly waiting: number;
@@ -103,21 +137,36 @@ export declare class HostLoadGovernor implements HostLoadStepGate {
103
137
  private runningStepsMemoryBytes;
104
138
  private logicalCpus;
105
139
  private settle;
140
+ /** Renewed tokens reset their lease clock; fenced ones stop their steps (they keep their cost until released). */
141
+ private applyHeldOutcome;
142
+ /** The step must stop: its reservation is no longer guaranteed. */
143
+ private lose;
144
+ /** Ledger failures reach every queued step instead of leaving it to time out. */
145
+ private failWaiters;
146
+ private attachProcess;
106
147
  /**
107
148
  * Returns a step's token. It stays held (and renewed) until the ledger takes
108
149
  * it back, so a ledger outage cannot leave it to lapse into a fenced
109
- * reservation; the renewal timer retries the release.
150
+ * reservation; the renewal timer retries the release. A fenced token is
151
+ * removed too (its step is over) and the release reports the fence.
110
152
  */
111
153
  private releaseHeld;
112
154
  private forget;
113
- /** The step must stop: its reservation is no longer guaranteed. */
114
- private lose;
115
- private onHeldTokens;
116
- /** Ledger failures reach every queued step instead of leaving it to time out. */
117
- private failWaiters;
118
155
  private armRecheck;
119
156
  private disarmRecheck;
120
157
  private armRenewal;
121
158
  private disarmRenewal;
159
+ /**
160
+ * The step ended but part of its process tree may still run: its token stays
161
+ * held and renewed, with its cost, and the step's own termination check is
162
+ * retried on every renewal tick until it proves the tree gone.
163
+ */
164
+ private retainUntilStopped;
165
+ /**
166
+ * Attempt teardown stopped the attempt's processes (its process supervisor
167
+ * proved them gone): tokens kept for a tree nothing else can check are returned.
168
+ */
169
+ releaseRetainedAfterTeardown(dispatchAttemptId: string): Promise<void>;
170
+ private checkRetained;
122
171
  private renewHeld;
123
172
  }
@@ -4,6 +4,7 @@ import { monotonicNowMs } from "../shared/time/monotonic.js";
4
4
  import { decideHostLoadAdmission, } from "./host-load-admission.js";
5
5
  import { loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
6
6
  import { HostCapacityLedgerUnavailableError } from "./host-load-ledger-lock.js";
7
+ import { terminateHostLoadStepProcess } from "./host-load-step-reaper.js";
7
8
  import { HostCapacityTokenFencedError, HostLoadTokenLedger, } from "./host-load-token-ledger.js";
8
9
  export class HostCapacityTimeoutError extends ForgeFailureError {
9
10
  stepClass;
@@ -48,11 +49,15 @@ export class HostLoadGovernor {
48
49
  now: options.now,
49
50
  liveness: options.liveness,
50
51
  owner: options.owner,
51
- // Every ledger transaction renews (or restores) the steps this governor is running.
52
+ terminateStep: options.terminateStep,
53
+ suspendedMs: options.suspendedMs,
54
+ // Every ledger transaction renews the steps this governor is running.
52
55
  heldTokens: () => [...this.held.values()].map(entry => entry.token),
53
- onHeldTokens: outcome => this.onHeldTokens(outcome),
54
56
  });
55
57
  }
58
+ get maxWaitMs() {
59
+ return this.config.maxWaitMs;
60
+ }
56
61
  async acquire(request, options = {}) {
57
62
  if (!this.enabled)
58
63
  throw new Error("host_load_governor_disabled: acquire() requires FORGE_HOST_LOAD_GOVERNOR=on.");
@@ -96,22 +101,55 @@ export class HostLoadGovernor {
96
101
  async reclaim() {
97
102
  if (!this.enabled)
98
103
  return [];
99
- const reclaimed = await this.ledger.reclaim();
100
- if (reclaimed.length > 0)
104
+ const outcome = await this.ledger.transaction(() => undefined);
105
+ this.applyHeldOutcome(outcome);
106
+ if (outcome.reclaimed.length > 0)
107
+ void this.drain();
108
+ return outcome.reclaimed;
109
+ }
110
+ /** Returns dead owners' unrecorded tokens the caller proved stopped (see the ledger). */
111
+ async releaseOrphaned(belongs) {
112
+ if (!this.enabled)
113
+ return [];
114
+ const released = await this.ledger.releaseOrphaned(belongs);
115
+ if (released.length > 0)
101
116
  void this.drain();
102
- return reclaimed;
117
+ return released;
103
118
  }
104
- /** Attempt teardown: cancels the attempt's waiters and returns every token it holds. */
119
+ /**
120
+ * Attempt teardown: cancels the attempt's queued steps and stops its running
121
+ * ones (their `fenced` signal aborts with dispatch_cancelled). A running step
122
+ * keeps its token, and its cost, until the step itself returns it once its
123
+ * processes are gone, so the capacity is never reused while it still runs.
124
+ */
125
+ stopAttempt(dispatchAttemptId) {
126
+ if (!this.enabled)
127
+ return;
128
+ this.cancelAttemptWaiters(dispatchAttemptId);
129
+ for (const entry of this.held.values()) {
130
+ if (entry.token.dispatchAttemptId !== dispatchAttemptId)
131
+ continue;
132
+ 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"));
133
+ }
134
+ }
135
+ /**
136
+ * Cancels the attempt's queued steps and returns every token it holds at
137
+ * once. Only for callers that know the attempt's steps are no longer running;
138
+ * attempt teardown uses stopAttempt.
139
+ */
105
140
  async releaseAttempt(dispatchAttemptId) {
106
141
  if (!this.enabled)
107
142
  return;
143
+ this.cancelAttemptWaiters(dispatchAttemptId);
144
+ const owned = [...this.held.values()].filter(entry => entry.token.dispatchAttemptId === dispatchAttemptId);
145
+ await Promise.allSettled(owned.map(entry => this.releaseHeld(entry)));
146
+ }
147
+ cancelAttemptWaiters(dispatchAttemptId) {
108
148
  for (const waiter of [...this.waiters]) {
109
149
  if (waiter.request.dispatchAttemptId !== dispatchAttemptId)
110
150
  continue;
111
151
  this.settle(waiter, () => waiter.reject(new ForgeFailureError("dispatch_cancelled", "dispatch_cancelled: the attempt was torn down while its step waited for host capacity.", "bridge")));
112
152
  }
113
- const owned = [...this.held.values()].filter(entry => entry.token.dispatchAttemptId === dispatchAttemptId);
114
- await Promise.allSettled(owned.map(entry => this.releaseHeld(entry)));
115
153
  }
116
154
  /** Waiting and admitted steps of this process, for diagnostics. */
117
155
  snapshot() {
@@ -139,7 +177,7 @@ export class HostLoadGovernor {
139
177
  const logicalCpus = this.logicalCpus();
140
178
  const nowMs = monotonicNowMs();
141
179
  const outcomes = [];
142
- await this.ledger.transaction(transaction => {
180
+ const outcome = await this.ledger.transaction(transaction => {
143
181
  const runningMemoryBytes = this.runningStepsMemoryBytes(transaction.tokens);
144
182
  const head = this.waiters[0];
145
183
  const headStarving = head !== undefined && nowMs - head.enqueuedAtMs >= this.config.antiStarvationMs;
@@ -168,6 +206,7 @@ export class HostLoadGovernor {
168
206
  break;
169
207
  }
170
208
  });
209
+ this.applyHeldOutcome(outcome);
171
210
  for (const { waiter, token, decision } of outcomes) {
172
211
  if (!token) {
173
212
  const first = waiter.lastDecision === null;
@@ -178,11 +217,14 @@ export class HostLoadGovernor {
178
217
  }
179
218
  const entry = {
180
219
  token,
181
- lost: new AbortController(),
220
+ fencedController: new AbortController(),
221
+ fencedError: null,
182
222
  renewedAtMs: monotonicNowMs(),
183
223
  releasing: false,
184
224
  releaseInFlight: null,
185
225
  gone: false,
226
+ retainedUntil: null,
227
+ retainCheck: null,
186
228
  };
187
229
  this.held.set(token.tokenId, entry);
188
230
  this.armRenewal();
@@ -198,8 +240,10 @@ export class HostLoadGovernor {
198
240
  stepClass: token.stepClass,
199
241
  waitMs,
200
242
  decision,
201
- signal: entry.lost.signal,
243
+ fenced: entry.fencedController.signal,
244
+ attachProcess: stepProcess => this.attachProcess(entry, stepProcess),
202
245
  release: () => this.releaseHeld(entry),
246
+ retainUntilStopped: (stillGone, reason) => this.retainUntilStopped(entry, stillGone, reason),
203
247
  }));
204
248
  }
205
249
  }
@@ -290,10 +334,53 @@ export class HostLoadGovernor {
290
334
  this.disarmRecheck();
291
335
  complete();
292
336
  }
337
+ /** Renewed tokens reset their lease clock; fenced ones stop their steps (they keep their cost until released). */
338
+ applyHeldOutcome(outcome) {
339
+ const nowMs = monotonicNowMs();
340
+ for (const token of outcome.renewed) {
341
+ const entry = this.held.get(token.tokenId);
342
+ if (entry?.token.fencingToken === token.fencingToken)
343
+ entry.renewedAtMs = nowMs;
344
+ }
345
+ for (const token of outcome.fenced) {
346
+ const entry = this.held.get(token.tokenId);
347
+ if (!entry || entry.token.fencingToken !== token.fencingToken)
348
+ continue;
349
+ entry.fencedError ??= new HostCapacityTokenFencedError(token.tokenId, "renew");
350
+ this.lose(entry, entry.fencedError);
351
+ }
352
+ }
353
+ /** The step must stop: its reservation is no longer guaranteed. */
354
+ lose(entry, reason) {
355
+ if (entry.gone || entry.releasing || entry.fencedController.signal.aborted)
356
+ return;
357
+ entry.fencedController.abort(reason);
358
+ }
359
+ /** Ledger failures reach every queued step instead of leaving it to time out. */
360
+ failWaiters(error) {
361
+ const failure = error instanceof HostCapacityLedgerUnavailableError
362
+ ? error
363
+ : new HostCapacityLedgerUnavailableError(`the admission decision failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
364
+ for (const waiter of [...this.waiters])
365
+ this.settle(waiter, () => waiter.reject(failure));
366
+ }
367
+ async attachProcess(entry, stepProcess) {
368
+ if (entry.fencedError)
369
+ throw entry.fencedError;
370
+ if (entry.gone || entry.releasing)
371
+ return;
372
+ const outcome = await this.ledger.transaction(transaction => transaction.attach(entry.token.tokenId, entry.token.fencingToken, stepProcess));
373
+ this.applyHeldOutcome(outcome);
374
+ if (outcome.result)
375
+ entry.token = outcome.result;
376
+ else
377
+ throw entry.fencedError ?? new HostCapacityTokenFencedError(entry.token.tokenId, "renew");
378
+ }
293
379
  /**
294
380
  * Returns a step's token. It stays held (and renewed) until the ledger takes
295
381
  * it back, so a ledger outage cannot leave it to lapse into a fenced
296
- * reservation; the renewal timer retries the release.
382
+ * reservation; the renewal timer retries the release. A fenced token is
383
+ * removed too (its step is over) and the release reports the fence.
297
384
  */
298
385
  async releaseHeld(entry) {
299
386
  if (entry.gone)
@@ -322,33 +409,6 @@ export class HostLoadGovernor {
322
409
  if (this.held.size === 0)
323
410
  this.disarmRenewal();
324
411
  }
325
- /** The step must stop: its reservation is no longer guaranteed. */
326
- lose(entry, reason) {
327
- if (entry.gone || entry.releasing || entry.lost.signal.aborted)
328
- return;
329
- entry.lost.abort(reason);
330
- }
331
- onHeldTokens(outcome) {
332
- const nowMs = monotonicNowMs();
333
- for (const token of outcome.renewed) {
334
- const entry = this.held.get(token.tokenId);
335
- if (entry?.token.fencingToken === token.fencingToken)
336
- entry.renewedAtMs = nowMs;
337
- }
338
- for (const token of outcome.fenced) {
339
- const entry = this.held.get(token.tokenId);
340
- if (entry?.token.fencingToken === token.fencingToken)
341
- this.lose(entry, new HostCapacityTokenFencedError(token.tokenId, "renew"));
342
- }
343
- }
344
- /** Ledger failures reach every queued step instead of leaving it to time out. */
345
- failWaiters(error) {
346
- const failure = error instanceof HostCapacityLedgerUnavailableError
347
- ? error
348
- : new HostCapacityLedgerUnavailableError(`the admission decision failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
349
- for (const waiter of [...this.waiters])
350
- this.settle(waiter, () => waiter.reject(failure));
351
- }
352
412
  armRecheck() {
353
413
  if (this.recheckTimer)
354
414
  return;
@@ -373,6 +433,49 @@ export class HostLoadGovernor {
373
433
  clearInterval(this.renewTimer);
374
434
  this.renewTimer = null;
375
435
  }
436
+ /**
437
+ * The step ended but part of its process tree may still run: its token stays
438
+ * held and renewed, with its cost, and the step's own termination check is
439
+ * retried on every renewal tick until it proves the tree gone.
440
+ */
441
+ retainUntilStopped(entry, stillGone, reason) {
442
+ if (entry.gone || entry.releasing)
443
+ return;
444
+ this.lose(entry, reason);
445
+ const terminate = this.options.terminateStep ?? terminateHostLoadStepProcess;
446
+ entry.retainedUntil = stillGone
447
+ // The tree recorded on the token (supervised builds, installs) is stopped and checked.
448
+ ?? (entry.token.stepProcess ? async () => await terminate(entry.token.stepProcess) : "attempt_teardown");
449
+ this.armRenewal();
450
+ }
451
+ /**
452
+ * Attempt teardown stopped the attempt's processes (its process supervisor
453
+ * proved them gone): tokens kept for a tree nothing else can check are returned.
454
+ */
455
+ async releaseRetainedAfterTeardown(dispatchAttemptId) {
456
+ if (!this.enabled)
457
+ return;
458
+ const settled = [...this.held.values()].filter(entry => entry.token.dispatchAttemptId === dispatchAttemptId && entry.retainedUntil === "attempt_teardown");
459
+ for (const entry of settled)
460
+ entry.retainedUntil = null;
461
+ await Promise.allSettled(settled.map(entry => this.releaseHeld(entry)));
462
+ }
463
+ checkRetained(entry) {
464
+ if (!entry.retainedUntil || entry.retainedUntil === "attempt_teardown" || entry.retainCheck)
465
+ return;
466
+ const stillGone = entry.retainedUntil;
467
+ entry.retainCheck = (async () => {
468
+ try {
469
+ if (await stillGone().catch(() => false)) {
470
+ entry.retainedUntil = null;
471
+ await this.releaseHeld(entry).catch(() => undefined);
472
+ }
473
+ }
474
+ finally {
475
+ entry.retainCheck = null;
476
+ }
477
+ })();
478
+ }
376
479
  async renewHeld() {
377
480
  if (this.held.size === 0)
378
481
  return;
@@ -380,11 +483,12 @@ export class HostLoadGovernor {
380
483
  // A release the ledger could not take is retried until it lands.
381
484
  if (entry.releasing && !entry.releaseInFlight)
382
485
  void this.releaseHeld(entry).catch(() => undefined);
486
+ this.checkRetained(entry);
383
487
  }
384
488
  try {
385
489
  // The ledger renews every held token at the start of each transaction and
386
- // reports the fenced ones through onHeldTokens.
387
- await this.ledger.transaction(() => undefined);
490
+ // reports the fenced ones.
491
+ this.applyHeldOutcome(await this.ledger.transaction(() => undefined));
388
492
  }
389
493
  catch (error) {
390
494
  // A brief outage is retried on the next tick. Once a whole lease passes
@@ -1,5 +1,6 @@
1
1
  import { type HostEnvironment, type HostFacts } from "./host-facts.js";
2
2
  import { type PressureStallResource } from "./host-pressure-stall.js";
3
+ import { type ForgeCgroupSource } from "./host-load-forge-cgroups.js";
3
4
  export interface HostSystemPressure {
4
5
  readonly cpu: PressureStallResource | null;
5
6
  readonly memory: PressureStallResource | null;
@@ -73,6 +74,8 @@ export interface HostLoadSamplerOptions {
73
74
  readonly monotonicNow?: () => number;
74
75
  /** Systemd unit the operator dedicates to the bridge (FORGE_BRIDGE_CGROUP_UNIT). */
75
76
  readonly cgroupUnit?: string | null;
77
+ /** Docker sandbox cgroups whose CPU time is Forge's own, not external load. */
78
+ readonly forgeCgroups?: ForgeCgroupSource;
76
79
  }
77
80
  export declare const defaultHostLoadSampleIntervalMs = 5000;
78
81
  /**
@@ -97,6 +100,8 @@ export declare class HostLoadSampler implements HostLoadSource {
97
100
  private hostCpuMark;
98
101
  private latestCpuAttribution;
99
102
  private latestMemoryHeadroom;
103
+ private readonly forgeCgroups;
104
+ private readonly sandboxCpu;
100
105
  constructor(options?: HostLoadSamplerOptions);
101
106
  facts(): HostFacts | null;
102
107
  current(): HostLoadSnapshot | null;
@@ -1,7 +1,7 @@
1
1
  import path from "node:path";
2
2
  import { defaultHostEnvironment, detectHostFacts, readOptional, } from "./host-facts.js";
3
3
  import { cgroupLeafName, isDedicatedBridgeUnit, parseCgroupCpuUsageUsec, parseCgroupMemoryAnonBytes, parseMemAvailableBytes, parseNonNegativeInteger, parsePressureStall, parseProcStatCpuTotals, parseUnifiedCgroupMembership, parseUnifiedCgroupPath, } from "./host-pressure-stall.js";
4
- import { readCgroupMemoryHeadroomBytes } from "./host-load-forge-cgroups.js";
4
+ import { ForgeCgroupCpuMeter, readCgroupMemoryHeadroomBytes, } from "./host-load-forge-cgroups.js";
5
5
  export const defaultHostLoadSampleIntervalMs = 5_000;
6
6
  /** Samples kept for the governor's pressure streak (FORGE_HOST_LOAD_BACKPRESSURE_SAMPLES is at most 60). */
7
7
  const retainedSampleCount = 64;
@@ -27,6 +27,8 @@ export class HostLoadSampler {
27
27
  hostCpuMark = null;
28
28
  latestCpuAttribution = null;
29
29
  latestMemoryHeadroom = null;
30
+ forgeCgroups;
31
+ sandboxCpu;
30
32
  constructor(options = {}) {
31
33
  this.environment = options.environment ?? defaultHostEnvironment();
32
34
  this.intervalMs = options.intervalMs !== undefined && Number.isFinite(options.intervalMs) && options.intervalMs > 0
@@ -37,6 +39,8 @@ export class HostLoadSampler {
37
39
  this.cgroupUnit = options.cgroupUnit !== undefined
38
40
  ? options.cgroupUnit
39
41
  : process.env.FORGE_BRIDGE_CGROUP_UNIT?.trim() || null;
42
+ this.forgeCgroups = options.forgeCgroups ?? null;
43
+ this.sandboxCpu = new ForgeCgroupCpuMeter(this.environment);
40
44
  }
41
45
  facts() {
42
46
  return this.hostFacts;
@@ -101,18 +105,22 @@ export class HostLoadSampler {
101
105
  const sampledAtMs = this.now();
102
106
  const monotonicMs = this.monotonicNow();
103
107
  const linux = this.environment.platform === "linux";
104
- const [systemPressure, ownCgroup, memoryAvailableBytes, hostCoresInUse, cgroupMemoryHeadroomBytes] = linux
108
+ const [systemPressure, ownCgroup, memoryAvailableBytes, hostCoresInUse, cgroupMemoryHeadroomBytes, sandboxCores] = linux
105
109
  ? await Promise.all([
106
110
  this.readSystemPressure(),
107
111
  this.readOwnCgroup(monotonicMs),
108
112
  this.readMemoryAvailable(),
109
113
  this.readHostCoresInUse(),
110
114
  this.readCgroupMemoryHeadroom(),
115
+ Promise.resolve(this.forgeCgroups?.paths() ?? [])
116
+ .then(paths => this.sandboxCpu.coresInUse(paths, monotonicMs)).catch(() => 0),
111
117
  ])
112
- : [null, null, this.fallbackFreeMemory(), null, null];
118
+ : [null, null, this.fallbackFreeMemory(), null, null, 0];
113
119
  const sampledAt = new Date(sampledAtMs).toISOString();
120
+ // Docker sandbox CPU is Forge's own work, already counted through reserved cost.
121
+ const ownCores = ownCgroup?.cpuCoresInUse ?? null;
114
122
  this.latestMemoryHeadroom = cgroupMemoryHeadroomBytes;
115
- this.latestCpuAttribution = hostCpuAttribution(sampledAt, hostCoresInUse, ownCgroup?.cpuCoresInUse ?? null);
123
+ this.latestCpuAttribution = hostCpuAttribution(sampledAt, hostCoresInUse, ownCores === null ? null : ownCores + sandboxCores);
116
124
  return {
117
125
  sampledAt,
118
126
  psiAvailable: systemPressure !== null,
@@ -25,9 +25,44 @@ export declare const defaultHostLoadStepCosts: {
25
25
  readonly cpuCores: 1;
26
26
  readonly memoryBytes: number;
27
27
  };
28
+ /** A `dotnet build` (or test with its build) started as a managed command. */
29
+ readonly managedBuild: {
30
+ readonly cpuCores: 2;
31
+ readonly memoryBytes: number;
32
+ };
33
+ readonly aspnetPrebuild: {
34
+ readonly cpuCores: 2;
35
+ readonly memoryBytes: number;
36
+ };
37
+ /** Dependency installs are mostly network and disk bound, so they cost less than a build. */
38
+ readonly dependencyInstall: {
39
+ readonly cpuCores: 0.5;
40
+ readonly memoryBytes: number;
41
+ };
28
42
  };
43
+ export declare const aspNetPrebuildStepClass: HostLoadStepClassification;
44
+ export declare const dependencyInstallStepClass: HostLoadStepClassification;
29
45
  /**
30
46
  * Maps a pre-publication validation step to its class: `dotnet.tier.<tier>`,
31
47
  * `vitest.<suite>`, `playwright.e2e`, or `generic` for everything else.
32
48
  */
33
49
  export declare function classifyValidationStep(checkId: string, command: string, args: readonly string[]): HostLoadStepClassification;
50
+ export interface ManagedCommandStepInput {
51
+ readonly command: string;
52
+ readonly args: readonly string[];
53
+ /** The runner-authored verification profile, when the command is one. */
54
+ readonly verificationProfile?: string;
55
+ /** Whether the command builds (see isBuildProducingManagedCommand). */
56
+ readonly buildProducing: boolean;
57
+ }
58
+ /**
59
+ * Maps a managed command to its class: `managed.<profile>` for verification
60
+ * profiles (a .NET tier's cost per parallel shard), `managed.playwright`,
61
+ * `managed.build` for build-producing commands, and `managed.command` otherwise.
62
+ */
63
+ export declare function classifyManagedCommand(input: ManagedCommandStepInput): HostLoadStepClassification;
64
+ /**
65
+ * The default cost of a step class, for a step whose cost the requester does
66
+ * not get to choose (a Docker sandbox asking the host bridge for admission).
67
+ */
68
+ export declare function hostLoadStepCostForClass(stepClass: string): HostLoadStepCost;
@@ -6,6 +6,19 @@ export const defaultHostLoadStepCosts = {
6
6
  vitest: { cpuCores: 1, memoryBytes: 1.5 * gib },
7
7
  playwright: { cpuCores: 2, memoryBytes: 2 * gib },
8
8
  generic: { cpuCores: 1, memoryBytes: 1 * gib },
9
+ /** A `dotnet build` (or test with its build) started as a managed command. */
10
+ managedBuild: { cpuCores: 2, memoryBytes: 2 * gib },
11
+ aspnetPrebuild: { cpuCores: 2, memoryBytes: 2 * gib },
12
+ /** Dependency installs are mostly network and disk bound, so they cost less than a build. */
13
+ dependencyInstall: { cpuCores: 0.5, memoryBytes: 0.75 * gib },
14
+ };
15
+ export const aspNetPrebuildStepClass = {
16
+ stepClass: "aspnet.prebuild",
17
+ cost: defaultHostLoadStepCosts.aspnetPrebuild,
18
+ };
19
+ export const dependencyInstallStepClass = {
20
+ stepClass: "deps.install",
21
+ cost: defaultHostLoadStepCosts.dependencyInstall,
9
22
  };
10
23
  const dotnetTierScripts = ["scripts/run-dotnet-test-tier.ps1", "scripts/run-dotnet-test-tier-set.ps1"];
11
24
  const affectedDotnetScript = "scripts/run-affected-dotnet-tests.mjs";
@@ -44,3 +57,50 @@ function stepClassSegment(value) {
44
57
  const segment = value.trim().toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "");
45
58
  return segment || "unknown";
46
59
  }
60
+ /**
61
+ * Maps a managed command to its class: `managed.<profile>` for verification
62
+ * profiles (a .NET tier's cost per parallel shard), `managed.playwright`,
63
+ * `managed.build` for build-producing commands, and `managed.command` otherwise.
64
+ */
65
+ export function classifyManagedCommand(input) {
66
+ if (input.verificationProfile) {
67
+ const parallelism = maxParallelismArgument(input.args);
68
+ const tier = defaultHostLoadStepCosts.dotnetTier;
69
+ return {
70
+ stepClass: `managed.${stepClassSegment(input.verificationProfile)}`,
71
+ cost: {
72
+ cpuCores: tier.cpuCores * parallelism,
73
+ memoryBytes: tier.memoryBytes + (parallelism - 1) * 1.5 * gib,
74
+ },
75
+ };
76
+ }
77
+ const invocation = [input.command, ...input.args].map(argument => argument.toLowerCase());
78
+ if (invocation.some(argument => argument.includes("playwright"))) {
79
+ return { stepClass: "managed.playwright", cost: defaultHostLoadStepCosts.playwright };
80
+ }
81
+ if (input.buildProducing)
82
+ return { stepClass: "managed.build", cost: defaultHostLoadStepCosts.managedBuild };
83
+ return { stepClass: "managed.command", cost: defaultHostLoadStepCosts.generic };
84
+ }
85
+ /**
86
+ * The default cost of a step class, for a step whose cost the requester does
87
+ * not get to choose (a Docker sandbox asking the host bridge for admission).
88
+ */
89
+ export function hostLoadStepCostForClass(stepClass) {
90
+ if (stepClass.startsWith("dotnet.tier."))
91
+ return defaultHostLoadStepCosts.dotnetTier;
92
+ if (stepClass.startsWith("vitest."))
93
+ return defaultHostLoadStepCosts.vitest;
94
+ if (stepClass === "playwright.e2e")
95
+ return defaultHostLoadStepCosts.playwright;
96
+ if (stepClass === aspNetPrebuildStepClass.stepClass)
97
+ return defaultHostLoadStepCosts.aspnetPrebuild;
98
+ if (stepClass === dependencyInstallStepClass.stepClass)
99
+ return defaultHostLoadStepCosts.dependencyInstall;
100
+ return defaultHostLoadStepCosts.generic;
101
+ }
102
+ function maxParallelismArgument(args) {
103
+ const index = args.findIndex(argument => argument.toLowerCase() === "-maxparallelism");
104
+ const value = index >= 0 ? Number(args[index + 1]) : 1;
105
+ return Number.isSafeInteger(value) && value >= 1 ? Math.min(value, 32) : 1;
106
+ }
@@ -0,0 +1,27 @@
1
+ import { type WindowsProcessTable } from "../shared/process/process-tree.js";
2
+ /** The process tree a governed step runs in, recorded on its token once it launches. */
3
+ export interface HostLoadStepProcess {
4
+ readonly rootPid: number;
5
+ /** OS birth marker of the root, so a reused pid is never signalled. Null where unsupported. */
6
+ readonly rootIdentity: string | null;
7
+ /** The root leads its own process group (Unix): the whole group is stopped and checked. */
8
+ readonly processGroup: boolean;
9
+ }
10
+ /** Stops a step's process tree; resolves true only when no member is left. */
11
+ export type HostLoadStepTerminator = (step: HostLoadStepProcess) => Promise<boolean>;
12
+ /**
13
+ * Stops the recorded tree with SIGTERM, then SIGKILL, and confirms it is gone.
14
+ * A root that cannot be identified (no birth marker) is never signalled and
15
+ * counts as not confirmed, so its token keeps its reserved cost.
16
+ */
17
+ export declare const terminateHostLoadStepProcess: HostLoadStepTerminator;
18
+ /**
19
+ * Windows has no process groups and does not reparent orphans. A root with a
20
+ * recorded birth marker is stopped together with every descendant created
21
+ * after it (found through parent ids, even if the root already exited), and
22
+ * the reservation is reused only once none is left. Without a birth marker the
23
+ * root cannot be told from a reused pid, so it is never signalled and only its
24
+ * absence counts.
25
+ */
26
+ export declare function windowsStepTerminator(table: WindowsProcessTable, waitMs?: number): HostLoadStepTerminator;
27
+ export declare function validHostLoadStepProcess(value: unknown): value is HostLoadStepProcess;