@loucompanion/forge-bridge 0.1.4-dev.fb770705136a → 0.2.1-dev.0f8fb73715e8
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 +183 -4
- package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
- package/dist/bridge/bridge-chat-giphy-look.js +55 -0
- package/dist/bridge/bridge-chat-provider-command.d.ts +40 -0
- package/dist/bridge/bridge-chat-provider-command.js +230 -0
- package/dist/bridge/bridge-chat.types.d.ts +20 -0
- package/dist/bridge/bridge-chat.types.js +28 -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 +15 -0
- package/dist/bridge/bridge-state-io.js +68 -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 +102 -14
- package/dist/bridge/bridge.service.js +499 -471
- package/dist/bridge/bridge.types.d.ts +37 -0
- package/dist/bridge/bridge.types.js +2 -1
- package/dist/bridge/default-session-service.d.ts +13 -0
- package/dist/bridge/default-session-service.js +22 -0
- package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
- package/dist/bridge/dispatch-offer-policy.js +58 -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 +31 -1
- 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/bridge/windows-bash-resolution.d.ts +31 -0
- package/dist/bridge/windows-bash-resolution.js +153 -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 +11 -0
- package/dist/cleanup/forge-owned-paths.js +62 -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 +75 -13
- package/dist/cli/cli.service.d.ts +19 -10
- package/dist/cli/cli.service.js +161 -228
- package/dist/cli/idle-status.d.ts +84 -0
- package/dist/cli/idle-status.js +181 -0
- package/dist/cli/local-config.d.ts +18 -1
- package/dist/cli/local-config.js +67 -5
- package/dist/cli/provider-cli-advertising.d.ts +24 -0
- package/dist/cli/provider-cli-advertising.js +88 -0
- 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 +72 -0
- package/dist/runtime/host-load-admission.js +99 -0
- package/dist/runtime/host-load-capacity.d.ts +198 -0
- package/dist/runtime/host-load-capacity.js +353 -0
- package/dist/runtime/host-load-child-environment.d.ts +40 -0
- package/dist/runtime/host-load-child-environment.js +110 -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 +82 -0
- package/dist/runtime/host-load-governor-config.js +104 -0
- package/dist/runtime/host-load-governor.d.ts +273 -0
- package/dist/runtime/host-load-governor.js +831 -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-live-test-slots.d.ts +61 -0
- package/dist/runtime/host-load-live-test-slots.js +193 -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 +92 -2
- package/dist/runtime/host-load-sampler.js +166 -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 +107 -0
- package/dist/runtime/host-load-step-run.js +158 -0
- package/dist/runtime/host-load-test-slot.d.ts +46 -0
- package/dist/runtime/host-load-test-slot.js +100 -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 +39 -6
- 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 +23 -1
- package/dist/runtime/prepared-runtime-readiness.js +89 -18
- 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 +11 -3
- package/dist/sandbox/runtime.js +53 -20
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/sandbox/sandbox-input.d.ts +22 -0
- package/dist/sandbox/sandbox-input.js +49 -0
- package/dist/sandbox/workspace.service.js +15 -2
- 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 +204 -141
- 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 +7 -0
- package/dist/session/managed-build-receipt.js +11 -3
- package/dist/session/managed-command-environment.d.ts +8 -0
- package/dist/session/managed-command-environment.js +28 -0
- package/dist/session/managed-command-host-load.d.ts +52 -0
- package/dist/session/managed-command-host-load.js +87 -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.artifact-bundle.d.ts +20 -0
- package/dist/session/phase-completion.artifact-bundle.js +167 -0
- package/dist/session/phase-completion.artifacts.d.ts +9 -17
- package/dist/session/phase-completion.artifacts.js +158 -190
- 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 +31 -2
- package/dist/session/phase-completion.helpers.js +18 -65
- package/dist/session/phase-completion.js +19 -32
- package/dist/session/phase-completion.mcp-args.d.ts +9 -0
- package/dist/session/phase-completion.mcp-args.js +195 -0
- package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
- package/dist/session/phase-completion.phase-aliases.js +43 -0
- package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
- package/dist/session/phase-completion.pr-review-schema.js +75 -0
- package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
- package/dist/session/phase-completion.pr-review-validation.js +212 -0
- package/dist/session/phase-completion.pr-review.d.ts +36 -0
- package/dist/session/phase-completion.pr-review.js +294 -0
- package/dist/session/phase-completion.prompts.d.ts +1 -1
- package/dist/session/phase-completion.prompts.js +20 -1
- package/dist/session/phase-completion.runtime.d.ts +13 -12
- package/dist/session/phase-completion.runtime.js +113 -214
- 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 +219 -232
- package/dist/session/phase-completion.validation.d.ts +3 -3
- package/dist/session/phase-completion.validation.js +58 -94
- package/dist/session/pr-review-diff-base.d.ts +18 -0
- package/dist/session/pr-review-diff-base.js +44 -0
- package/dist/session/pr-review-placement.d.ts +50 -0
- package/dist/session/pr-review-placement.js +91 -0
- package/dist/session/pre-publication-change-set.d.ts +62 -0
- package/dist/session/pre-publication-change-set.js +166 -0
- package/dist/session/pre-publication-host-load.d.ts +27 -0
- package/dist/session/pre-publication-host-load.js +112 -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 +32 -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 +39 -22
- package/dist/session/pre-publication-validation.js +241 -207
- 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/dispatch-target-branch.d.ts +7 -0
- package/dist/session/provider-cli/dispatch-target-branch.js +8 -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/pr-review-credential-isolation.d.ts +83 -0
- package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
- package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
- package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
- package/dist/session/provider-cli/pr-review-prompt.d.ts +2 -0
- package/dist/session/provider-cli/pr-review-prompt.js +119 -0
- package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
- package/dist/session/provider-cli/pre-publication-repair.js +281 -0
- package/dist/session/provider-cli/provider-cli.base.d.ts +1 -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.deterministic.d.ts +1 -0
- package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
- package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
- package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
- package/dist/session/provider-cli/provider-cli.pr-review.js +213 -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 +15 -3
- package/dist/session/provider-cli/provider-cli.prompts.js +183 -90
- package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
- package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +15 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +43 -1
- package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
- package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
- package/dist/session/provider-cli/provider-cli.service.d.ts +18 -18
- package/dist/session/provider-cli/provider-cli.service.js +127 -317
- package/dist/session/provider-cli/provider-cli.types.d.ts +35 -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 +279 -0
- package/dist/session/session-host-project.d.ts +22 -0
- package/dist/session/session-host-project.js +98 -0
- package/dist/session/session-redaction.js +31 -181
- package/dist/session/session.base.d.ts +9 -1
- package/dist/session/session.parse-helpers.d.ts +10 -0
- package/dist/session/session.parse-helpers.js +84 -0
- package/dist/session/session.runtime-refresh.d.ts +46 -0
- package/dist/session/session.runtime-refresh.js +116 -0
- package/dist/session/session.service.d.ts +16 -2
- package/dist/session/session.service.js +208 -155
- package/dist/session/session.types.d.ts +8 -0
- package/dist/session/session.types.js +13 -83
- package/dist/session/session.types.pr-review.d.ts +48 -0
- package/dist/session/session.types.pr-review.js +51 -0
- 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.d.ts +2 -0
- package/dist/shared/provider-capabilities.js +23 -7
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/artifact-injector.js +24 -0
- 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 +58 -0
- package/dist/worktree/wip-git.js +182 -0
- package/dist/worktree/wip-refs.d.ts +85 -0
- package/dist/worktree/wip-refs.js +169 -0
- package/dist/worktree/wip-restore.d.ts +51 -0
- package/dist/worktree/wip-restore.js +324 -0
- package/dist/worktree/wip-snapshot.d.ts +53 -0
- package/dist/worktree/wip-snapshot.js +270 -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 +35 -0
- package/dist/worktree/worktree-origin-sync.js +128 -0
- package/dist/worktree/worktree-wip-events.d.ts +20 -0
- package/dist/worktree/worktree-wip-events.js +148 -0
- package/dist/worktree/worktree-wip.d.ts +57 -0
- package/dist/worktree/worktree-wip.js +200 -0
- package/dist/worktree/worktree.base.d.ts +7 -1
- package/dist/worktree/worktree.service.d.ts +58 -5
- package/dist/worktree/worktree.service.js +237 -161
- package/dist/worktree/worktree.types.d.ts +54 -0
- package/package.json +2 -2
- package/runtime/windows-listener-owner.ps1 +12 -1
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { ForgeFailureError } from "../session/session.types.js";
|
|
2
|
+
import type { HostLoadStepCost } from "./host-load-step-class.js";
|
|
3
|
+
import { type HostTestSlotTicket, type HostTestSlotTicketRequest } from "./host-load-test-slot.js";
|
|
4
|
+
import { type HostLoadStepProcess, type HostLoadStepTerminator } from "./host-load-step-reaper.js";
|
|
5
|
+
/**
|
|
6
|
+
* File-backed token ledger for the host load governor (decision 0013). Every
|
|
7
|
+
* process on the host that runs heavy steps shares it through the coordinator
|
|
8
|
+
* state root. Each token names its owner (pid, OS process birth marker and a
|
|
9
|
+
* per-process instance id), carries a fencing token, and holds an `expiresAt`
|
|
10
|
+
* lease the owner renews. A lapsed lease with a live owner fences the token:
|
|
11
|
+
* it keeps its reserved cost (the owner's step may still be running), renewals
|
|
12
|
+
* are refused so the owner stops that step, and the capacity returns when the
|
|
13
|
+
* owner releases it or is gone. A dead owner's token is reclaimed only once its
|
|
14
|
+
* step's recorded process tree is stopped and confirmed gone; until then it
|
|
15
|
+
* stays `degraded` and keeps its reserved cost.
|
|
16
|
+
*/
|
|
17
|
+
export type HostLoadTokenPriority = "foreground" | "background";
|
|
18
|
+
export interface HostLoadTokenOwner {
|
|
19
|
+
readonly pid: number;
|
|
20
|
+
/** OS-issued birth marker (Linux boot id + start ticks); null where unsupported. */
|
|
21
|
+
readonly processIdentity: string | null;
|
|
22
|
+
/** Random per process: a reused pid in a new process never matches it. */
|
|
23
|
+
readonly processInstanceId: string;
|
|
24
|
+
}
|
|
25
|
+
export interface HostLoadToken {
|
|
26
|
+
readonly tokenId: string;
|
|
27
|
+
readonly fencingToken: number;
|
|
28
|
+
readonly stepClass: string;
|
|
29
|
+
readonly label: string;
|
|
30
|
+
readonly cost: HostLoadStepCost;
|
|
31
|
+
readonly dispatchAttemptId: string | null;
|
|
32
|
+
readonly priority: HostLoadTokenPriority;
|
|
33
|
+
readonly owner: HostLoadTokenOwner;
|
|
34
|
+
readonly admittedAt: string;
|
|
35
|
+
readonly expiresAt: string;
|
|
36
|
+
/** The step's process tree, recorded once it launches; the reaper stops it before reuse. */
|
|
37
|
+
readonly stepProcess?: HostLoadStepProcess | null;
|
|
38
|
+
/** The host's suspend counter (hostSuspendedMs) when the lease was last renewed. */
|
|
39
|
+
readonly suspendedMsAtRenewal?: number;
|
|
40
|
+
/** When an expired token's step could not be proven stopped; it keeps its cost meanwhile. */
|
|
41
|
+
readonly degradedAt?: string | null;
|
|
42
|
+
/** Set when the lease lapsed while the owner was still live: cost kept, renewal refused. */
|
|
43
|
+
readonly fencedAt?: string | null;
|
|
44
|
+
/**
|
|
45
|
+
* Set when the step ended but part of its process tree could not be proven
|
|
46
|
+
* stopped: the token is kept until it is (or until attempt teardown), and the
|
|
47
|
+
* attempt's own later steps do not wait for it (decision 0018).
|
|
48
|
+
*/
|
|
49
|
+
readonly retainedAt?: string | null;
|
|
50
|
+
}
|
|
51
|
+
export interface HostLoadTokenRequest {
|
|
52
|
+
readonly stepClass: string;
|
|
53
|
+
readonly label: string;
|
|
54
|
+
readonly cost: HostLoadStepCost;
|
|
55
|
+
readonly dispatchAttemptId: string | null;
|
|
56
|
+
readonly priority: HostLoadTokenPriority;
|
|
57
|
+
}
|
|
58
|
+
/** The live (post-reclaim) token set inside one locked ledger transaction. */
|
|
59
|
+
export interface HostLoadLedgerTransaction {
|
|
60
|
+
readonly tokens: readonly HostLoadToken[];
|
|
61
|
+
/**
|
|
62
|
+
* Set for one lease after a corrupt ledger was quarantined: owners are still
|
|
63
|
+
* restoring the reservations it lost, so no new step may be admitted yet.
|
|
64
|
+
*/
|
|
65
|
+
readonly recoveringUntil: string | null;
|
|
66
|
+
/** Live host test slot tickets of every owner (decision 0018). */
|
|
67
|
+
readonly queue: readonly HostTestSlotTicket[];
|
|
68
|
+
issue(request: HostLoadTokenRequest): HostLoadToken;
|
|
69
|
+
/** Takes an admitted step's ticket out of the queue in the same commit as its token. */
|
|
70
|
+
removeTicket(ticketId: string): void;
|
|
71
|
+
renew(tokenId: string, fencingToken: number): HostLoadToken | null;
|
|
72
|
+
remove(tokenId: string, fencingToken: number): boolean;
|
|
73
|
+
/** Records the step's process tree on its token; null when the token is fenced. */
|
|
74
|
+
attach(tokenId: string, fencingToken: number, stepProcess: HostLoadStepProcess): HostLoadToken | null;
|
|
75
|
+
/** Marks the token kept after its step ended (`retainedAt`), fenced or not; null when it is gone. */
|
|
76
|
+
retain(tokenId: string, fencingToken: number): HostLoadToken | null;
|
|
77
|
+
}
|
|
78
|
+
export interface HostLoadTransactionOutcome<T> {
|
|
79
|
+
readonly result: T;
|
|
80
|
+
readonly reclaimed: readonly HostLoadToken[];
|
|
81
|
+
/**
|
|
82
|
+
* Tokens this owner holds that are fenced (lease lapsed, or lost from the
|
|
83
|
+
* ledger and put back fenced): their steps must stop. They keep their cost
|
|
84
|
+
* until released.
|
|
85
|
+
*/
|
|
86
|
+
readonly fenced: readonly HostLoadToken[];
|
|
87
|
+
/** Tokens this owner holds whose lease this transaction renewed. */
|
|
88
|
+
readonly renewed: readonly HostLoadToken[];
|
|
89
|
+
}
|
|
90
|
+
export interface HostLoadOwnerLiveness {
|
|
91
|
+
isLive(owner: HostLoadTokenOwner): boolean;
|
|
92
|
+
}
|
|
93
|
+
export interface HostLoadTokenLedgerOptions {
|
|
94
|
+
readonly stateRoot: string;
|
|
95
|
+
readonly leaseMs: number;
|
|
96
|
+
readonly now?: () => number;
|
|
97
|
+
readonly liveness?: HostLoadOwnerLiveness;
|
|
98
|
+
/** Owner recorded on tokens this ledger issues; defaults to the current process (resolved lazily). */
|
|
99
|
+
readonly owner?: HostLoadTokenOwner;
|
|
100
|
+
readonly lockTimeoutMs?: number;
|
|
101
|
+
/**
|
|
102
|
+
* Tokens this owner still holds for running steps. Each transaction renews
|
|
103
|
+
* them before it reclaims anything. One missing from the ledger keeps its
|
|
104
|
+
* cost: it is put back (fenced, unless a quarantine is still recovering).
|
|
105
|
+
*/
|
|
106
|
+
readonly heldTokens?: () => readonly HostLoadToken[];
|
|
107
|
+
/**
|
|
108
|
+
* The steps this owner still waits on for the host test slot (decision 0018). Each
|
|
109
|
+
* transaction renews their tickets and drops the owner's other tickets.
|
|
110
|
+
*/
|
|
111
|
+
readonly waitingTickets?: () => readonly HostTestSlotTicketRequest[];
|
|
112
|
+
/** Stops a reclaimed token's step; defaults to the exact process-tree reaper. */
|
|
113
|
+
readonly terminateStep?: HostLoadStepTerminator;
|
|
114
|
+
/** Host suspend counter (test seam); defaults to hostSuspendedMs. */
|
|
115
|
+
readonly suspendedMs?: () => number;
|
|
116
|
+
/** Test seam passed to the ledger lock. */
|
|
117
|
+
readonly beforeStaleLockBreak?: () => Promise<void>;
|
|
118
|
+
}
|
|
119
|
+
export declare class HostCapacityTokenFencedError extends ForgeFailureError {
|
|
120
|
+
readonly tokenId: string;
|
|
121
|
+
readonly code = "host_capacity_token_fenced";
|
|
122
|
+
constructor(tokenId: string, action: "renew" | "release" | "released_fenced");
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* This process as a token owner, computed once. The birth marker is read only
|
|
126
|
+
* on Linux (a cheap /proc read); elsewhere it would mean a synchronous process
|
|
127
|
+
* spawn, so pid reuse there is covered by the lease and the instance id.
|
|
128
|
+
*/
|
|
129
|
+
export declare function currentHostLoadTokenOwner(): HostLoadTokenOwner;
|
|
130
|
+
/** Owner liveness from the OS: dead pid, or a pid reused by a different process, is gone. */
|
|
131
|
+
export declare const processHostLoadOwnerLiveness: HostLoadOwnerLiveness;
|
|
132
|
+
/**
|
|
133
|
+
* Total time the host has been suspended (Linux: boot-time uptime minus the
|
|
134
|
+
* monotonic clock, which stops while suspended). Zero where it is unknown.
|
|
135
|
+
*/
|
|
136
|
+
export declare function hostSuspendedMs(): number;
|
|
137
|
+
export declare class HostLoadTokenLedger {
|
|
138
|
+
private readonly options;
|
|
139
|
+
private readonly root;
|
|
140
|
+
private readonly ledgerPath;
|
|
141
|
+
private readonly now;
|
|
142
|
+
private readonly liveness;
|
|
143
|
+
private resolvedOwner;
|
|
144
|
+
private readonly lock;
|
|
145
|
+
private tail;
|
|
146
|
+
constructor(options: HostLoadTokenLedgerOptions);
|
|
147
|
+
private suspendedMs;
|
|
148
|
+
private get owner();
|
|
149
|
+
/**
|
|
150
|
+
* Runs `action` under the cross-process ledger lock against the live token
|
|
151
|
+
* set. Dead or expired tokens are reclaimed first, so every admission
|
|
152
|
+
* decision sees only real reservations.
|
|
153
|
+
*/
|
|
154
|
+
transaction<T>(action: (transaction: HostLoadLedgerTransaction) => T | Promise<T>): Promise<HostLoadTransactionOutcome<T>>;
|
|
155
|
+
reclaim(): Promise<readonly HostLoadToken[]>;
|
|
156
|
+
list(): Promise<readonly HostLoadToken[]>;
|
|
157
|
+
/** Extends a token's lease. A fenced, reclaimed or superseded token is rejected. */
|
|
158
|
+
renew(tokenId: string, fencingToken: number): Promise<HostLoadToken>;
|
|
159
|
+
/**
|
|
160
|
+
* Returns a token. A reclaimed or superseded token is rejected, never released
|
|
161
|
+
* twice. A fenced token is removed (its owner's step is over) but still
|
|
162
|
+
* reported as fenced.
|
|
163
|
+
*/
|
|
164
|
+
release(tokenId: string, fencingToken: number): Promise<void>;
|
|
165
|
+
private lockedTransaction;
|
|
166
|
+
/** The live token set and host test slot queue one locked transaction reads and changes. */
|
|
167
|
+
private transactionView;
|
|
168
|
+
/**
|
|
169
|
+
* The host test slot queue (decision 0018): other owners' tickets while their owner
|
|
170
|
+
* lives and renews them, and this owner's current waiters, renewed. A ticket this
|
|
171
|
+
* owner no longer waits on (admitted, cancelled, timed out) leaves the queue here.
|
|
172
|
+
*/
|
|
173
|
+
private liveQueue;
|
|
174
|
+
/**
|
|
175
|
+
* Decides every token another owner can no longer vouch for (decision 0013):
|
|
176
|
+
* - owner alive but its lease lapsed (it stalled): the token is fenced, never
|
|
177
|
+
* killed, and keeps its cost; the owner stops its own step when it next
|
|
178
|
+
* touches the ledger and returns the capacity when it releases the token;
|
|
179
|
+
* - owner gone with a recorded process tree: the tree is stopped and confirmed
|
|
180
|
+
* gone first, otherwise the token stays degraded and keeps its cost;
|
|
181
|
+
* - owner gone with no recorded tree: degraded, keeping its cost, until the
|
|
182
|
+
* attempt's teardown or the bridge's restart reap proves the step stopped
|
|
183
|
+
* (releaseOrphaned).
|
|
184
|
+
*/
|
|
185
|
+
private reapExpired;
|
|
186
|
+
/**
|
|
187
|
+
* Returns dead owners' tokens that have no recorded process tree once the
|
|
188
|
+
* caller has proven their steps stopped (attempt teardown after its process
|
|
189
|
+
* trees are stopped, or the restart reap after attempt recovery).
|
|
190
|
+
*/
|
|
191
|
+
releaseOrphaned(belongs: (token: HostLoadToken) => boolean): Promise<readonly HostLoadToken[]>;
|
|
192
|
+
private read;
|
|
193
|
+
/**
|
|
194
|
+
* A corrupt ledger is kept aside for inspection and none of its tokens are
|
|
195
|
+
* trusted. Admissions pause for one lease while live owners, which renew
|
|
196
|
+
* several times per lease, put their running steps' reservations back.
|
|
197
|
+
*/
|
|
198
|
+
private quarantine;
|
|
199
|
+
private write;
|
|
200
|
+
}
|
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import fs from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { ForgeFailureError } from "../session/session.types.js";
|
|
6
|
+
import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
|
|
7
|
+
import { HostCapacityLedgerUnavailableError, HostLoadLedgerLock } from "./host-load-ledger-lock.js";
|
|
8
|
+
import { validHostTestSlotTicket } from "./host-load-test-slot.js";
|
|
9
|
+
import { terminateHostLoadStepProcess, validHostLoadStepProcess, } from "./host-load-step-reaper.js";
|
|
10
|
+
const processInstanceId = randomUUID();
|
|
11
|
+
const maximumLedgerBytes = 1024 * 1024;
|
|
12
|
+
/** A degraded token's tree is retried at most this often, so a stuck process cannot stall every admission. */
|
|
13
|
+
const degradedRetryMs = 30_000;
|
|
14
|
+
export class HostCapacityTokenFencedError extends ForgeFailureError {
|
|
15
|
+
tokenId;
|
|
16
|
+
code = "host_capacity_token_fenced";
|
|
17
|
+
constructor(tokenId, action) {
|
|
18
|
+
super("host_capacity_token_fenced", action === "released_fenced"
|
|
19
|
+
? `host_capacity_token_fenced: host load token ${tokenId} was fenced after its lease lapsed; the step ran past its lease, and its reservation has now been returned.`
|
|
20
|
+
: `host_capacity_token_fenced: host load token ${tokenId} was fenced, reclaimed or superseded; the ${action} was rejected so it cannot affect another step's reservation.`, "bridge");
|
|
21
|
+
this.tokenId = tokenId;
|
|
22
|
+
this.name = "HostCapacityTokenFencedError";
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
let cachedCurrentOwner = null;
|
|
26
|
+
/**
|
|
27
|
+
* This process as a token owner, computed once. The birth marker is read only
|
|
28
|
+
* on Linux (a cheap /proc read); elsewhere it would mean a synchronous process
|
|
29
|
+
* spawn, so pid reuse there is covered by the lease and the instance id.
|
|
30
|
+
*/
|
|
31
|
+
export function currentHostLoadTokenOwner() {
|
|
32
|
+
cachedCurrentOwner ??= {
|
|
33
|
+
pid: process.pid,
|
|
34
|
+
processIdentity: linuxProcessIdentity(process.pid),
|
|
35
|
+
processInstanceId,
|
|
36
|
+
};
|
|
37
|
+
return cachedCurrentOwner;
|
|
38
|
+
}
|
|
39
|
+
/** Owner liveness from the OS: dead pid, or a pid reused by a different process, is gone. */
|
|
40
|
+
export const processHostLoadOwnerLiveness = {
|
|
41
|
+
isLive(owner) {
|
|
42
|
+
if (owner.pid === process.pid)
|
|
43
|
+
return owner.processInstanceId === processInstanceId;
|
|
44
|
+
try {
|
|
45
|
+
process.kill(owner.pid, 0);
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
if (error.code !== "EPERM")
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
if (!owner.processIdentity)
|
|
52
|
+
return true;
|
|
53
|
+
const current = linuxProcessIdentity(owner.pid);
|
|
54
|
+
return current === null || current === owner.processIdentity;
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
function linuxProcessIdentity(pid) {
|
|
58
|
+
return process.platform === "linux" ? captureHostProcessIdentity(pid, "linux") : null;
|
|
59
|
+
}
|
|
60
|
+
/** Lapsed: past its lease even after taking away the time the host was suspended since renewal. */
|
|
61
|
+
function leaseLapsed(token, nowMs, suspendedMs) {
|
|
62
|
+
const expiresAtMs = Date.parse(token.expiresAt);
|
|
63
|
+
if (!Number.isFinite(expiresAtMs))
|
|
64
|
+
return true;
|
|
65
|
+
const asleepMs = Math.max(0, suspendedMs - (token.suspendedMsAtRenewal ?? suspendedMs));
|
|
66
|
+
return expiresAtMs + asleepMs <= nowMs;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Total time the host has been suspended (Linux: boot-time uptime minus the
|
|
70
|
+
* monotonic clock, which stops while suspended). Zero where it is unknown.
|
|
71
|
+
*/
|
|
72
|
+
export function hostSuspendedMs() {
|
|
73
|
+
if (process.platform !== "linux")
|
|
74
|
+
return 0;
|
|
75
|
+
try {
|
|
76
|
+
const uptimeMs = Number(readFileSync("/proc/uptime", "utf8").split(/\s+/u)[0]) * 1000;
|
|
77
|
+
const monotonicMs = Number(process.hrtime.bigint() / 1000000n);
|
|
78
|
+
return Number.isFinite(uptimeMs) ? Math.max(0, Math.round(uptimeMs - monotonicMs)) : 0;
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return 0;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
export class HostLoadTokenLedger {
|
|
85
|
+
options;
|
|
86
|
+
root;
|
|
87
|
+
ledgerPath;
|
|
88
|
+
now;
|
|
89
|
+
liveness;
|
|
90
|
+
resolvedOwner;
|
|
91
|
+
lock;
|
|
92
|
+
tail = Promise.resolve();
|
|
93
|
+
constructor(options) {
|
|
94
|
+
this.options = options;
|
|
95
|
+
this.root = path.join(options.stateRoot, "host-load-governor");
|
|
96
|
+
this.ledgerPath = path.join(this.root, "tokens.v1.json");
|
|
97
|
+
this.now = options.now ?? Date.now;
|
|
98
|
+
this.liveness = options.liveness ?? processHostLoadOwnerLiveness;
|
|
99
|
+
this.resolvedOwner = options.owner ?? null;
|
|
100
|
+
this.lock = new HostLoadLedgerLock({
|
|
101
|
+
lockPath: path.join(this.root, "tokens.lock"),
|
|
102
|
+
holder: () => this.owner,
|
|
103
|
+
isLive: holder => this.liveness.isLive(holder),
|
|
104
|
+
timeoutMs: options.lockTimeoutMs ?? 10_000,
|
|
105
|
+
beforeStaleBreak: options.beforeStaleLockBreak,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
suspendedMs() {
|
|
109
|
+
return (this.options.suspendedMs ?? hostSuspendedMs)();
|
|
110
|
+
}
|
|
111
|
+
get owner() {
|
|
112
|
+
this.resolvedOwner ??= currentHostLoadTokenOwner();
|
|
113
|
+
return this.resolvedOwner;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Runs `action` under the cross-process ledger lock against the live token
|
|
117
|
+
* set. Dead or expired tokens are reclaimed first, so every admission
|
|
118
|
+
* decision sees only real reservations.
|
|
119
|
+
*/
|
|
120
|
+
async transaction(action) {
|
|
121
|
+
const run = this.tail.then(() => this.lockedTransaction(action));
|
|
122
|
+
this.tail = run.catch(() => undefined);
|
|
123
|
+
return await run;
|
|
124
|
+
}
|
|
125
|
+
async reclaim() {
|
|
126
|
+
return (await this.transaction(() => undefined)).reclaimed;
|
|
127
|
+
}
|
|
128
|
+
async list() {
|
|
129
|
+
return (await this.transaction(transaction => transaction.tokens)).result;
|
|
130
|
+
}
|
|
131
|
+
/** Extends a token's lease. A fenced, reclaimed or superseded token is rejected. */
|
|
132
|
+
async renew(tokenId, fencingToken) {
|
|
133
|
+
const renewed = (await this.transaction(transaction => transaction.renew(tokenId, fencingToken))).result;
|
|
134
|
+
if (!renewed)
|
|
135
|
+
throw new HostCapacityTokenFencedError(tokenId, "renew");
|
|
136
|
+
return renewed;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Returns a token. A reclaimed or superseded token is rejected, never released
|
|
140
|
+
* twice. A fenced token is removed (its owner's step is over) but still
|
|
141
|
+
* reported as fenced.
|
|
142
|
+
*/
|
|
143
|
+
async release(tokenId, fencingToken) {
|
|
144
|
+
const outcome = (await this.transaction(transaction => {
|
|
145
|
+
const entry = transaction.tokens.find(token => token.tokenId === tokenId && token.fencingToken === fencingToken);
|
|
146
|
+
if (!entry || !transaction.remove(tokenId, fencingToken))
|
|
147
|
+
return "missing";
|
|
148
|
+
return entry.fencedAt ? "fenced" : "released";
|
|
149
|
+
})).result;
|
|
150
|
+
if (outcome === "missing")
|
|
151
|
+
throw new HostCapacityTokenFencedError(tokenId, "release");
|
|
152
|
+
if (outcome === "fenced")
|
|
153
|
+
throw new HostCapacityTokenFencedError(tokenId, "released_fenced");
|
|
154
|
+
}
|
|
155
|
+
async lockedTransaction(action) {
|
|
156
|
+
await fs.mkdir(this.root, { recursive: true, mode: 0o700 }).catch(error => {
|
|
157
|
+
throw new HostCapacityLedgerUnavailableError("the host load ledger directory could not be created.", { cause: error });
|
|
158
|
+
});
|
|
159
|
+
const lockToken = await this.lock.acquire();
|
|
160
|
+
try {
|
|
161
|
+
const { ledger, quarantined } = await this.read();
|
|
162
|
+
const nowMs = this.now();
|
|
163
|
+
const nowIso = new Date(nowMs).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: new Date(this.now() + this.options.leaseMs).toISOString(), suspendedMsAtRenewal: suspendedMs });
|
|
167
|
+
const recoveringUntil = ledger.recoveringUntil && Date.parse(ledger.recoveringUntil) > nowMs
|
|
168
|
+
? ledger.recoveringUntil
|
|
169
|
+
: null;
|
|
170
|
+
// Running steps of this owner are renewed before anything is reclaimed.
|
|
171
|
+
const key = (token) => `${token.tokenId}:${token.fencingToken}`;
|
|
172
|
+
const held = this.options.heldTokens?.() ?? [];
|
|
173
|
+
const heldIds = new Set(held.map(key));
|
|
174
|
+
const ledgerIds = new Set(ledger.tokens.map(key));
|
|
175
|
+
// A held token missing from the ledger keeps its cost. While a quarantined
|
|
176
|
+
// ledger is recovering no step was admitted against the gap, so it is put
|
|
177
|
+
// back as is; otherwise capacity may have been reused, so it comes back fenced.
|
|
178
|
+
const restored = held
|
|
179
|
+
.filter(token => !ledgerIds.has(key(token)))
|
|
180
|
+
.map(token => ({ ...token, ...lease(), fencedAt: token.fencedAt ?? (recoveringUntil ? null : nowIso) }));
|
|
181
|
+
const current = [
|
|
182
|
+
...ledger.tokens.map(token => heldIds.has(key(token)) && !token.fencedAt ? { ...token, ...lease() } : token),
|
|
183
|
+
...restored,
|
|
184
|
+
];
|
|
185
|
+
const { reclaimed, degraded, fencedNow } = await this.reapExpired(current, nowMs, suspendedMs, nowIso);
|
|
186
|
+
const queue = this.liveQueue(ledger.slotQueue ?? [], nowMs, lease().expiresAt);
|
|
187
|
+
const state = {
|
|
188
|
+
tokens: current
|
|
189
|
+
.filter(token => !reclaimed.includes(token))
|
|
190
|
+
.map(token => degraded.get(token) ?? fencedNow.get(token) ?? token),
|
|
191
|
+
queue: queue.tickets,
|
|
192
|
+
nextFencingToken: Math.max(ledger.nextFencingToken, ...restored.map(token => token.fencingToken + 1)),
|
|
193
|
+
changed: quarantined || reclaimed.length > 0 || degraded.size > 0 || fencedNow.size > 0 || held.length > 0
|
|
194
|
+
|| queue.changed || (ledger.recoveringUntil !== undefined && recoveringUntil === null),
|
|
195
|
+
};
|
|
196
|
+
const result = await action(this.transactionView(state, recoveringUntil, lease));
|
|
197
|
+
if (state.changed) {
|
|
198
|
+
// A lock broken under us (a stalled holder taken for dead) must not commit.
|
|
199
|
+
if (!await this.lock.holds(lockToken)) {
|
|
200
|
+
throw new HostCapacityLedgerUnavailableError("the ledger lock was lost before the update could be written.");
|
|
201
|
+
}
|
|
202
|
+
await this.write({
|
|
203
|
+
schemaVersion: 1,
|
|
204
|
+
nextFencingToken: state.nextFencingToken,
|
|
205
|
+
tokens: state.tokens,
|
|
206
|
+
...state.queue.length > 0 ? { slotQueue: state.queue } : {},
|
|
207
|
+
...recoveringUntil ? { recoveringUntil } : {},
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
const heldNow = state.tokens.filter(token => heldIds.has(key(token)));
|
|
211
|
+
return {
|
|
212
|
+
result,
|
|
213
|
+
reclaimed,
|
|
214
|
+
fenced: heldNow.filter(token => Boolean(token.fencedAt)),
|
|
215
|
+
renewed: heldNow.filter(token => !token.fencedAt),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
finally {
|
|
219
|
+
await this.lock.release(lockToken);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
/** The live token set and host test slot queue one locked transaction reads and changes. */
|
|
223
|
+
transactionView(state, recoveringUntil, lease) {
|
|
224
|
+
const replace = (tokenId, fencingToken, change, evenFenced = false) => {
|
|
225
|
+
const index = state.tokens.findIndex(token => token.tokenId === tokenId && token.fencingToken === fencingToken);
|
|
226
|
+
if (index < 0 || (state.tokens[index].fencedAt && !evenFenced))
|
|
227
|
+
return null;
|
|
228
|
+
const changed = change(state.tokens[index]);
|
|
229
|
+
state.tokens = state.tokens.map((token, position) => position === index ? changed : token);
|
|
230
|
+
state.changed = true;
|
|
231
|
+
return changed;
|
|
232
|
+
};
|
|
233
|
+
return {
|
|
234
|
+
get tokens() { return state.tokens; },
|
|
235
|
+
get queue() { return state.queue; },
|
|
236
|
+
recoveringUntil,
|
|
237
|
+
issue: request => {
|
|
238
|
+
const token = {
|
|
239
|
+
tokenId: randomUUID(),
|
|
240
|
+
fencingToken: state.nextFencingToken,
|
|
241
|
+
stepClass: request.stepClass,
|
|
242
|
+
label: request.label,
|
|
243
|
+
cost: { cpuCores: request.cost.cpuCores, memoryBytes: request.cost.memoryBytes },
|
|
244
|
+
dispatchAttemptId: request.dispatchAttemptId,
|
|
245
|
+
priority: request.priority,
|
|
246
|
+
owner: this.owner,
|
|
247
|
+
admittedAt: new Date(this.now()).toISOString(),
|
|
248
|
+
...lease(),
|
|
249
|
+
};
|
|
250
|
+
state.nextFencingToken += 1;
|
|
251
|
+
state.tokens = [...state.tokens, token];
|
|
252
|
+
state.changed = true;
|
|
253
|
+
return token;
|
|
254
|
+
},
|
|
255
|
+
renew: (tokenId, fencingToken) => replace(tokenId, fencingToken, token => ({ ...token, ...lease() })),
|
|
256
|
+
attach: (tokenId, fencingToken, stepProcess) => replace(tokenId, fencingToken, token => ({ ...token, stepProcess })),
|
|
257
|
+
// A fenced token's step can end unproven too: the marker is metadata, not a renewal.
|
|
258
|
+
retain: (tokenId, fencingToken) => replace(tokenId, fencingToken, token => ({ ...token, retainedAt: new Date(this.now()).toISOString() }), true),
|
|
259
|
+
remove: (tokenId, fencingToken) => {
|
|
260
|
+
const before = state.tokens.length;
|
|
261
|
+
state.tokens = state.tokens.filter(token => !(token.tokenId === tokenId && token.fencingToken === fencingToken));
|
|
262
|
+
state.changed ||= state.tokens.length !== before;
|
|
263
|
+
return state.tokens.length !== before;
|
|
264
|
+
},
|
|
265
|
+
removeTicket: ticketId => {
|
|
266
|
+
const before = state.queue.length;
|
|
267
|
+
state.queue = state.queue.filter(ticket => ticket.ticketId !== ticketId);
|
|
268
|
+
state.changed ||= state.queue.length !== before;
|
|
269
|
+
},
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* The host test slot queue (decision 0018): other owners' tickets while their owner
|
|
274
|
+
* lives and renews them, and this owner's current waiters, renewed. A ticket this
|
|
275
|
+
* owner no longer waits on (admitted, cancelled, timed out) leaves the queue here.
|
|
276
|
+
*/
|
|
277
|
+
liveQueue(stored, nowMs, expiresAt) {
|
|
278
|
+
const owner = this.owner;
|
|
279
|
+
const mine = (ticket) => ticket.owner.pid === owner.pid
|
|
280
|
+
&& ticket.owner.processInstanceId === owner.processInstanceId;
|
|
281
|
+
const others = stored.filter(ticket => !mine(ticket)
|
|
282
|
+
&& Date.parse(ticket.expiresAt) > nowMs
|
|
283
|
+
&& this.liveness.isLive(ticket.owner));
|
|
284
|
+
const waiting = (this.options.waitingTickets?.() ?? []).map(ticket => ({ ...ticket, owner, expiresAt }));
|
|
285
|
+
return {
|
|
286
|
+
tickets: [...others, ...waiting],
|
|
287
|
+
changed: waiting.length > 0 || others.length + waiting.length !== stored.length,
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Decides every token another owner can no longer vouch for (decision 0013):
|
|
292
|
+
* - owner alive but its lease lapsed (it stalled): the token is fenced, never
|
|
293
|
+
* killed, and keeps its cost; the owner stops its own step when it next
|
|
294
|
+
* touches the ledger and returns the capacity when it releases the token;
|
|
295
|
+
* - owner gone with a recorded process tree: the tree is stopped and confirmed
|
|
296
|
+
* gone first, otherwise the token stays degraded and keeps its cost;
|
|
297
|
+
* - owner gone with no recorded tree: degraded, keeping its cost, until the
|
|
298
|
+
* attempt's teardown or the bridge's restart reap proves the step stopped
|
|
299
|
+
* (releaseOrphaned).
|
|
300
|
+
*/
|
|
301
|
+
async reapExpired(current, nowMs, suspendedMs, nowIso) {
|
|
302
|
+
const reclaimed = [];
|
|
303
|
+
const degraded = new Map();
|
|
304
|
+
const fencedNow = new Map();
|
|
305
|
+
const terminate = this.options.terminateStep ?? terminateHostLoadStepProcess;
|
|
306
|
+
for (const token of current) {
|
|
307
|
+
if (this.liveness.isLive(token.owner)) {
|
|
308
|
+
// Its step may still be running: fence it, but never free its capacity.
|
|
309
|
+
if (!token.fencedAt && leaseLapsed(token, nowMs, suspendedMs))
|
|
310
|
+
fencedNow.set(token, { ...token, fencedAt: nowIso });
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
const lastDegraded = token.degradedAt ? Date.parse(token.degradedAt) : Number.NaN;
|
|
314
|
+
if (Number.isFinite(lastDegraded) && nowMs - lastDegraded < degradedRetryMs)
|
|
315
|
+
continue;
|
|
316
|
+
const gone = Boolean(token.stepProcess) && await terminate(token.stepProcess).catch(() => false);
|
|
317
|
+
if (gone)
|
|
318
|
+
reclaimed.push(token);
|
|
319
|
+
else
|
|
320
|
+
degraded.set(token, { ...token, degradedAt: new Date(nowMs).toISOString() });
|
|
321
|
+
}
|
|
322
|
+
return { reclaimed, degraded, fencedNow };
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Returns dead owners' tokens that have no recorded process tree once the
|
|
326
|
+
* caller has proven their steps stopped (attempt teardown after its process
|
|
327
|
+
* trees are stopped, or the restart reap after attempt recovery).
|
|
328
|
+
*/
|
|
329
|
+
async releaseOrphaned(belongs) {
|
|
330
|
+
return (await this.transaction(transaction => {
|
|
331
|
+
const orphaned = transaction.tokens.filter(token => !token.stepProcess && belongs(token) && !this.liveness.isLive(token.owner));
|
|
332
|
+
for (const token of orphaned)
|
|
333
|
+
transaction.remove(token.tokenId, token.fencingToken);
|
|
334
|
+
return orphaned;
|
|
335
|
+
})).result;
|
|
336
|
+
}
|
|
337
|
+
async read() {
|
|
338
|
+
let content;
|
|
339
|
+
try {
|
|
340
|
+
const stat = await fs.lstat(this.ledgerPath);
|
|
341
|
+
if (!stat.isFile() || stat.size > maximumLedgerBytes)
|
|
342
|
+
return await this.quarantine(null);
|
|
343
|
+
content = await fs.readFile(this.ledgerPath, "utf8");
|
|
344
|
+
}
|
|
345
|
+
catch (error) {
|
|
346
|
+
if (error.code === "ENOENT")
|
|
347
|
+
return { ledger: emptyLedger(), quarantined: false };
|
|
348
|
+
// EMFILE, EACCES and the like say nothing about the ledger's content: keep it.
|
|
349
|
+
throw new HostCapacityLedgerUnavailableError("the host load ledger could not be read.", { cause: error });
|
|
350
|
+
}
|
|
351
|
+
let parsed;
|
|
352
|
+
try {
|
|
353
|
+
parsed = JSON.parse(content);
|
|
354
|
+
}
|
|
355
|
+
catch {
|
|
356
|
+
return await this.quarantine(null);
|
|
357
|
+
}
|
|
358
|
+
const nextFencingToken = Number.isSafeInteger(parsed?.nextFencingToken) ? parsed.nextFencingToken : null;
|
|
359
|
+
// One malformed reservation makes the whole ledger untrustworthy: dropping just
|
|
360
|
+
// that token would turn a possibly running step's cost into free capacity.
|
|
361
|
+
if (parsed?.schemaVersion !== 1 || !Array.isArray(parsed.tokens) || nextFencingToken === null
|
|
362
|
+
|| !parsed.tokens.every(validToken)
|
|
363
|
+
|| !uniqueTokenIds(parsed.tokens)
|
|
364
|
+
|| (parsed.recoveringUntil !== undefined && !Number.isFinite(Date.parse(parsed.recoveringUntil)))) {
|
|
365
|
+
return await this.quarantine(nextFencingToken);
|
|
366
|
+
}
|
|
367
|
+
return {
|
|
368
|
+
ledger: {
|
|
369
|
+
schemaVersion: 1,
|
|
370
|
+
nextFencingToken,
|
|
371
|
+
tokens: parsed.tokens,
|
|
372
|
+
slotQueue: Array.isArray(parsed.slotQueue) ? parsed.slotQueue.filter(validHostTestSlotTicket) : [],
|
|
373
|
+
...parsed.recoveringUntil !== undefined ? { recoveringUntil: parsed.recoveringUntil } : {},
|
|
374
|
+
},
|
|
375
|
+
quarantined: false,
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* A corrupt ledger is kept aside for inspection and none of its tokens are
|
|
380
|
+
* trusted. Admissions pause for one lease while live owners, which renew
|
|
381
|
+
* several times per lease, put their running steps' reservations back.
|
|
382
|
+
*/
|
|
383
|
+
async quarantine(nextFencingToken) {
|
|
384
|
+
// A unique name: a second quarantine in the same millisecond must not replace the first copy.
|
|
385
|
+
await fs.rename(this.ledgerPath, `${this.ledgerPath}.corrupt-${this.now()}-${randomUUID()}`).catch(() => undefined);
|
|
386
|
+
return {
|
|
387
|
+
ledger: {
|
|
388
|
+
...emptyLedger(),
|
|
389
|
+
nextFencingToken: Math.max(1, nextFencingToken ?? 1),
|
|
390
|
+
recoveringUntil: new Date(this.now() + this.options.leaseMs).toISOString(),
|
|
391
|
+
},
|
|
392
|
+
quarantined: true,
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
async write(ledger) {
|
|
396
|
+
const temporary = `${this.ledgerPath}.${process.pid}.${randomUUID()}.tmp`;
|
|
397
|
+
try {
|
|
398
|
+
const handle = await fs.open(temporary, "wx", 0o600);
|
|
399
|
+
try {
|
|
400
|
+
await handle.writeFile(`${JSON.stringify(ledger)}\n`);
|
|
401
|
+
await handle.sync();
|
|
402
|
+
}
|
|
403
|
+
finally {
|
|
404
|
+
await handle.close();
|
|
405
|
+
}
|
|
406
|
+
await fs.rename(temporary, this.ledgerPath);
|
|
407
|
+
}
|
|
408
|
+
catch (error) {
|
|
409
|
+
await fs.rm(temporary, { force: true }).catch(() => undefined);
|
|
410
|
+
throw new HostCapacityLedgerUnavailableError("the host load ledger could not be written.", { cause: error });
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
function emptyLedger() {
|
|
415
|
+
return { schemaVersion: 1, nextFencingToken: 1, tokens: [] };
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* Each reservation needs its own identity: with a duplicate tokenId the owner's
|
|
419
|
+
* held map would keep one copy, and one release would drop both reservations.
|
|
420
|
+
*/
|
|
421
|
+
function uniqueTokenIds(tokens) {
|
|
422
|
+
return new Set(tokens.map(token => token.tokenId)).size === tokens.length;
|
|
423
|
+
}
|
|
424
|
+
function validOwner(value) {
|
|
425
|
+
const owner = value;
|
|
426
|
+
return Boolean(owner)
|
|
427
|
+
&& Number.isSafeInteger(owner.pid) && owner.pid > 0
|
|
428
|
+
&& typeof owner.processInstanceId === "string"
|
|
429
|
+
&& (owner.processIdentity === null || typeof owner.processIdentity === "string");
|
|
430
|
+
}
|
|
431
|
+
function validToken(value) {
|
|
432
|
+
const token = value;
|
|
433
|
+
return Boolean(token)
|
|
434
|
+
&& typeof token.tokenId === "string"
|
|
435
|
+
&& Number.isSafeInteger(token.fencingToken)
|
|
436
|
+
&& typeof token.stepClass === "string"
|
|
437
|
+
&& typeof token.label === "string"
|
|
438
|
+
&& Number.isFinite(token.cost?.cpuCores) && token.cost.cpuCores >= 0
|
|
439
|
+
&& Number.isFinite(token.cost?.memoryBytes) && token.cost.memoryBytes >= 0
|
|
440
|
+
&& (token.dispatchAttemptId === null || typeof token.dispatchAttemptId === "string")
|
|
441
|
+
&& (token.priority === "foreground" || token.priority === "background")
|
|
442
|
+
&& validOwner(token.owner)
|
|
443
|
+
&& typeof token.admittedAt === "string"
|
|
444
|
+
&& typeof token.expiresAt === "string"
|
|
445
|
+
&& validOptionalTokenFields(token);
|
|
446
|
+
}
|
|
447
|
+
/** The fields a token gains as its step runs, ends or loses its owner. */
|
|
448
|
+
function validOptionalTokenFields(token) {
|
|
449
|
+
const optionalTime = (time) => time === undefined || time === null || typeof time === "string";
|
|
450
|
+
return (token.stepProcess === undefined || token.stepProcess === null || validHostLoadStepProcess(token.stepProcess))
|
|
451
|
+
&& (token.suspendedMsAtRenewal === undefined || Number.isFinite(token.suspendedMsAtRenewal))
|
|
452
|
+
&& optionalTime(token.degradedAt) && optionalTime(token.fencedAt) && optionalTime(token.retainedAt);
|
|
453
|
+
}
|