@loucompanion/forge-bridge 0.1.3-dev.f66395c3ac21 → 0.1.4-dev.0098fdb4e213
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 +306 -1
- package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
- package/dist/bridge/bridge-chat-provider-command.js +132 -0
- package/dist/bridge/bridge-chat.types.d.ts +121 -0
- package/dist/bridge/bridge-chat.types.js +416 -0
- package/dist/bridge/bridge-state-file.d.ts +161 -0
- package/dist/bridge/bridge-state-file.js +376 -0
- package/dist/bridge/bridge-state-io.d.ts +11 -0
- package/dist/bridge/bridge-state-io.js +50 -0
- package/dist/bridge/bridge-state-lock.d.ts +11 -0
- package/dist/bridge/bridge-state-lock.js +102 -0
- package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
- package/dist/bridge/bridge-state-unpublished.js +111 -0
- package/dist/bridge/bridge.base.d.ts +18 -1
- package/dist/bridge/bridge.service.d.ts +216 -4
- package/dist/bridge/bridge.service.js +2574 -90
- package/dist/bridge/bridge.types.d.ts +245 -2
- package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
- package/dist/bridge/dispatch-result-outbox.js +87 -0
- package/dist/bridge/dispatch-result-worker.d.ts +2 -0
- package/dist/bridge/dispatch-result-worker.js +122 -0
- package/dist/bridge/in-flight-registry.d.ts +62 -0
- package/dist/bridge/in-flight-registry.js +207 -0
- package/dist/bridge/internals.d.ts +2 -0
- package/dist/bridge/internals.js +1 -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 +25 -0
- package/dist/bridge/readiness-result-outbox.js +74 -0
- package/dist/bridge/readiness-result-worker.d.ts +2 -0
- package/dist/bridge/readiness-result-worker.js +121 -0
- package/dist/bridge/runner-host-capabilities.d.ts +20 -0
- package/dist/bridge/runner-host-capabilities.js +110 -0
- package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
- package/dist/bridge/sandbox-resource-accounting.js +150 -0
- package/dist/bridge/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- package/dist/cleanup/cleanup-wip.d.ts +12 -0
- package/dist/cleanup/cleanup-wip.js +66 -0
- package/dist/cleanup/cleanup.service.d.ts +33 -2
- package/dist/cleanup/cleanup.service.js +477 -3
- package/dist/cleanup/cleanup.types.d.ts +16 -0
- package/dist/cleanup/forge-owned-paths.d.ts +9 -0
- package/dist/cleanup/forge-owned-paths.js +53 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
- package/dist/cleanup/host-runtime-ledger.js +130 -0
- package/dist/cleanup/index.d.ts +1 -1
- package/dist/cleanup/index.js +1 -1
- package/dist/cleanup/internals.d.ts +2 -2
- package/dist/cleanup/internals.js +1 -1
- package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
- package/dist/cleanup/managed-branch-sweep.js +111 -0
- package/dist/cli/cli.help.d.ts +2 -0
- package/dist/cli/cli.help.js +279 -0
- package/dist/cli/cli.service.d.ts +69 -12
- package/dist/cli/cli.service.js +557 -382
- package/dist/cli/idle-status.d.ts +84 -0
- package/dist/cli/idle-status.js +181 -0
- package/dist/cli/local-config.d.ts +13 -0
- package/dist/cli/local-config.js +82 -6
- 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 +41 -0
- package/dist/runtime/aspnet-runtime-prebuild.js +474 -0
- package/dist/runtime/attempt-database-broker.d.ts +89 -0
- package/dist/runtime/attempt-database-broker.js +390 -0
- package/dist/runtime/attempt-node-runtime-launcher.d.ts +18 -0
- package/dist/runtime/attempt-node-runtime-launcher.js +140 -0
- package/dist/runtime/attempt-path-operation.d.ts +21 -0
- package/dist/runtime/attempt-path-operation.js +94 -0
- package/dist/runtime/attempt-private-directory.d.ts +6 -0
- package/dist/runtime/attempt-private-directory.js +54 -0
- package/dist/runtime/attempt-process-supervisor-registry.d.ts +20 -0
- package/dist/runtime/attempt-process-supervisor-registry.js +64 -0
- package/dist/runtime/attempt-process-supervisor.d.ts +121 -0
- package/dist/runtime/attempt-process-supervisor.js +471 -0
- package/dist/runtime/canonical-source-file.d.ts +3 -0
- package/dist/runtime/canonical-source-file.js +54 -0
- package/dist/runtime/docker-engine-probe.d.ts +95 -0
- package/dist/runtime/docker-engine-probe.js +340 -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/generated-output-reset.d.ts +20 -0
- package/dist/runtime/generated-output-reset.js +157 -0
- package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
- package/dist/runtime/host-database-capability-boundary.js +63 -0
- package/dist/runtime/host-diagnostics.d.ts +11 -0
- package/dist/runtime/host-diagnostics.js +192 -0
- package/dist/runtime/host-execution-root.d.ts +4 -0
- package/dist/runtime/host-execution-root.js +39 -0
- package/dist/runtime/host-facts.d.ts +36 -0
- package/dist/runtime/host-facts.js +95 -0
- package/dist/runtime/host-listener-inspector.d.ts +51 -0
- package/dist/runtime/host-listener-inspector.js +385 -0
- package/dist/runtime/host-load-admission.d.ts +67 -0
- package/dist/runtime/host-load-admission.js +99 -0
- package/dist/runtime/host-load-child-environment.d.ts +27 -0
- package/dist/runtime/host-load-child-environment.js +76 -0
- package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
- package/dist/runtime/host-load-forge-cgroups.js +140 -0
- package/dist/runtime/host-load-governor-config.d.ts +52 -0
- package/dist/runtime/host-load-governor-config.js +83 -0
- package/dist/runtime/host-load-governor.d.ts +186 -0
- package/dist/runtime/host-load-governor.js +632 -0
- package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
- package/dist/runtime/host-load-ledger-lock.js +187 -0
- package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
- package/dist/runtime/host-load-runtime-settings.js +80 -0
- package/dist/runtime/host-load-sampler.d.ts +156 -0
- package/dist/runtime/host-load-sampler.js +298 -0
- package/dist/runtime/host-load-step-class.d.ts +70 -0
- package/dist/runtime/host-load-step-class.js +161 -0
- package/dist/runtime/host-load-step-reaper.d.ts +27 -0
- package/dist/runtime/host-load-step-reaper.js +95 -0
- package/dist/runtime/host-load-step-run.d.ts +73 -0
- package/dist/runtime/host-load-step-run.js +102 -0
- package/dist/runtime/host-load-test-slot.d.ts +43 -0
- package/dist/runtime/host-load-test-slot.js +81 -0
- package/dist/runtime/host-load-token-ledger.d.ts +200 -0
- package/dist/runtime/host-load-token-ledger.js +453 -0
- package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
- package/dist/runtime/host-load-windows-cpu.js +85 -0
- package/dist/runtime/host-port-broker.d.ts +76 -0
- package/dist/runtime/host-port-broker.js +333 -0
- package/dist/runtime/host-pressure-stall.d.ts +61 -0
- package/dist/runtime/host-pressure-stall.js +168 -0
- package/dist/runtime/host-runtime-contract.d.ts +74 -0
- package/dist/runtime/host-runtime-contract.js +846 -0
- package/dist/runtime/host-runtime-lease.d.ts +287 -0
- package/dist/runtime/host-runtime-lease.js +2763 -0
- package/dist/runtime/host-runtime-promotion.d.ts +55 -0
- package/dist/runtime/host-runtime-promotion.js +254 -0
- 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.d.ts +62 -0
- package/dist/runtime/managed-command-teardown.js +596 -0
- package/dist/runtime/memory-capacity.d.ts +70 -0
- package/dist/runtime/memory-capacity.js +123 -0
- package/dist/runtime/native-test-postgres-fallback.d.ts +69 -0
- package/dist/runtime/native-test-postgres-fallback.js +143 -0
- package/dist/runtime/node-host-runtime-adapter.d.ts +54 -0
- package/dist/runtime/node-host-runtime-adapter.js +286 -0
- package/dist/runtime/pinned-directory-process.d.ts +9 -0
- package/dist/runtime/pinned-directory-process.js +61 -0
- package/dist/runtime/pinned-source-directory.d.ts +17 -0
- package/dist/runtime/pinned-source-directory.js +94 -0
- package/dist/runtime/playwright-browser-cache.d.ts +39 -0
- package/dist/runtime/playwright-browser-cache.js +227 -0
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +39 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +274 -0
- package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
- package/dist/runtime/prepared-runtime-identity.js +218 -0
- package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
- package/dist/runtime/prepared-runtime-readiness.js +285 -0
- package/dist/runtime/runner-settings.d.ts +104 -0
- package/dist/runtime/runner-settings.js +236 -0
- package/dist/runtime/runtime-isolation-lease.d.ts +67 -0
- package/dist/runtime/runtime-isolation-lease.js +161 -0
- package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
- package/dist/runtime/workspace-resource-estimator.js +174 -0
- package/dist/sandbox/command-runner.d.ts +4 -0
- package/dist/sandbox/command-runner.js +47 -0
- package/dist/sandbox/contract.d.ts +5 -0
- package/dist/sandbox/contract.js +276 -0
- package/dist/sandbox/event-budget.d.ts +11 -0
- package/dist/sandbox/event-budget.js +27 -0
- package/dist/sandbox/host-capacity-broker.d.ts +115 -0
- package/dist/sandbox/host-capacity-broker.js +336 -0
- package/dist/sandbox/image-policy.d.ts +35 -0
- package/dist/sandbox/image-policy.js +247 -0
- package/dist/sandbox/index.d.ts +5 -0
- package/dist/sandbox/index.js +5 -0
- package/dist/sandbox/lease-watchdog.d.ts +18 -0
- package/dist/sandbox/lease-watchdog.js +67 -0
- package/dist/sandbox/managed-branch.d.ts +13 -0
- package/dist/sandbox/managed-branch.js +36 -0
- package/dist/sandbox/preflight.d.ts +84 -0
- package/dist/sandbox/preflight.js +521 -0
- package/dist/sandbox/process.d.ts +20 -0
- package/dist/sandbox/process.js +209 -0
- package/dist/sandbox/provider-auth/codex.d.ts +26 -0
- package/dist/sandbox/provider-auth/codex.js +212 -0
- package/dist/sandbox/repository-lock.d.ts +6 -0
- package/dist/sandbox/repository-lock.js +129 -0
- package/dist/sandbox/runtime.d.ts +311 -0
- package/dist/sandbox/runtime.js +2407 -0
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/sandbox/sandbox.types.d.ts +93 -0
- package/dist/sandbox/sandbox.types.js +1 -0
- package/dist/sandbox/smoke.d.ts +76 -0
- package/dist/sandbox/smoke.js +380 -0
- package/dist/sandbox/worker-supervisor.d.ts +13 -0
- package/dist/sandbox/worker-supervisor.js +36 -0
- package/dist/sandbox/worker.d.ts +1 -0
- package/dist/sandbox/worker.js +225 -0
- package/dist/sandbox/workspace.service.d.ts +13 -0
- package/dist/sandbox/workspace.service.js +74 -0
- package/dist/session/architect-waits.d.ts +2 -0
- package/dist/session/architect-waits.js +138 -0
- package/dist/session/managed-attempt-tools.d.ts +48 -0
- package/dist/session/managed-attempt-tools.js +1299 -0
- package/dist/session/managed-build-coordinator.d.ts +5 -0
- package/dist/session/managed-build-coordinator.js +109 -0
- package/dist/session/managed-build-receipt.d.ts +26 -0
- package/dist/session/managed-build-receipt.js +342 -0
- package/dist/session/managed-command-host-load.d.ts +47 -0
- package/dist/session/managed-command-host-load.js +83 -0
- package/dist/session/managed-verification-timeouts.d.ts +8 -0
- package/dist/session/managed-verification-timeouts.js +17 -0
- package/dist/session/mcp-argument-coercion.d.ts +23 -0
- package/dist/session/mcp-argument-coercion.js +121 -0
- package/dist/session/phase-completion.artifacts.d.ts +34 -0
- package/dist/session/phase-completion.artifacts.js +903 -0
- 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 +65 -42
- package/dist/session/phase-completion.helpers.d.ts +117 -0
- package/dist/session/phase-completion.helpers.js +708 -0
- package/dist/session/phase-completion.js +130 -3007
- package/dist/session/phase-completion.mcp-args.d.ts +9 -0
- package/dist/session/phase-completion.mcp-args.js +156 -0
- package/dist/session/phase-completion.prompts.d.ts +14 -0
- package/dist/session/phase-completion.prompts.js +238 -0
- package/dist/session/phase-completion.runtime.d.ts +43 -0
- package/dist/session/phase-completion.runtime.js +721 -0
- 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 -0
- package/dist/session/phase-completion.schemas.js +836 -0
- package/dist/session/phase-completion.validation.d.ts +37 -0
- package/dist/session/phase-completion.validation.js +874 -0
- package/dist/session/pre-publication-host-load.d.ts +27 -0
- package/dist/session/pre-publication-host-load.js +111 -0
- package/dist/session/pre-publication-native-postgres.d.ts +30 -0
- package/dist/session/pre-publication-native-postgres.js +111 -0
- package/dist/session/pre-publication-pass.d.ts +61 -0
- package/dist/session/pre-publication-pass.js +148 -0
- package/dist/session/pre-publication-process.d.ts +23 -0
- package/dist/session/pre-publication-process.js +109 -0
- package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
- package/dist/session/pre-publication-skipped-tests.js +109 -0
- 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 +91 -0
- package/dist/session/pre-publication-validation.js +670 -0
- package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
- package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
- package/dist/session/provider-cli/ci-repair-readiness.d.ts +16 -0
- package/dist/session/provider-cli/ci-repair-readiness.js +110 -0
- package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
- package/dist/session/provider-cli/claude-background-work.js +181 -0
- package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
- package/dist/session/provider-cli/host-build-lock.js +30 -0
- package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
- package/dist/session/provider-cli/pre-publication-repair.js +276 -0
- package/dist/session/provider-cli/provider-cli.artifacts.d.ts +96 -0
- package/dist/session/provider-cli/provider-cli.artifacts.js +818 -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-payloads.d.ts +12 -0
- package/dist/session/provider-cli/provider-cli.deterministic-payloads.js +279 -0
- package/dist/session/provider-cli/provider-cli.deterministic.d.ts +14 -0
- package/dist/session/provider-cli/provider-cli.deterministic.js +407 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +114 -0
- package/dist/session/provider-cli/provider-cli.process.js +757 -0
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +62 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +770 -0
- package/dist/session/provider-cli/provider-cli.qa-sidecars.d.ts +11 -0
- package/dist/session/provider-cli/provider-cli.qa-sidecars.js +66 -0
- package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
- package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +30 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +120 -0
- package/dist/session/provider-cli/provider-cli.service.d.ts +53 -53
- package/dist/session/provider-cli/provider-cli.service.js +1299 -2523
- package/dist/session/provider-cli/provider-cli.types.d.ts +38 -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 +10 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +92 -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 +40 -0
- package/dist/session/provider-cli/provider-output-state.js +832 -0
- package/dist/session/provider-cli/provider-usage.d.ts +9 -1
- package/dist/session/provider-cli/provider-usage.js +28 -5
- 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/publishable-worktree-changes.d.ts +54 -0
- package/dist/session/publishable-worktree-changes.js +193 -0
- package/dist/session/qa-sidecar-validation.d.ts +6 -0
- package/dist/session/qa-sidecar-validation.js +28 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
- package/dist/session/sandbox-host-capacity-gate.js +257 -0
- package/dist/session/session-redaction.d.ts +3 -0
- package/dist/session/session-redaction.js +298 -0
- package/dist/session/session.base.d.ts +14 -1
- package/dist/session/session.service.d.ts +17 -2
- package/dist/session/session.service.js +708 -60
- package/dist/session/session.types.d.ts +327 -3
- package/dist/session/session.types.js +951 -10
- package/dist/session/sidecar-json-shape.d.ts +31 -0
- package/dist/session/sidecar-json-shape.js +217 -0
- package/dist/session/unreferenced-exports.d.ts +12 -0
- package/dist/session/unreferenced-exports.js +59 -0
- package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
- package/dist/session/workspace-runtime-fingerprint.js +138 -0
- package/dist/shared/format/format-bytes.d.ts +1 -0
- package/dist/shared/format/format-bytes.js +9 -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/git/git.js +2 -1
- package/dist/shared/path/path.d.ts +1 -0
- package/dist/shared/path/path.js +21 -1
- package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
- package/dist/shared/process/dotnet-toolchain.js +307 -0
- package/dist/shared/process/host-process-recovery.d.ts +23 -0
- package/dist/shared/process/host-process-recovery.js +99 -0
- package/dist/shared/process/host-process-supervisor.d.ts +72 -0
- package/dist/shared/process/host-process-supervisor.js +383 -0
- 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 +70 -0
- package/dist/shared/process/process.js +224 -16
- 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 +26 -0
- package/dist/shared/process/windows-launch.js +109 -0
- package/dist/shared/provider-capabilities.d.ts +4 -0
- package/dist/shared/provider-capabilities.js +95 -0
- package/dist/shared/redaction/redaction.d.ts +1 -0
- package/dist/shared/redaction/redaction.js +47 -4
- package/dist/shared/time/monotonic.d.ts +1 -0
- package/dist/shared/time/monotonic.js +8 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/artifact-injector.d.ts +3 -2
- package/dist/worktree/artifact-injector.js +82 -10
- package/dist/worktree/dependency-warmer.d.ts +78 -1
- package/dist/worktree/dependency-warmer.js +731 -13
- package/dist/worktree/index.d.ts +2 -1
- package/dist/worktree/index.js +1 -0
- package/dist/worktree/prior-phase-artifact-hydrator.d.ts +2 -0
- package/dist/worktree/prior-phase-artifact-hydrator.js +136 -0
- package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
- package/dist/worktree/story-qa-reference-hydrator.js +253 -0
- package/dist/worktree/wip-git.d.ts +33 -0
- package/dist/worktree/wip-git.js +122 -0
- package/dist/worktree/wip-refs.d.ts +62 -0
- package/dist/worktree/wip-refs.js +119 -0
- package/dist/worktree/wip-restore.d.ts +38 -0
- package/dist/worktree/wip-restore.js +190 -0
- package/dist/worktree/wip-snapshot.d.ts +50 -0
- package/dist/worktree/wip-snapshot.js +268 -0
- package/dist/worktree/worktree-paths.d.ts +4 -0
- package/dist/worktree/worktree-paths.js +30 -0
- package/dist/worktree/worktree-wip-events.d.ts +18 -0
- package/dist/worktree/worktree-wip-events.js +98 -0
- package/dist/worktree/worktree-wip.d.ts +49 -0
- package/dist/worktree/worktree-wip.js +182 -0
- package/dist/worktree/worktree.base.d.ts +10 -1
- package/dist/worktree/worktree.service.d.ts +30 -4
- package/dist/worktree/worktree.service.js +379 -54
- package/dist/worktree/worktree.types.d.ts +38 -1
- package/package.json +12 -7
- package/runtime/windows-job-supervisor.ps1 +722 -0
- package/runtime/windows-listener-owner.ps1 +33 -0
|
@@ -0,0 +1,2763 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import { statfsSync } from "node:fs";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { assertHostAttemptRootIdentity, retainHostDiagnostics } from "./host-diagnostics.js";
|
|
7
|
+
import { assertHostExecutionRoot, compactHostAttemptId } from "./host-execution-root.js";
|
|
8
|
+
import { PreparedRuntimeReadiness } from "./prepared-runtime-readiness.js";
|
|
9
|
+
import { preparedRuntimeIdentity } from "./prepared-runtime-identity.js";
|
|
10
|
+
import { ForgeFailureError } from "../session/session.types.js";
|
|
11
|
+
import { resolveExistingDirectoryPath } from "../shared/path/path.js";
|
|
12
|
+
import { formatBytes } from "../shared/format/format-bytes.js";
|
|
13
|
+
import { StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.process.js";
|
|
14
|
+
import { createRuntimeIsolationLease, renewRuntimeIsolationLease, transitionRuntimeIsolationLease, validRuntimeIsolationLease, withRuntimeIsolationResources, } from "./runtime-isolation-lease.js";
|
|
15
|
+
import { hostPortEnvironment, loadHostRuntimeContract, newAttemptApiMasterKey, withAttemptApiMasterKey, } from "./host-runtime-contract.js";
|
|
16
|
+
import { HostPortBroker, } from "./host-port-broker.js";
|
|
17
|
+
import { NodeHostRuntimeAdapter, } from "./node-host-runtime-adapter.js";
|
|
18
|
+
import { AttemptProcessSupervisorRegistry } from "./attempt-process-supervisor-registry.js";
|
|
19
|
+
import { terminateAttemptManagedCommands } from "./managed-command-teardown.js";
|
|
20
|
+
import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "./attempt-database-broker.js";
|
|
21
|
+
import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
|
|
22
|
+
import { HostListenerInspector } from "./host-listener-inspector.js";
|
|
23
|
+
import { RecoveryStabilizedMemory, buildMemoryAdmissionDiagnostics, resolveAdaptiveMemoryReserveBytes, } from "./memory-capacity.js";
|
|
24
|
+
import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
|
|
25
|
+
import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, readmitHostRuntimeContract, } from "./host-runtime-promotion.js";
|
|
26
|
+
import { ExactHostProcessRecovery, } from "../shared/process/host-process-recovery.js";
|
|
27
|
+
import { resetGeneratedOutputs } from "./generated-output-reset.js";
|
|
28
|
+
import { assertCanonicalDirectory, createCanonicalDirectory } from "./attempt-private-directory.js";
|
|
29
|
+
import { readCanonicalSourceFile } from "./canonical-source-file.js";
|
|
30
|
+
import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
|
|
31
|
+
import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
|
|
32
|
+
import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, executeAspNetRuntimeBuild, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
|
|
33
|
+
import { HostLoadGovernor } from "./host-load-governor.js";
|
|
34
|
+
import { hostLoadChildEnvironment } from "./host-load-child-environment.js";
|
|
35
|
+
import { aspNetPrebuildStepClass } from "./host-load-step-class.js";
|
|
36
|
+
import { attachSupervisedStepProcess, runHostGovernedStep } from "./host-load-step-run.js";
|
|
37
|
+
import { HostLoadSampler } from "./host-load-sampler.js";
|
|
38
|
+
const hostCapacityWaiterScanLimit = 64;
|
|
39
|
+
const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
|
|
40
|
+
export class HostRuntimeLeaseManager {
|
|
41
|
+
stateRoot;
|
|
42
|
+
processSupervisors;
|
|
43
|
+
processRunner;
|
|
44
|
+
listenerInspector;
|
|
45
|
+
promotionStore;
|
|
46
|
+
playwrightAdapter;
|
|
47
|
+
processRecovery;
|
|
48
|
+
capacityResourceSample;
|
|
49
|
+
databaseBroker;
|
|
50
|
+
preparedReadiness;
|
|
51
|
+
active = new Map();
|
|
52
|
+
pendingRenewals = new Map();
|
|
53
|
+
acquiringAdmissions = new Set();
|
|
54
|
+
admissions = new Map();
|
|
55
|
+
singletonOwners = new Map();
|
|
56
|
+
singletonWaiters = [];
|
|
57
|
+
parallelProjectOwners = new Map();
|
|
58
|
+
parallelProjectWaiters = [];
|
|
59
|
+
capacityReservations = new Map();
|
|
60
|
+
capacityWaiters = [];
|
|
61
|
+
capacityWaiterScanCursor = 0;
|
|
62
|
+
backgroundAdmissionWaiters = [];
|
|
63
|
+
degraded = new Map();
|
|
64
|
+
knownPromotions = new Map();
|
|
65
|
+
ledgerWriteTail = Promise.resolve();
|
|
66
|
+
workspaceAvailableBytes = Number.MAX_SAFE_INTEGER;
|
|
67
|
+
portBroker;
|
|
68
|
+
nodeAdapter;
|
|
69
|
+
/** Rebuilt by applyCapacityLimits (decision 0014); every admission reads the current one. */
|
|
70
|
+
capacityConfiguration;
|
|
71
|
+
memoryAvailability;
|
|
72
|
+
executionRoot;
|
|
73
|
+
/** Host-wide admission for heavy steps (decisions 0013, 0018): the host test slot, and the budget when on. */
|
|
74
|
+
hostLoadGovernor;
|
|
75
|
+
requirementsCheck = null;
|
|
76
|
+
/** Installs the decision 0013 accept-time requirements recheck for host attempts. */
|
|
77
|
+
setRequirementsCheck(check) {
|
|
78
|
+
this.requirementsCheck = check;
|
|
79
|
+
}
|
|
80
|
+
constructor(stateRoot, portBroker = new HostPortBroker(), nodeAdapter, processSupervisors = new AttemptProcessSupervisorRegistry(), processRunner = new StreamingProviderProcessRunner(), listenerInspector = new HostListenerInspector(), promotionStore = new HostParallelPromotionStore(stateRoot), playwrightAdapter = new PlaywrightHostRuntimeAdapter(), processRecovery = new ExactHostProcessRecovery(), capacityResourceSample, executionRoot, databaseBroker = null, hostLoad = null) {
|
|
81
|
+
this.stateRoot = stateRoot;
|
|
82
|
+
this.processSupervisors = processSupervisors;
|
|
83
|
+
this.processRunner = processRunner;
|
|
84
|
+
this.listenerInspector = listenerInspector;
|
|
85
|
+
this.promotionStore = promotionStore;
|
|
86
|
+
this.playwrightAdapter = playwrightAdapter;
|
|
87
|
+
this.processRecovery = processRecovery;
|
|
88
|
+
this.capacityResourceSample = capacityResourceSample;
|
|
89
|
+
this.databaseBroker = databaseBroker;
|
|
90
|
+
this.hostLoadGovernor = new HostLoadGovernor({ stateRoot, load: hostLoad ?? new HostLoadSampler() });
|
|
91
|
+
this.executionRoot = path.resolve(executionRoot ?? stateRoot);
|
|
92
|
+
if (executionRoot !== undefined)
|
|
93
|
+
assertHostExecutionRoot(this.executionRoot);
|
|
94
|
+
this.preparedReadiness = new PreparedRuntimeReadiness(this, promotionStore, (id, fence) => this.release(id, fence, true), () => new HostRuntimeAdmissionExpiredError());
|
|
95
|
+
this.portBroker = portBroker;
|
|
96
|
+
this.nodeAdapter = nodeAdapter ?? new NodeHostRuntimeAdapter(portBroker);
|
|
97
|
+
this.capacityConfiguration = loadHostCapacityConfiguration(capacityResourceSample);
|
|
98
|
+
this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
|
|
99
|
+
}
|
|
100
|
+
/** Today's defaults for the limits the server can push, before any env bound (decision 0014). */
|
|
101
|
+
capacityLimitDefaults() {
|
|
102
|
+
return {
|
|
103
|
+
maxConcurrentAttempts: this.capacityConfiguration.defaultHardMaxAttempts,
|
|
104
|
+
memoryReserveBytes: this.capacityConfiguration.adaptiveHostReserveBytes,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Decision 0014: the bridge's effective max attempts and memory reserve. They
|
|
109
|
+
* apply from the next attempt admission; admitted attempts keep their
|
|
110
|
+
* reservations and are never preempted, even when the new limit is lower than
|
|
111
|
+
* what already runs. The idle reserve follows the reserve as at startup.
|
|
112
|
+
*/
|
|
113
|
+
applyCapacityLimits(limits) {
|
|
114
|
+
const current = this.capacityConfiguration;
|
|
115
|
+
const hardMaxAttempts = Math.max(1, Math.min(32, Math.floor(limits.maxConcurrentAttempts)));
|
|
116
|
+
const hostReserveBytes = Math.max(512 * 1024 ** 2, Math.floor(limits.memoryReserveBytes));
|
|
117
|
+
if (hardMaxAttempts === current.hardMaxAttempts && hostReserveBytes === current.hostReserveBytes)
|
|
118
|
+
return;
|
|
119
|
+
this.capacityConfiguration = {
|
|
120
|
+
...current,
|
|
121
|
+
hardMaxAttempts,
|
|
122
|
+
hostReserveBytes,
|
|
123
|
+
idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, current),
|
|
124
|
+
};
|
|
125
|
+
// A raised limit may admit queued attempts now rather than at their next recheck.
|
|
126
|
+
this.drainAdmissionWaiters();
|
|
127
|
+
}
|
|
128
|
+
hostLoadChildEnvironment() {
|
|
129
|
+
return this.hostLoadGovernor.enabled ? hostLoadChildEnvironment(this.stateRoot) : {};
|
|
130
|
+
}
|
|
131
|
+
async reap(options) {
|
|
132
|
+
// Heavy-step tokens whose owner died or whose lease lapsed are returned first.
|
|
133
|
+
await this.hostLoadGovernor.reclaim().catch(() => undefined);
|
|
134
|
+
await this.refreshKnownPromotions();
|
|
135
|
+
const recoveredAttempts = [];
|
|
136
|
+
const report = {
|
|
137
|
+
examined: 0,
|
|
138
|
+
reaped: 0,
|
|
139
|
+
processesTerminated: 0,
|
|
140
|
+
reusedPidsProtected: 0,
|
|
141
|
+
degraded: 0,
|
|
142
|
+
recoveredAttempts,
|
|
143
|
+
};
|
|
144
|
+
for (const ledger of await this.readLedgers()) {
|
|
145
|
+
const lease = ledger.runtimeLease;
|
|
146
|
+
if (lease.runnerId !== options.runnerId)
|
|
147
|
+
continue;
|
|
148
|
+
// A released ledger with its original attempt root is intentionally retained
|
|
149
|
+
// evidence that exceeded the diagnostics archive budget. It owns no runtime
|
|
150
|
+
// resources, but still requires process-identity recovery below on restart.
|
|
151
|
+
if (lease.state === "released") {
|
|
152
|
+
const attemptRoot = this.attemptRoot(lease.dispatchAttemptId);
|
|
153
|
+
const rootExists = await fs.stat(attemptRoot).then(() => true, error => {
|
|
154
|
+
if (error.code === "ENOENT")
|
|
155
|
+
return false;
|
|
156
|
+
throw error;
|
|
157
|
+
});
|
|
158
|
+
if (!rootExists) {
|
|
159
|
+
await fs.rm(this.ledgerPath(lease.dispatchAttemptId), { force: true });
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const active = this.active.get(lease.dispatchAttemptId);
|
|
164
|
+
if (active) {
|
|
165
|
+
if (active.lease.state !== "degraded")
|
|
166
|
+
continue;
|
|
167
|
+
report.examined += 1;
|
|
168
|
+
try {
|
|
169
|
+
const released = await this.release(lease.dispatchAttemptId, lease.fencingToken);
|
|
170
|
+
if (released?.state === "released")
|
|
171
|
+
report.reaped += 1;
|
|
172
|
+
else
|
|
173
|
+
report.degraded += 1;
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
report.degraded += 1;
|
|
177
|
+
}
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
const staleInstance = lease.runnerInstanceId !== options.runnerInstanceId;
|
|
181
|
+
const expired = Date.parse(lease.expiresAt) <= (options.nowMs ?? Date.now());
|
|
182
|
+
if (!staleInstance && !expired && lease.state !== "released" && lease.state !== "degraded")
|
|
183
|
+
continue;
|
|
184
|
+
report.examined += 1;
|
|
185
|
+
const attemptRoot = this.attemptRoot(lease.dispatchAttemptId);
|
|
186
|
+
const attemptRootIdentity = deserializeHostAttemptRootIdentity(ledger.attemptRootIdentity);
|
|
187
|
+
let outcomes;
|
|
188
|
+
try {
|
|
189
|
+
if (!attemptRootIdentity) {
|
|
190
|
+
throw new Error("host_runtime_reaper_invalid: original attempt-root identity is unavailable.");
|
|
191
|
+
}
|
|
192
|
+
outcomes = await this.recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity);
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
await this.markLedgerDegraded(ledger);
|
|
196
|
+
report.degraded += 1;
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
report.processesTerminated += outcomes.filter(outcome => outcome === "terminated").length;
|
|
200
|
+
report.reusedPidsProtected += outcomes.filter(outcome => outcome === "pid_reused").length;
|
|
201
|
+
if (outcomes.includes("unverifiable")) {
|
|
202
|
+
await this.markLedgerDegraded(ledger);
|
|
203
|
+
report.degraded += 1;
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
// The runtime has already been released. Keep the over-budget original
|
|
207
|
+
// evidence without re-copying it or reacquiring a capacity claim.
|
|
208
|
+
if (lease.state === "released")
|
|
209
|
+
continue;
|
|
210
|
+
// Every supervised tree of this previous-instance attempt is proved gone,
|
|
211
|
+
// so no provider can still act for it. Diagnostics handling below never
|
|
212
|
+
// revives a process, so the proof stands even if cleanup degrades. An
|
|
213
|
+
// attempt with no ownership record at all may have been mid-launch, so
|
|
214
|
+
// it is not reported and keeps its unknown outcome.
|
|
215
|
+
if (staleInstance && outcomes.length > 0) {
|
|
216
|
+
recoveredAttempts.push({
|
|
217
|
+
dispatchAttemptId: lease.dispatchAttemptId,
|
|
218
|
+
fencingToken: lease.fencingToken,
|
|
219
|
+
runnerInstanceId: lease.runnerInstanceId,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
try {
|
|
223
|
+
const releasing = transitionHostLeaseForCleanup(lease, "releasing");
|
|
224
|
+
await this.writeLedger(releasing, ledger.repoId, attemptRootIdentity);
|
|
225
|
+
let evidenceRetainedAtAttemptRoot = false;
|
|
226
|
+
try {
|
|
227
|
+
await retainHostDiagnostics(this.stateRoot, attemptRoot, lease.dispatchAttemptId, attemptRootIdentity, this.executionRoot);
|
|
228
|
+
}
|
|
229
|
+
catch {
|
|
230
|
+
// Exact process recovery above already proved that the runtime is gone.
|
|
231
|
+
// Diagnostics retention can independently refuse a changed inventory,
|
|
232
|
+
// an unsafe archive path, or an over-budget source. Preserve the
|
|
233
|
+
// original attempt root and a released ledger for reconciliation, but
|
|
234
|
+
// never turn evidence-only work back into a capacity-owning runtime.
|
|
235
|
+
evidenceRetainedAtAttemptRoot = true;
|
|
236
|
+
}
|
|
237
|
+
if (evidenceRetainedAtAttemptRoot) {
|
|
238
|
+
const released = transitionRuntimeIsolationLease(releasing, "released");
|
|
239
|
+
await this.writeLedger(released, ledger.repoId, attemptRootIdentity);
|
|
240
|
+
this.forgetDegraded(lease.dispatchAttemptId, lease.fencingToken);
|
|
241
|
+
report.reaped += 1;
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
await removeHostAttemptRoot(attemptRoot);
|
|
245
|
+
await fs.rm(this.ledgerPath(lease.dispatchAttemptId), { force: true });
|
|
246
|
+
this.forgetDegraded(lease.dispatchAttemptId, lease.fencingToken);
|
|
247
|
+
report.reaped += 1;
|
|
248
|
+
}
|
|
249
|
+
catch {
|
|
250
|
+
await this.markLedgerDegraded(ledger);
|
|
251
|
+
report.degraded += 1;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
// Databases issued to attempts that ended without a clean release (a Bridge crash, or a
|
|
255
|
+
// drop that met a lingering session) are removed once no live lease holds them.
|
|
256
|
+
// A degraded lease may still own running processes after a restart, so its database is kept.
|
|
257
|
+
await this.databaseBroker?.reapOrphans(id => this.active.has(id) || this.degraded.has(id)).catch(() => undefined);
|
|
258
|
+
// Heavy-step tokens of a dead owner with no recorded process tree (an attempt that
|
|
259
|
+
// ended with a crashed bridge or MCP server) are returned once no live lease holds
|
|
260
|
+
// their attempt; a degraded lease may still own the running step, so its tokens stay.
|
|
261
|
+
await this.hostLoadGovernor.releaseOrphaned(token => !token.dispatchAttemptId
|
|
262
|
+
|| (!this.active.has(token.dispatchAttemptId) && !this.degraded.has(token.dispatchAttemptId))).catch(() => undefined);
|
|
263
|
+
return report;
|
|
264
|
+
}
|
|
265
|
+
snapshot() {
|
|
266
|
+
this.reconcileReservationOwners();
|
|
267
|
+
const projects = new Map();
|
|
268
|
+
for (const promotion of this.knownPromotions.values()) {
|
|
269
|
+
const project = capacityProject(projects, promotion.repoId);
|
|
270
|
+
project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_parallel_safe");
|
|
271
|
+
project.runtimeContractFingerprint = promotion.runtimeContractFingerprint;
|
|
272
|
+
project.runtimeContractSource = promotion.runtimeContractSource ?? null;
|
|
273
|
+
project.promotedAt = promotion.observedAt;
|
|
274
|
+
}
|
|
275
|
+
for (const [dispatchAttemptId, admission] of this.admissions) {
|
|
276
|
+
const active = this.active.get(dispatchAttemptId);
|
|
277
|
+
const project = capacityProject(projects, admission.repoId);
|
|
278
|
+
if (active) {
|
|
279
|
+
if (active.lease.state === "degraded") {
|
|
280
|
+
project.degradedAttempts += 1;
|
|
281
|
+
project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_serial_only");
|
|
282
|
+
}
|
|
283
|
+
else {
|
|
284
|
+
project.activeAttempts += 1;
|
|
285
|
+
const effectiveConcurrency = effectiveHostConcurrency(active.lease, active.runtimeContract, active.executionClass);
|
|
286
|
+
project.safetyClass = conservativeSafetyClass(project.safetyClass, effectiveConcurrency === "host_parallel_safe"
|
|
287
|
+
? effectiveConcurrency
|
|
288
|
+
: admission.executionClass === "analysis_only"
|
|
289
|
+
? "host_parallel_safe"
|
|
290
|
+
: admission.parallelProjectKey && admission.provisionalPromotionFingerprint
|
|
291
|
+
? "host_parallel_candidate"
|
|
292
|
+
: "host_serial_only");
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
else {
|
|
296
|
+
project.reservedAttempts += 1;
|
|
297
|
+
project.safetyClass = conservativeSafetyClass(project.safetyClass, admission.executionClass === "analysis_only"
|
|
298
|
+
? "host_parallel_safe"
|
|
299
|
+
: admission.provisionalPromotionFingerprint ? "host_parallel_candidate" : "host_serial_only");
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
for (const [dispatchAttemptId, degraded] of this.degraded) {
|
|
303
|
+
if (this.active.has(dispatchAttemptId) || !degraded.repoId)
|
|
304
|
+
continue;
|
|
305
|
+
const project = capacityProject(projects, degraded.repoId);
|
|
306
|
+
project.degradedAttempts += 1;
|
|
307
|
+
project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_serial_only");
|
|
308
|
+
}
|
|
309
|
+
for (const waiter of this.singletonWaiters) {
|
|
310
|
+
const repoId = repoIdFromProjectSingletonKeys(waiter.keys);
|
|
311
|
+
if (!repoId)
|
|
312
|
+
continue;
|
|
313
|
+
const project = capacityProject(projects, repoId);
|
|
314
|
+
project.waitingAttempts += 1;
|
|
315
|
+
project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_serial_only");
|
|
316
|
+
}
|
|
317
|
+
for (const waiter of this.parallelProjectWaiters) {
|
|
318
|
+
const repoId = repoIdFromProjectSingletonKey(waiter.key);
|
|
319
|
+
if (!repoId)
|
|
320
|
+
continue;
|
|
321
|
+
const project = capacityProject(projects, repoId);
|
|
322
|
+
project.waitingAttempts += 1;
|
|
323
|
+
project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_parallel_candidate");
|
|
324
|
+
}
|
|
325
|
+
for (const waiter of this.backgroundAdmissionWaiters) {
|
|
326
|
+
const repoId = repoIdFromProjectSingletonKeys(waiter.keys);
|
|
327
|
+
if (!repoId)
|
|
328
|
+
continue;
|
|
329
|
+
const project = capacityProject(projects, repoId);
|
|
330
|
+
project.waitingAttempts += 1;
|
|
331
|
+
project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_serial_only");
|
|
332
|
+
}
|
|
333
|
+
// A prepared-runtime verification remains foreground demand after its
|
|
334
|
+
// preparation admission is released and before the internal probe has
|
|
335
|
+
// acquired a normal admission. Report that barrier as waiting capacity so
|
|
336
|
+
// the server cannot mistake the transient gap for an idle host and dispatch
|
|
337
|
+
// readiness probes in a tight loop.
|
|
338
|
+
const unrepresentedPrepared = this.preparedReadiness.pendingSnapshots()
|
|
339
|
+
.filter(pending => !this.hasAttemptRepresentation(pending.probeDispatchAttemptId ?? pending.dispatchAttemptId, pending.probeFencingToken ?? pending.fencingToken));
|
|
340
|
+
for (const pending of unrepresentedPrepared) {
|
|
341
|
+
const project = capacityProject(projects, pending.repoId);
|
|
342
|
+
project.waitingAttempts += 1;
|
|
343
|
+
project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_parallel_candidate");
|
|
344
|
+
}
|
|
345
|
+
const activeAttempts = [...this.active.values()]
|
|
346
|
+
.filter(active => active.lease.state !== "degraded").length;
|
|
347
|
+
const degradedAttempts = new Set([
|
|
348
|
+
...this.degraded.keys(),
|
|
349
|
+
...[...this.active.entries()]
|
|
350
|
+
.filter(([, active]) => active.lease.state === "degraded")
|
|
351
|
+
.map(([dispatchAttemptId]) => dispatchAttemptId),
|
|
352
|
+
]).size;
|
|
353
|
+
const hostResources = this.hostResourceSnapshot();
|
|
354
|
+
return {
|
|
355
|
+
activeAttempts,
|
|
356
|
+
preparedWorktreeReadiness: true,
|
|
357
|
+
reservedAttempts: Math.max(0, this.admissions.size - this.active.size),
|
|
358
|
+
waitingAttempts: this.singletonWaiters.length
|
|
359
|
+
+ this.parallelProjectWaiters.length
|
|
360
|
+
+ this.capacityWaiters.length
|
|
361
|
+
+ this.backgroundAdmissionWaiters.length
|
|
362
|
+
+ unrepresentedPrepared.length,
|
|
363
|
+
degradedAttempts,
|
|
364
|
+
exclusiveReservations: this.singletonOwners.size,
|
|
365
|
+
sharedReservations: [...this.parallelProjectOwners.values()]
|
|
366
|
+
.reduce((count, owners) => count + owners.size, 0),
|
|
367
|
+
...hostResources,
|
|
368
|
+
projects: [...projects.values()]
|
|
369
|
+
.map(project => ({
|
|
370
|
+
...project,
|
|
371
|
+
safetyClass: project.safetyClass ?? "host_serial_only",
|
|
372
|
+
}))
|
|
373
|
+
.sort((left, right) => left.repoId.localeCompare(right.repoId)),
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
hasForegroundDemand() {
|
|
377
|
+
return this.preparedReadiness.hasPending()
|
|
378
|
+
|| [...this.admissions.values()].some(admission => admission.priority === "foreground")
|
|
379
|
+
|| this.singletonWaiters.some(waiter => waiter.priority === "foreground")
|
|
380
|
+
|| this.parallelProjectWaiters.some(waiter => waiter.priority === "foreground")
|
|
381
|
+
|| this.capacityWaiters.some(waiter => waiter.priority === "foreground");
|
|
382
|
+
}
|
|
383
|
+
async acquirePreparation(dispatch, signal) {
|
|
384
|
+
// Discovery probes already own their verification lifecycle. Analysis-only
|
|
385
|
+
// work never launches the application and must not wait for a runtime wave.
|
|
386
|
+
if (runtimeExecutionClass(dispatch) === "analysis_only" || runtimeAdmissionPriority(dispatch) === "background") {
|
|
387
|
+
return await this.acquire(dispatch, signal);
|
|
388
|
+
}
|
|
389
|
+
return await this.preparedReadiness.acquire(dispatch, signal);
|
|
390
|
+
}
|
|
391
|
+
async acquire(dispatch, signal) {
|
|
392
|
+
const sandbox = dispatch.sandbox;
|
|
393
|
+
if (!sandbox || sandbox.executionMode !== "host") {
|
|
394
|
+
throw new Error("host_runtime_lease_invalid: managed host sandbox context is required.");
|
|
395
|
+
}
|
|
396
|
+
uuidHex(sandbox.dispatchAttemptId, "dispatch attempt");
|
|
397
|
+
uuidHex(dispatch.lease.fencingToken, "fencing token");
|
|
398
|
+
const owner = {
|
|
399
|
+
dispatchAttemptId: sandbox.dispatchAttemptId,
|
|
400
|
+
fencingToken: dispatch.lease.fencingToken,
|
|
401
|
+
};
|
|
402
|
+
const existing = this.admissions.get(sandbox.dispatchAttemptId);
|
|
403
|
+
if (existing) {
|
|
404
|
+
if (existing.fencingToken !== owner.fencingToken) {
|
|
405
|
+
throw new Error("host_runtime_singleton_conflict: dispatch attempt already holds admission under a different fence.");
|
|
406
|
+
}
|
|
407
|
+
return existing.keys;
|
|
408
|
+
}
|
|
409
|
+
const executionClass = runtimeExecutionClass(dispatch);
|
|
410
|
+
const priority = runtimeAdmissionPriority(dispatch);
|
|
411
|
+
const promotion = executionClass === "managed_runtime"
|
|
412
|
+
? await this.promotionStore.load(dispatch.repo.id)
|
|
413
|
+
: null;
|
|
414
|
+
if (promotion)
|
|
415
|
+
this.knownPromotions.set(promotion.repoId, promotion);
|
|
416
|
+
const projectKey = executionClass === "analysis_only"
|
|
417
|
+
? projectHostAnalysisKey(dispatch.repo.id)
|
|
418
|
+
: projectHostRuntimeSingletonKey(dispatch.repo.id);
|
|
419
|
+
const useParallelAdmission = priority === "foreground"
|
|
420
|
+
&& dispatch.cycleRun.phase !== "prepared_readiness"
|
|
421
|
+
&& (promotion !== null || executionClass === "analysis_only");
|
|
422
|
+
let keys = useParallelAdmission ? [] : [projectKey];
|
|
423
|
+
const resources = normalizedHostResourceRequest(sandbox.requestedResources);
|
|
424
|
+
const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
|
|
425
|
+
? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
|
|
426
|
+
: dispatch.lease.expiresAt;
|
|
427
|
+
const acquisitionKey = hostRuntimeOwnerKey(owner);
|
|
428
|
+
this.acquiringAdmissions.add(acquisitionKey);
|
|
429
|
+
try {
|
|
430
|
+
try {
|
|
431
|
+
if (priority === "background") {
|
|
432
|
+
await this.refreshWorkspaceCapacity();
|
|
433
|
+
keys = await this.reserveBackgroundAdmission(keys, owner, resources, expiresAt, signal);
|
|
434
|
+
}
|
|
435
|
+
else if (useParallelAdmission) {
|
|
436
|
+
await this.reserveParallelProject(projectKey, owner, expiresAt, signal, priority);
|
|
437
|
+
}
|
|
438
|
+
else {
|
|
439
|
+
keys = await this.reserveSingletonKeys(keys, owner, expiresAt, signal, priority);
|
|
440
|
+
}
|
|
441
|
+
if (priority === "foreground") {
|
|
442
|
+
await this.refreshWorkspaceCapacity();
|
|
443
|
+
const capacityExpiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
|
|
444
|
+
? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
|
|
445
|
+
: expiresAt;
|
|
446
|
+
await this.reserveHostCapacity(owner, resources, capacityExpiresAt, signal, priority);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
catch (error) {
|
|
450
|
+
this.releaseHostCapacity(owner.dispatchAttemptId, owner.fencingToken);
|
|
451
|
+
this.releaseSingletonKeys(owner.dispatchAttemptId, owner.fencingToken);
|
|
452
|
+
this.releaseParallelProjects(owner.dispatchAttemptId, owner.fencingToken);
|
|
453
|
+
this.clearPendingRenewal(owner);
|
|
454
|
+
throw error;
|
|
455
|
+
}
|
|
456
|
+
const admittedPromotion = useParallelAdmission
|
|
457
|
+
? promotion ?? (executionClass === "managed_runtime" && keys.length === 0
|
|
458
|
+
? this.knownPromotions.get(dispatch.repo.id) ?? null
|
|
459
|
+
: null)
|
|
460
|
+
: null;
|
|
461
|
+
this.admissions.set(sandbox.dispatchAttemptId, {
|
|
462
|
+
repoId: dispatch.repo.id,
|
|
463
|
+
fencingToken: owner.fencingToken,
|
|
464
|
+
executionClass,
|
|
465
|
+
priority,
|
|
466
|
+
provisionalPromotionFingerprint: admittedPromotion?.runtimeContractFingerprint ?? null,
|
|
467
|
+
keys,
|
|
468
|
+
parallelProjectKey: useParallelAdmission ? projectKey : null,
|
|
469
|
+
});
|
|
470
|
+
return keys;
|
|
471
|
+
}
|
|
472
|
+
finally {
|
|
473
|
+
this.acquiringAdmissions.delete(acquisitionKey);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
async reserveHostCapacity(owner, resources, expiresAt, signal, priority = "foreground") {
|
|
477
|
+
const existing = this.capacityReservations.get(owner.dispatchAttemptId);
|
|
478
|
+
if (existing) {
|
|
479
|
+
if (!sameSingletonOwner(existing.owner, owner)) {
|
|
480
|
+
throw new Error("host_runtime_capacity_conflict: dispatch attempt already holds capacity under a different fence.");
|
|
481
|
+
}
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
if (signal?.aborted)
|
|
485
|
+
throw cancellationError(signal);
|
|
486
|
+
throwIfAdmissionExpired(expiresAt);
|
|
487
|
+
const impossibleReason = this.hostCapacityImpossibleReason(resources);
|
|
488
|
+
if (impossibleReason)
|
|
489
|
+
throw new HostRuntimeCapacityRequestImpossibleError(impossibleReason);
|
|
490
|
+
if (this.capacityWaiters.length === 0 && this.hostCapacityAvailable(resources)) {
|
|
491
|
+
this.capacityReservations.set(owner.dispatchAttemptId, { owner, resources, state: "pending" });
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
return new Promise((resolve, reject) => {
|
|
495
|
+
const waiter = {
|
|
496
|
+
owner,
|
|
497
|
+
resources,
|
|
498
|
+
priority,
|
|
499
|
+
resolve,
|
|
500
|
+
reject,
|
|
501
|
+
signal,
|
|
502
|
+
expiresAt,
|
|
503
|
+
deadlineTimer: null,
|
|
504
|
+
capacityRecheckTimer: null,
|
|
505
|
+
abort: () => {
|
|
506
|
+
if (!this.detachCapacityWaiter(waiter))
|
|
507
|
+
return;
|
|
508
|
+
this.clearPendingRenewal(owner);
|
|
509
|
+
reject(cancellationError(signal));
|
|
510
|
+
this.drainAdmissionWaiters();
|
|
511
|
+
},
|
|
512
|
+
expire: () => {
|
|
513
|
+
if (!this.detachCapacityWaiter(waiter))
|
|
514
|
+
return;
|
|
515
|
+
this.clearPendingRenewal(owner);
|
|
516
|
+
reject(new HostRuntimeAdmissionExpiredError());
|
|
517
|
+
this.drainAdmissionWaiters();
|
|
518
|
+
},
|
|
519
|
+
};
|
|
520
|
+
waiter.deadlineTimer = scheduleAdmissionDeadline(expiresAt, waiter.expire);
|
|
521
|
+
// Memory, CPU and filesystem capacity can recover without one of our leases
|
|
522
|
+
// being released (for example when an unrelated host process exits). Recheck
|
|
523
|
+
// ambient capacity while queued so readiness probes and attempts do not remain
|
|
524
|
+
// stranded behind a stale low-resource sample.
|
|
525
|
+
waiter.capacityRecheckTimer = setInterval(() => this.drainCapacityWaiters(), 1_000);
|
|
526
|
+
waiter.capacityRecheckTimer.unref?.();
|
|
527
|
+
signal?.addEventListener("abort", waiter.abort, { once: true });
|
|
528
|
+
enqueueAdmissionWaiter(this.capacityWaiters, waiter);
|
|
529
|
+
this.drainCapacityWaiters();
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
async reserveBackgroundAdmission(keys, owner, resources, expiresAt, signal) {
|
|
533
|
+
if (signal?.aborted)
|
|
534
|
+
throw cancellationError(signal);
|
|
535
|
+
throwIfAdmissionExpired(expiresAt);
|
|
536
|
+
return await new Promise((resolve, reject) => {
|
|
537
|
+
const waiter = {
|
|
538
|
+
owner,
|
|
539
|
+
keys,
|
|
540
|
+
resources,
|
|
541
|
+
priority: "background",
|
|
542
|
+
resolve,
|
|
543
|
+
reject,
|
|
544
|
+
signal,
|
|
545
|
+
expiresAt,
|
|
546
|
+
deadlineTimer: null,
|
|
547
|
+
capacityRecheckTimer: null,
|
|
548
|
+
abort: () => {
|
|
549
|
+
removeWaiter(this.backgroundAdmissionWaiters, waiter);
|
|
550
|
+
clearAdmissionDeadline(waiter);
|
|
551
|
+
clearCapacityRecheck(waiter);
|
|
552
|
+
this.clearPendingRenewal(owner);
|
|
553
|
+
reject(cancellationError(signal));
|
|
554
|
+
this.drainAdmissionWaiters();
|
|
555
|
+
},
|
|
556
|
+
expire: () => {
|
|
557
|
+
removeWaiter(this.backgroundAdmissionWaiters, waiter);
|
|
558
|
+
clearCapacityRecheck(waiter);
|
|
559
|
+
signal?.removeEventListener("abort", waiter.abort);
|
|
560
|
+
this.clearPendingRenewal(owner);
|
|
561
|
+
reject(new HostRuntimeAdmissionExpiredError());
|
|
562
|
+
this.drainAdmissionWaiters();
|
|
563
|
+
},
|
|
564
|
+
};
|
|
565
|
+
waiter.deadlineTimer = scheduleAdmissionDeadline(expiresAt, waiter.expire);
|
|
566
|
+
waiter.capacityRecheckTimer = setInterval(() => this.drainAdmissionWaiters(), 1_000);
|
|
567
|
+
waiter.capacityRecheckTimer.unref?.();
|
|
568
|
+
signal?.addEventListener("abort", waiter.abort, { once: true });
|
|
569
|
+
this.backgroundAdmissionWaiters.push(waiter);
|
|
570
|
+
this.drainAdmissionWaiters();
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
hostCapacityAvailable(resources) {
|
|
574
|
+
const capacity = this.hostResourceSnapshot();
|
|
575
|
+
return capacity.availableAttempts >= resources.sandboxSlots
|
|
576
|
+
&& capacity.availableMemoryBytes >= resources.memoryBytes
|
|
577
|
+
&& capacity.availableCpuMillis >= resources.cpuMillis
|
|
578
|
+
&& capacity.availableWorkspaceBytes >= resources.workspaceBytes;
|
|
579
|
+
}
|
|
580
|
+
hostCapacityImpossibleReason(resources) {
|
|
581
|
+
const { hardMaxAttempts, idleHostReserveBytes, cpuReserveMillis } = this.capacityConfiguration;
|
|
582
|
+
if (resources.sandboxSlots > hardMaxAttempts) {
|
|
583
|
+
return `requested ${resources.sandboxSlots} sandbox slots exceed the host maximum of ${hardMaxAttempts}.`;
|
|
584
|
+
}
|
|
585
|
+
const totalMemoryBytes = this.capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
|
|
586
|
+
const maximumMemoryBytes = Math.max(0, totalMemoryBytes - idleHostReserveBytes);
|
|
587
|
+
if (resources.memoryBytes > maximumMemoryBytes) {
|
|
588
|
+
return `requested memory ${resources.memoryBytes} exceeds the host maximum of ${maximumMemoryBytes} bytes after reserve.`;
|
|
589
|
+
}
|
|
590
|
+
const totalCpuMillis = this.capacityResourceSample?.totalCpuMillis ?? os.cpus().length * 1_000;
|
|
591
|
+
const maximumCpuMillis = Math.max(0, totalCpuMillis - cpuReserveMillis);
|
|
592
|
+
if (resources.cpuMillis > maximumCpuMillis) {
|
|
593
|
+
return `requested CPU ${resources.cpuMillis} millis exceeds the host maximum of ${maximumCpuMillis} millis after reserve.`;
|
|
594
|
+
}
|
|
595
|
+
return null;
|
|
596
|
+
}
|
|
597
|
+
hostResourceSnapshot() {
|
|
598
|
+
if (!this.capacityResourceSample) {
|
|
599
|
+
try {
|
|
600
|
+
const stats = statfsSync(this.stateRoot);
|
|
601
|
+
this.workspaceAvailableBytes = Math.max(0, stats.bavail * stats.bsize);
|
|
602
|
+
}
|
|
603
|
+
catch {
|
|
604
|
+
// State root may not exist during the first capability heartbeat. The first
|
|
605
|
+
// admission creates it and refreshes the sample before reserving resources.
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
const { hardMaxAttempts, cpuReserveMillis, workspaceReserveBytes } = this.capacityConfiguration;
|
|
609
|
+
const hostReserveBytes = this.capacityReservations.size === 0
|
|
610
|
+
? this.capacityConfiguration.idleHostReserveBytes
|
|
611
|
+
: this.capacityConfiguration.hostReserveBytes;
|
|
612
|
+
const activeReservationMemoryBytes = [...this.capacityReservations.values()]
|
|
613
|
+
.reduce((total, reservation) => total + reservation.resources.memoryBytes, 0);
|
|
614
|
+
const pendingReservationMemoryBytes = [...this.capacityReservations.values()]
|
|
615
|
+
.filter(reservation => reservation.state === "pending")
|
|
616
|
+
.reduce((total, reservation) => total + reservation.resources.memoryBytes, 0);
|
|
617
|
+
const activeReservationCpuMillis = [...this.capacityReservations.values()]
|
|
618
|
+
.reduce((total, reservation) => total + reservation.resources.cpuMillis, 0);
|
|
619
|
+
const activeReservationWorkspaceBytes = [...this.capacityReservations.values()]
|
|
620
|
+
.reduce((total, reservation) => total + reservation.resources.workspaceBytes, 0);
|
|
621
|
+
const sampledAt = new Date().toISOString();
|
|
622
|
+
const totalMemoryBytes = this.capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
|
|
623
|
+
const rawAvailableMemoryBytes = this.capacityResourceSample?.availableMemoryBytes ?? os.freemem();
|
|
624
|
+
const sampledAvailableMemoryBytes = this.memoryAvailability.observe(rawAvailableMemoryBytes);
|
|
625
|
+
// raw/stabilized available memory already includes every resident host and
|
|
626
|
+
// Forge process. Keep the independent total ceiling scoped to Forge's own
|
|
627
|
+
// reservations; adding ambient use here charges it a second time and can
|
|
628
|
+
// strand work even while more than the requested memory is physically free.
|
|
629
|
+
const committedMemoryBytes = Math.min(totalMemoryBytes, activeReservationMemoryBytes);
|
|
630
|
+
const totalCpuMillis = this.capacityResourceSample?.totalCpuMillis ?? os.cpus().length * 1000;
|
|
631
|
+
const sampledWorkspaceBytes = this.capacityResourceSample?.availableWorkspaceBytes ?? this.workspaceAvailableBytes;
|
|
632
|
+
const memoryAdmission = buildMemoryAdmissionDiagnostics({
|
|
633
|
+
sampledAt,
|
|
634
|
+
totalMemoryBytes,
|
|
635
|
+
rawAvailableMemoryBytes,
|
|
636
|
+
stabilizedAvailableMemoryBytes: sampledAvailableMemoryBytes,
|
|
637
|
+
controlPlaneMemoryBytes: process.memoryUsage().rss,
|
|
638
|
+
reserveMemoryBytes: hostReserveBytes,
|
|
639
|
+
committedMemoryBytes,
|
|
640
|
+
pendingCommitmentMemoryBytes: pendingReservationMemoryBytes,
|
|
641
|
+
});
|
|
642
|
+
const availableMemoryBytes = memoryAdmission.availableForAdmissionBytes;
|
|
643
|
+
const availableCpuMillis = Math.max(0, totalCpuMillis - cpuReserveMillis - activeReservationCpuMillis);
|
|
644
|
+
const availableWorkspaceBytes = Math.max(0, sampledWorkspaceBytes - workspaceReserveBytes - activeReservationWorkspaceBytes);
|
|
645
|
+
const slotAvailability = Math.max(0, hardMaxAttempts - this.capacityReservations.size);
|
|
646
|
+
// Capability snapshots advertise whether any supported attempt can fit.
|
|
647
|
+
// The queue/admission path still checks the exact project-derived request.
|
|
648
|
+
const minimumRequest = minimumSupportedHostResourceRequest();
|
|
649
|
+
const resourceAvailability = Math.min(resourceSlots(availableMemoryBytes, minimumRequest.memoryBytes), resourceSlots(availableCpuMillis, minimumRequest.cpuMillis), resourceSlots(availableWorkspaceBytes, minimumRequest.workspaceBytes));
|
|
650
|
+
const availableAttempts = Math.max(0, Math.min(slotAvailability, resourceAvailability));
|
|
651
|
+
const unavailableReason = slotAvailability <= 0
|
|
652
|
+
? `Host attempt capacity is full (${this.capacityReservations.size}/${hardMaxAttempts}).`
|
|
653
|
+
: availableMemoryBytes < minimumRequest.memoryBytes
|
|
654
|
+
? "Host memory is below the admission reserve."
|
|
655
|
+
: availableCpuMillis < minimumRequest.cpuMillis
|
|
656
|
+
? "Host CPU capacity is below the admission reserve."
|
|
657
|
+
: availableWorkspaceBytes < minimumRequest.workspaceBytes
|
|
658
|
+
? "Host workspace capacity is below the admission reserve."
|
|
659
|
+
: null;
|
|
660
|
+
return {
|
|
661
|
+
hardMaxAttempts,
|
|
662
|
+
effectiveMaxAttempts: this.capacityReservations.size + availableAttempts,
|
|
663
|
+
availableAttempts,
|
|
664
|
+
totalMemoryBytes,
|
|
665
|
+
availableMemoryBytes,
|
|
666
|
+
hostReserveBytes,
|
|
667
|
+
availableCpuMillis,
|
|
668
|
+
availableWorkspaceBytes,
|
|
669
|
+
activeReservationMemoryBytes,
|
|
670
|
+
memoryAdmission,
|
|
671
|
+
unavailableCode: unavailableReason ? "capacity_unavailable" : null,
|
|
672
|
+
unavailableReason,
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
async refreshWorkspaceCapacity() {
|
|
676
|
+
if (this.capacityResourceSample)
|
|
677
|
+
return;
|
|
678
|
+
try {
|
|
679
|
+
await fs.mkdir(this.stateRoot, { recursive: true });
|
|
680
|
+
const stats = await fs.statfs(this.stateRoot);
|
|
681
|
+
this.workspaceAvailableBytes = Math.max(0, stats.bavail * stats.bsize);
|
|
682
|
+
}
|
|
683
|
+
catch {
|
|
684
|
+
// Keep the last trustworthy sample. Memory/CPU and the hard ceiling still
|
|
685
|
+
// protect admission when the filesystem cannot be sampled temporarily.
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
releaseHostCapacity(dispatchAttemptId, fencingToken) {
|
|
689
|
+
const reservation = this.capacityReservations.get(dispatchAttemptId);
|
|
690
|
+
if (!reservation || reservation.owner.fencingToken !== fencingToken)
|
|
691
|
+
return;
|
|
692
|
+
this.capacityReservations.delete(dispatchAttemptId);
|
|
693
|
+
this.drainAdmissionWaiters();
|
|
694
|
+
}
|
|
695
|
+
drainCapacityWaiters() {
|
|
696
|
+
for (const waiter of this.capacityWaitersForScan()) {
|
|
697
|
+
if (!this.capacityWaiters.includes(waiter))
|
|
698
|
+
continue;
|
|
699
|
+
if (waiter.signal?.aborted) {
|
|
700
|
+
this.detachCapacityWaiter(waiter);
|
|
701
|
+
this.clearPendingRenewal(waiter.owner);
|
|
702
|
+
waiter.reject(cancellationError(waiter.signal));
|
|
703
|
+
continue;
|
|
704
|
+
}
|
|
705
|
+
if (admissionExpired(waiter.expiresAt)) {
|
|
706
|
+
this.detachCapacityWaiter(waiter);
|
|
707
|
+
this.clearPendingRenewal(waiter.owner);
|
|
708
|
+
waiter.reject(new HostRuntimeAdmissionExpiredError());
|
|
709
|
+
continue;
|
|
710
|
+
}
|
|
711
|
+
const impossibleReason = this.hostCapacityImpossibleReason(waiter.resources);
|
|
712
|
+
if (impossibleReason) {
|
|
713
|
+
this.detachCapacityWaiter(waiter);
|
|
714
|
+
this.clearPendingRenewal(waiter.owner);
|
|
715
|
+
waiter.reject(new HostRuntimeCapacityRequestImpossibleError(impossibleReason));
|
|
716
|
+
continue;
|
|
717
|
+
}
|
|
718
|
+
if (!this.hostCapacityAvailable(waiter.resources))
|
|
719
|
+
continue;
|
|
720
|
+
this.detachCapacityWaiter(waiter);
|
|
721
|
+
this.capacityReservations.set(waiter.owner.dispatchAttemptId, {
|
|
722
|
+
owner: waiter.owner,
|
|
723
|
+
resources: waiter.resources,
|
|
724
|
+
state: "pending",
|
|
725
|
+
});
|
|
726
|
+
waiter.resolve();
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
capacityWaitersForScan() {
|
|
730
|
+
const head = this.capacityWaiters[0];
|
|
731
|
+
if (!head) {
|
|
732
|
+
this.capacityWaiterScanCursor = 0;
|
|
733
|
+
return [];
|
|
734
|
+
}
|
|
735
|
+
const scanCount = Math.min(hostCapacityWaiterScanLimit, this.capacityWaiters.length);
|
|
736
|
+
if (scanCount === this.capacityWaiters.length) {
|
|
737
|
+
this.capacityWaiterScanCursor = 0;
|
|
738
|
+
return this.capacityWaiters.slice();
|
|
739
|
+
}
|
|
740
|
+
// The head always gets the first opportunity, while a rotating bounded
|
|
741
|
+
// window prevents an unfit renewed head (or a very deep queue) from
|
|
742
|
+
// indefinitely hiding a later request that fits current capacity.
|
|
743
|
+
const laterCount = this.capacityWaiters.length - 1;
|
|
744
|
+
const laterScanCount = scanCount - 1;
|
|
745
|
+
const start = this.capacityWaiterScanCursor % laterCount;
|
|
746
|
+
const result = [head];
|
|
747
|
+
for (let offset = 0; offset < laterScanCount; offset += 1) {
|
|
748
|
+
result.push(this.capacityWaiters[1 + ((start + offset) % laterCount)]);
|
|
749
|
+
}
|
|
750
|
+
this.capacityWaiterScanCursor = (start + laterScanCount) % laterCount;
|
|
751
|
+
return result;
|
|
752
|
+
}
|
|
753
|
+
detachCapacityWaiter(waiter) {
|
|
754
|
+
const index = this.capacityWaiters.indexOf(waiter);
|
|
755
|
+
if (index < 0)
|
|
756
|
+
return false;
|
|
757
|
+
this.capacityWaiters.splice(index, 1);
|
|
758
|
+
clearAdmissionDeadline(waiter);
|
|
759
|
+
clearCapacityRecheck(waiter);
|
|
760
|
+
waiter.signal?.removeEventListener("abort", waiter.abort);
|
|
761
|
+
if (this.capacityWaiters.length === 0)
|
|
762
|
+
this.capacityWaiterScanCursor = 0;
|
|
763
|
+
return true;
|
|
764
|
+
}
|
|
765
|
+
async reserveSingletonKeys(keys, owner, expiresAt, signal, priority = "foreground") {
|
|
766
|
+
const owned = keys.every(key => sameSingletonOwner(this.singletonOwners.get(key), owner));
|
|
767
|
+
if (owned)
|
|
768
|
+
return keys;
|
|
769
|
+
const staleFence = [...this.singletonOwners.values()].find(existing => existing.dispatchAttemptId === owner.dispatchAttemptId
|
|
770
|
+
&& existing.fencingToken !== owner.fencingToken);
|
|
771
|
+
if (staleFence) {
|
|
772
|
+
throw new Error("host_runtime_singleton_conflict: dispatch attempt already holds the singleton under a different fence.");
|
|
773
|
+
}
|
|
774
|
+
if (signal?.aborted)
|
|
775
|
+
throw cancellationError(signal);
|
|
776
|
+
throwIfAdmissionExpired(expiresAt);
|
|
777
|
+
if (this.singletonKeysAvailable(keys)) {
|
|
778
|
+
this.assignSingletonKeys(keys, owner);
|
|
779
|
+
return keys;
|
|
780
|
+
}
|
|
781
|
+
return new Promise((resolve, reject) => {
|
|
782
|
+
const waiter = {
|
|
783
|
+
owner,
|
|
784
|
+
keys,
|
|
785
|
+
priority,
|
|
786
|
+
resolve,
|
|
787
|
+
reject,
|
|
788
|
+
signal,
|
|
789
|
+
expiresAt,
|
|
790
|
+
deadlineTimer: null,
|
|
791
|
+
abort: () => {
|
|
792
|
+
const index = this.singletonWaiters.indexOf(waiter);
|
|
793
|
+
if (index >= 0)
|
|
794
|
+
this.singletonWaiters.splice(index, 1);
|
|
795
|
+
clearAdmissionDeadline(waiter);
|
|
796
|
+
this.clearPendingRenewal(owner);
|
|
797
|
+
reject(cancellationError(signal));
|
|
798
|
+
this.drainAdmissionWaiters();
|
|
799
|
+
},
|
|
800
|
+
expire: () => {
|
|
801
|
+
const index = this.singletonWaiters.indexOf(waiter);
|
|
802
|
+
if (index < 0)
|
|
803
|
+
return;
|
|
804
|
+
this.singletonWaiters.splice(index, 1);
|
|
805
|
+
clearAdmissionDeadline(waiter);
|
|
806
|
+
waiter.signal?.removeEventListener("abort", waiter.abort);
|
|
807
|
+
this.clearPendingRenewal(owner);
|
|
808
|
+
reject(new HostRuntimeAdmissionExpiredError());
|
|
809
|
+
this.drainAdmissionWaiters();
|
|
810
|
+
},
|
|
811
|
+
};
|
|
812
|
+
enqueueAdmissionWaiter(this.singletonWaiters, waiter);
|
|
813
|
+
signal?.addEventListener("abort", waiter.abort, { once: true });
|
|
814
|
+
waiter.deadlineTimer = scheduleAdmissionDeadline(waiter.expiresAt, waiter.expire);
|
|
815
|
+
this.drainAdmissionWaiters();
|
|
816
|
+
});
|
|
817
|
+
}
|
|
818
|
+
async reserveParallelProject(key, owner, expiresAt, signal, priority = "foreground") {
|
|
819
|
+
if (this.parallelProjectOwned(key, owner))
|
|
820
|
+
return;
|
|
821
|
+
const staleFence = [...(this.parallelProjectOwners.get(key)?.values() ?? [])]
|
|
822
|
+
.find(existing => existing.dispatchAttemptId === owner.dispatchAttemptId
|
|
823
|
+
&& existing.fencingToken !== owner.fencingToken);
|
|
824
|
+
if (staleFence) {
|
|
825
|
+
throw new Error("host_runtime_parallel_conflict: dispatch attempt already holds shared admission under a different fence.");
|
|
826
|
+
}
|
|
827
|
+
if (signal?.aborted)
|
|
828
|
+
throw cancellationError(signal);
|
|
829
|
+
throwIfAdmissionExpired(expiresAt);
|
|
830
|
+
if (this.parallelProjectAvailable(key, priority)) {
|
|
831
|
+
this.assignParallelProject(key, owner);
|
|
832
|
+
return;
|
|
833
|
+
}
|
|
834
|
+
await new Promise((resolve, reject) => {
|
|
835
|
+
const waiter = {
|
|
836
|
+
owner,
|
|
837
|
+
key,
|
|
838
|
+
priority,
|
|
839
|
+
resolve,
|
|
840
|
+
reject,
|
|
841
|
+
signal,
|
|
842
|
+
expiresAt,
|
|
843
|
+
deadlineTimer: null,
|
|
844
|
+
abort: () => {
|
|
845
|
+
const index = this.parallelProjectWaiters.indexOf(waiter);
|
|
846
|
+
if (index >= 0)
|
|
847
|
+
this.parallelProjectWaiters.splice(index, 1);
|
|
848
|
+
clearAdmissionDeadline(waiter);
|
|
849
|
+
this.clearPendingRenewal(owner);
|
|
850
|
+
reject(cancellationError(signal));
|
|
851
|
+
this.drainAdmissionWaiters();
|
|
852
|
+
},
|
|
853
|
+
expire: () => {
|
|
854
|
+
const index = this.parallelProjectWaiters.indexOf(waiter);
|
|
855
|
+
if (index < 0)
|
|
856
|
+
return;
|
|
857
|
+
this.parallelProjectWaiters.splice(index, 1);
|
|
858
|
+
clearAdmissionDeadline(waiter);
|
|
859
|
+
waiter.signal?.removeEventListener("abort", waiter.abort);
|
|
860
|
+
this.clearPendingRenewal(owner);
|
|
861
|
+
reject(new HostRuntimeAdmissionExpiredError());
|
|
862
|
+
this.drainAdmissionWaiters();
|
|
863
|
+
},
|
|
864
|
+
};
|
|
865
|
+
enqueueAdmissionWaiter(this.parallelProjectWaiters, waiter);
|
|
866
|
+
signal?.addEventListener("abort", waiter.abort, { once: true });
|
|
867
|
+
waiter.deadlineTimer = scheduleAdmissionDeadline(waiter.expiresAt, waiter.expire);
|
|
868
|
+
this.drainAdmissionWaiters();
|
|
869
|
+
});
|
|
870
|
+
}
|
|
871
|
+
async upgradeParallelProjectToSingleton(keys, parallelProjectKey, owner, expiresAt, signal, priority = "foreground") {
|
|
872
|
+
if (!this.parallelProjectOwned(parallelProjectKey, owner)) {
|
|
873
|
+
throw new Error("host_runtime_parallel_unreserved: matching shared project admission is required before serialization.");
|
|
874
|
+
}
|
|
875
|
+
if (signal?.aborted)
|
|
876
|
+
throw cancellationError(signal);
|
|
877
|
+
throwIfAdmissionExpired(expiresAt);
|
|
878
|
+
return await new Promise((resolve, reject) => {
|
|
879
|
+
const waiter = {
|
|
880
|
+
owner,
|
|
881
|
+
keys,
|
|
882
|
+
priority,
|
|
883
|
+
resolve,
|
|
884
|
+
reject,
|
|
885
|
+
signal,
|
|
886
|
+
expiresAt,
|
|
887
|
+
deadlineTimer: null,
|
|
888
|
+
abort: () => {
|
|
889
|
+
const index = this.singletonWaiters.indexOf(waiter);
|
|
890
|
+
if (index >= 0)
|
|
891
|
+
this.singletonWaiters.splice(index, 1);
|
|
892
|
+
clearAdmissionDeadline(waiter);
|
|
893
|
+
this.clearPendingRenewal(owner);
|
|
894
|
+
reject(cancellationError(signal));
|
|
895
|
+
this.drainAdmissionWaiters();
|
|
896
|
+
},
|
|
897
|
+
expire: () => {
|
|
898
|
+
const index = this.singletonWaiters.indexOf(waiter);
|
|
899
|
+
if (index < 0)
|
|
900
|
+
return;
|
|
901
|
+
this.singletonWaiters.splice(index, 1);
|
|
902
|
+
clearAdmissionDeadline(waiter);
|
|
903
|
+
waiter.signal?.removeEventListener("abort", waiter.abort);
|
|
904
|
+
this.clearPendingRenewal(owner);
|
|
905
|
+
reject(new HostRuntimeAdmissionExpiredError());
|
|
906
|
+
this.drainAdmissionWaiters();
|
|
907
|
+
},
|
|
908
|
+
};
|
|
909
|
+
// Queue the exclusive claim before relinquishing the shared claim. This
|
|
910
|
+
// makes the promotion downgrade atomic from the broker's perspective and
|
|
911
|
+
// prevents a background readiness probe from jumping ahead in between.
|
|
912
|
+
enqueueAdmissionWaiter(this.singletonWaiters, waiter);
|
|
913
|
+
signal?.addEventListener("abort", waiter.abort, { once: true });
|
|
914
|
+
waiter.deadlineTimer = scheduleAdmissionDeadline(waiter.expiresAt, waiter.expire);
|
|
915
|
+
this.releaseParallelProjectNoDrain(parallelProjectKey, owner);
|
|
916
|
+
this.drainAdmissionWaiters();
|
|
917
|
+
});
|
|
918
|
+
}
|
|
919
|
+
async start(dispatch, worktreePath, signal, onAdmissionCheckpoint) {
|
|
920
|
+
const sandbox = dispatch.sandbox;
|
|
921
|
+
if (!sandbox || sandbox.executionMode !== "host") {
|
|
922
|
+
throw new Error("host_runtime_lease_invalid: managed host sandbox context is required.");
|
|
923
|
+
}
|
|
924
|
+
const wasPrepared = this.preparedReadiness.has(sandbox.dispatchAttemptId);
|
|
925
|
+
const preparedProof = wasPrepared
|
|
926
|
+
? await this.preparedReadiness.verify(dispatch, worktreePath, onAdmissionCheckpoint)
|
|
927
|
+
: undefined;
|
|
928
|
+
if (wasPrepared) {
|
|
929
|
+
signal?.throwIfAborted();
|
|
930
|
+
const admission = this.hostResourceSnapshot().memoryAdmission;
|
|
931
|
+
const requestedMemoryBytes = normalizedHostResourceRequest(sandbox.requestedResources).memoryBytes;
|
|
932
|
+
await onAdmissionCheckpoint?.({
|
|
933
|
+
code: "host_runtime_prepared_admission_waiting",
|
|
934
|
+
message: `Prepared runtime verification passed. Waiting for host admission before agent startup: ${formatBytes(requestedMemoryBytes)} requested, ${formatBytes(admission.availableForAdmissionBytes)} currently available under the host reserve.`,
|
|
935
|
+
expiresAt: dispatch.lease.expiresAt,
|
|
936
|
+
});
|
|
937
|
+
await this.acquire(dispatch, signal);
|
|
938
|
+
await onAdmissionCheckpoint?.({
|
|
939
|
+
code: "host_runtime_prepared_admission_acquired",
|
|
940
|
+
message: "Prepared runtime acquired host admission; agent startup is continuing.",
|
|
941
|
+
expiresAt: dispatch.lease.expiresAt,
|
|
942
|
+
});
|
|
943
|
+
}
|
|
944
|
+
const existing = this.active.get(sandbox.dispatchAttemptId);
|
|
945
|
+
if (existing) {
|
|
946
|
+
if (existing.lease.fencingToken !== dispatch.lease.fencingToken) {
|
|
947
|
+
throw new Error("host_runtime_lease_conflict: an active host lease has a different fence.");
|
|
948
|
+
}
|
|
949
|
+
return {
|
|
950
|
+
lease: existing.lease,
|
|
951
|
+
environment: hostRuntimeEnvironment(dispatch.session.id, existing.lease, existing.runtimeContract, existing.executionClass, existing.databaseCapability),
|
|
952
|
+
runtimeContract: existing.runtimeContract,
|
|
953
|
+
executionClass: existing.executionClass,
|
|
954
|
+
};
|
|
955
|
+
}
|
|
956
|
+
const admission = this.admissions.get(sandbox.dispatchAttemptId);
|
|
957
|
+
const owner = { dispatchAttemptId: sandbox.dispatchAttemptId, fencingToken: dispatch.lease.fencingToken };
|
|
958
|
+
if (!admission || admission.fencingToken !== owner.fencingToken) {
|
|
959
|
+
throw new Error("host_runtime_singleton_unreserved: managed host admission is required before start.");
|
|
960
|
+
}
|
|
961
|
+
const attemptHex = uuidHex(sandbox.dispatchAttemptId, "dispatch attempt");
|
|
962
|
+
const compactAttemptHex = compactHostAttemptId(sandbox.dispatchAttemptId);
|
|
963
|
+
const normalizedWorktreePath = await resolveExistingDirectoryPath(worktreePath);
|
|
964
|
+
const attemptRoot = path.join(this.executionRoot, "a", compactAttemptHex);
|
|
965
|
+
const temporaryPath = path.join(attemptRoot, "t");
|
|
966
|
+
const logPath = path.join(attemptRoot, "logs");
|
|
967
|
+
const cachePath = path.join(attemptRoot, "c");
|
|
968
|
+
const browserProfilePath = path.join(attemptRoot, "b");
|
|
969
|
+
const testOutputPath = path.join(attemptRoot, "test-output");
|
|
970
|
+
const processSupervisorMetadataPath = path.join(logPath, "attempt-process-supervisor.json");
|
|
971
|
+
const processSupervisorId = `host-${attemptHex}`;
|
|
972
|
+
const renewedExpiry = this.pendingRenewals.get(sandbox.dispatchAttemptId);
|
|
973
|
+
const expiresAt = renewedExpiry?.fencingToken === dispatch.lease.fencingToken
|
|
974
|
+
? renewedExpiry.expiresAt
|
|
975
|
+
: dispatch.lease.expiresAt;
|
|
976
|
+
let processSupervisor = null;
|
|
977
|
+
let attemptRootIdentity = null;
|
|
978
|
+
try {
|
|
979
|
+
const runtimeContract = await loadHostRuntimeContract(normalizedWorktreePath);
|
|
980
|
+
// Decision 0013 accept-time recheck. Readiness probes are exempt: they are how the
|
|
981
|
+
// API learns the requirements in the first place.
|
|
982
|
+
const unmetRequirements = dispatch.workItem.kind === "runtime_readiness"
|
|
983
|
+
? []
|
|
984
|
+
: this.requirementsCheck?.(runtimeContract.contract.requires) ?? [];
|
|
985
|
+
if (unmetRequirements.length > 0) {
|
|
986
|
+
// Typed, so the API receives the retryable code and re-places the work (not bridge.execution_failed).
|
|
987
|
+
throw new ForgeFailureError("placement_requirements_unmet", `placement_requirements_unmet: this host does not meet the project's requirements: ${unmetRequirements.join("; ")}.`);
|
|
988
|
+
}
|
|
989
|
+
if (runtimeContract.contract.runtime.hostConcurrency === "disabled") {
|
|
990
|
+
throw new Error("host_runtime_disabled: project runtime configuration requires Docker execution.");
|
|
991
|
+
}
|
|
992
|
+
if (wasPrepared && !preparedProof && admission.executionClass === "managed_runtime"
|
|
993
|
+
&& hostRuntimeParallelEligible(runtimeContract)) {
|
|
994
|
+
throw new Error("host_runtime_prepared_source_changed: runtime became parallel-eligible after preparation; a new foreground proof is required.");
|
|
995
|
+
}
|
|
996
|
+
const runtimeContractFingerprint = hostRuntimeContractFingerprint(runtimeContract);
|
|
997
|
+
const inputCommitSha = preparedProof?.inputCommitSha
|
|
998
|
+
?? await resolveWorktreeCommitSha(normalizedWorktreePath, sandbox.inputCommitSha);
|
|
999
|
+
if (preparedProof && (runtimeContractFingerprint !== preparedProof.runtimeContractFingerprint
|
|
1000
|
+
|| JSON.stringify(preparedProof) !== JSON.stringify(await preparedRuntimeIdentity(normalizedWorktreePath, signal)))) {
|
|
1001
|
+
throw new Error("host_runtime_prepared_source_changed: source changed after its foreground proof; agent was not started.");
|
|
1002
|
+
}
|
|
1003
|
+
const promotion = admission.executionClass === "managed_runtime"
|
|
1004
|
+
? await this.promotionStore.load(dispatch.repo.id, preparedProof ?? { runtimeContractFingerprint, inputCommitSha })
|
|
1005
|
+
: null;
|
|
1006
|
+
const promotionMatches = hostRuntimeParallelEligible(runtimeContract)
|
|
1007
|
+
&& promotion?.runtimeContractFingerprint === runtimeContractFingerprint
|
|
1008
|
+
&& promotion.inputCommitSha === inputCommitSha;
|
|
1009
|
+
if (admission.executionClass === "managed_runtime" && admission.keys.length === 0 && !promotionMatches) {
|
|
1010
|
+
const projectKeys = hostRuntimeSingletonKeys(dispatch);
|
|
1011
|
+
const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
|
|
1012
|
+
? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
|
|
1013
|
+
: dispatch.lease.expiresAt;
|
|
1014
|
+
const parallelProjectKey = admission.parallelProjectKey;
|
|
1015
|
+
admission.parallelProjectKey = null;
|
|
1016
|
+
const capacityReservation = this.capacityReservations.get(owner.dispatchAttemptId);
|
|
1017
|
+
if (capacityReservation && !sameSingletonOwner(capacityReservation.owner, owner)) {
|
|
1018
|
+
throw new Error("host_runtime_capacity_conflict: dispatch attempt holds capacity under a different fence.");
|
|
1019
|
+
}
|
|
1020
|
+
const serializedAdmission = parallelProjectKey
|
|
1021
|
+
? this.upgradeParallelProjectToSingleton(projectKeys, parallelProjectKey, owner, expiresAt, signal, admission.priority)
|
|
1022
|
+
: this.reserveSingletonKeys(projectKeys, owner, expiresAt, signal, admission.priority);
|
|
1023
|
+
// A sibling can already hold the same provisional shared project claim
|
|
1024
|
+
// while waiting for this attempt's host-capacity slot. Retaining capacity
|
|
1025
|
+
// while waiting for that sibling to release its shared claim creates a
|
|
1026
|
+
// cycle: exclusive waits on shared, shared waits on capacity. Relinquish
|
|
1027
|
+
// the capacity slot only after the exclusive waiter is queued, then
|
|
1028
|
+
// reacquire it after serialization is granted.
|
|
1029
|
+
if (capacityReservation) {
|
|
1030
|
+
this.releaseHostCapacity(owner.dispatchAttemptId, owner.fencingToken);
|
|
1031
|
+
}
|
|
1032
|
+
// The checkpoint is allowed to do I/O. Observe an early admission
|
|
1033
|
+
// failure now so a slow acknowledgement cannot create an unhandled
|
|
1034
|
+
// rejection before the operational promise is awaited below.
|
|
1035
|
+
void serializedAdmission.catch(() => undefined);
|
|
1036
|
+
// Begin the operational downgrade before publishing telemetry. A lost
|
|
1037
|
+
// callback acknowledgement must not leave the attempt holding its old
|
|
1038
|
+
// shared admission while every recovery probe waits behind it.
|
|
1039
|
+
await onAdmissionCheckpoint?.({
|
|
1040
|
+
code: "host_runtime_serial_admission_waiting",
|
|
1041
|
+
message: "The prepared runtime contract no longer matches the parallel-readiness proof. Waiting for foreground-priority serialized admission before launch.",
|
|
1042
|
+
expiresAt,
|
|
1043
|
+
});
|
|
1044
|
+
admission.keys = await serializedAdmission;
|
|
1045
|
+
while (admission.keys.length === 0) {
|
|
1046
|
+
const promoted = this.knownPromotions.get(dispatch.repo.id);
|
|
1047
|
+
if (!promoted) {
|
|
1048
|
+
throw new Error("host_runtime_parallel_promotion_missing: shared admission requires matching promotion evidence.");
|
|
1049
|
+
}
|
|
1050
|
+
const matching = await this.promotionStore.load(dispatch.repo.id, preparedProof ?? { runtimeContractFingerprint, inputCommitSha });
|
|
1051
|
+
if (!matching) {
|
|
1052
|
+
// Drop obsolete proof before asking for exclusive admission; otherwise
|
|
1053
|
+
// the queue can grant the same stale shared promotion indefinitely.
|
|
1054
|
+
this.releaseParallelProjectNoDrain(projectKeys[0], owner);
|
|
1055
|
+
admission.keys = await this.reserveSingletonKeys(projectKeys, owner, expiresAt, signal, admission.priority);
|
|
1056
|
+
continue;
|
|
1057
|
+
}
|
|
1058
|
+
admission.parallelProjectKey = projectKeys[0] ?? null;
|
|
1059
|
+
admission.provisionalPromotionFingerprint = promoted.runtimeContractFingerprint;
|
|
1060
|
+
break;
|
|
1061
|
+
}
|
|
1062
|
+
// Do not hold a capacity slot while a stale shared re-grant is still
|
|
1063
|
+
// being converted to exclusive admission.
|
|
1064
|
+
if (capacityReservation) {
|
|
1065
|
+
await this.reserveHostCapacity(owner, capacityReservation.resources, expiresAt, signal, admission.priority);
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
const declaredSingletonKeys = runtimeContract.contract.runtime.singletonResources
|
|
1069
|
+
.map(hostRuntimeDeclaredSingletonKey);
|
|
1070
|
+
const missingSingletonKeys = declaredSingletonKeys
|
|
1071
|
+
.filter(key => !admission.keys.includes(key));
|
|
1072
|
+
if (missingSingletonKeys.length > 0) {
|
|
1073
|
+
const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
|
|
1074
|
+
? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
|
|
1075
|
+
: dispatch.lease.expiresAt;
|
|
1076
|
+
const reservedSingletonKeys = await this.reserveSingletonKeys(missingSingletonKeys, owner, expiresAt, signal, admission.priority);
|
|
1077
|
+
admission.keys = [...admission.keys, ...reservedSingletonKeys]
|
|
1078
|
+
.sort((left, right) => left.localeCompare(right));
|
|
1079
|
+
}
|
|
1080
|
+
const singletonKeys = admission.keys;
|
|
1081
|
+
if (!singletonKeys.every(key => sameSingletonOwner(this.singletonOwners.get(key), owner))) {
|
|
1082
|
+
throw new Error("host_runtime_singleton_unreserved: managed host singleton ownership is required before start.");
|
|
1083
|
+
}
|
|
1084
|
+
if (admission.parallelProjectKey && !this.parallelProjectOwned(admission.parallelProjectKey, owner)) {
|
|
1085
|
+
throw new Error("host_runtime_parallel_unreserved: matching shared project admission is required before start.");
|
|
1086
|
+
}
|
|
1087
|
+
await createCanonicalDirectory(attemptRoot);
|
|
1088
|
+
attemptRootIdentity = (await assertCanonicalDirectory(attemptRoot));
|
|
1089
|
+
await Promise.all([
|
|
1090
|
+
createCanonicalDirectory(temporaryPath),
|
|
1091
|
+
createCanonicalDirectory(logPath),
|
|
1092
|
+
createCanonicalDirectory(cachePath),
|
|
1093
|
+
createCanonicalDirectory(browserProfilePath),
|
|
1094
|
+
createCanonicalDirectory(testOutputPath),
|
|
1095
|
+
]);
|
|
1096
|
+
await assertHostAttemptRootIdentity(attemptRoot, attemptRootIdentity);
|
|
1097
|
+
await resetGeneratedOutputs(normalizedWorktreePath, testOutputPath);
|
|
1098
|
+
let lease = createRuntimeIsolationLease({
|
|
1099
|
+
leaseId: sandbox.executionLeaseId,
|
|
1100
|
+
dispatchAttemptId: sandbox.dispatchAttemptId,
|
|
1101
|
+
executionLeaseId: sandbox.executionLeaseId,
|
|
1102
|
+
fencingToken: dispatch.lease.fencingToken,
|
|
1103
|
+
runnerId: dispatch.execution.runnerId ?? "",
|
|
1104
|
+
runnerInstanceId: sandbox.runnerInstanceId,
|
|
1105
|
+
worktreeKey: dispatch.lease.worktreeKey,
|
|
1106
|
+
worktreePath: normalizedWorktreePath,
|
|
1107
|
+
mode: "host",
|
|
1108
|
+
expiresAt,
|
|
1109
|
+
resources: {
|
|
1110
|
+
memoryReservationBytes: 0,
|
|
1111
|
+
cpuMillis: 0,
|
|
1112
|
+
pids: 0,
|
|
1113
|
+
ports: [],
|
|
1114
|
+
paths: [
|
|
1115
|
+
{ path: normalizedWorktreePath, role: "worktree" },
|
|
1116
|
+
{ path: temporaryPath, role: "temporary" },
|
|
1117
|
+
{ path: logPath, role: "logs" },
|
|
1118
|
+
{ path: cachePath, role: "cache" },
|
|
1119
|
+
{ path: browserProfilePath, role: "browser_profile" },
|
|
1120
|
+
{ path: testOutputPath, role: "test_output" },
|
|
1121
|
+
{ path: processSupervisorMetadataPath, role: "process_supervisor_metadata" },
|
|
1122
|
+
],
|
|
1123
|
+
processSupervisorId,
|
|
1124
|
+
dockerResources: [],
|
|
1125
|
+
singletonKeys,
|
|
1126
|
+
},
|
|
1127
|
+
});
|
|
1128
|
+
await this.writeLedger(lease, undefined, attemptRootIdentity);
|
|
1129
|
+
lease = transitionRuntimeIsolationLease(lease, "starting");
|
|
1130
|
+
await this.writeLedger(lease, undefined, attemptRootIdentity);
|
|
1131
|
+
lease = transitionRuntimeIsolationLease(lease, "active");
|
|
1132
|
+
await this.writeLedger(lease, undefined, attemptRootIdentity);
|
|
1133
|
+
processSupervisor = this.processSupervisors.register({
|
|
1134
|
+
processSupervisorId,
|
|
1135
|
+
dispatchAttemptId: lease.dispatchAttemptId,
|
|
1136
|
+
executionLeaseId: lease.executionLeaseId,
|
|
1137
|
+
fencingToken: lease.fencingToken,
|
|
1138
|
+
logDirectory: logPath,
|
|
1139
|
+
}, this.processRunner, { signal });
|
|
1140
|
+
this.active.set(sandbox.dispatchAttemptId, {
|
|
1141
|
+
lease,
|
|
1142
|
+
repoId: dispatch.repo.id,
|
|
1143
|
+
sessionId: dispatch.session.id,
|
|
1144
|
+
attemptRoot,
|
|
1145
|
+
attemptRootIdentity,
|
|
1146
|
+
runtimeContract,
|
|
1147
|
+
runtimeContractFingerprint,
|
|
1148
|
+
inputCommitSha,
|
|
1149
|
+
executionClass: admission.executionClass,
|
|
1150
|
+
parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract) && dispatch.cycleRun.phase !== "prepared_readiness",
|
|
1151
|
+
processSupervisor,
|
|
1152
|
+
adapterCleanups: [],
|
|
1153
|
+
adapterCleanupsByPort: new Map(),
|
|
1154
|
+
restartingConfiguredProject: false,
|
|
1155
|
+
pendingAdapterLaunches: new Map(),
|
|
1156
|
+
runtimeResourcesReleased: false,
|
|
1157
|
+
releasing: false,
|
|
1158
|
+
});
|
|
1159
|
+
this.pendingRenewals.delete(sandbox.dispatchAttemptId);
|
|
1160
|
+
return {
|
|
1161
|
+
lease,
|
|
1162
|
+
environment: hostRuntimeEnvironment(dispatch.session.id, lease, runtimeContract, admission.executionClass),
|
|
1163
|
+
runtimeContract,
|
|
1164
|
+
executionClass: admission.executionClass,
|
|
1165
|
+
};
|
|
1166
|
+
}
|
|
1167
|
+
catch (error) {
|
|
1168
|
+
this.pendingRenewals.delete(sandbox.dispatchAttemptId);
|
|
1169
|
+
if (processSupervisor) {
|
|
1170
|
+
await processSupervisor.stopAll(dispatch.lease.fencingToken, "Host runtime start rolled back.").catch(() => undefined);
|
|
1171
|
+
this.processSupervisors.unregister(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
|
|
1172
|
+
}
|
|
1173
|
+
const attemptRemoved = await retainHostDiagnostics(this.stateRoot, attemptRoot, sandbox.dispatchAttemptId, attemptRootIdentity, this.executionRoot).then(async () => {
|
|
1174
|
+
await removeHostAttemptRoot(attemptRoot);
|
|
1175
|
+
return true;
|
|
1176
|
+
}).catch(() => false); // A retention failure preserves the original evidence and ownership ledger.
|
|
1177
|
+
if (attemptRemoved) {
|
|
1178
|
+
await fs.rm(this.ledgerPath(sandbox.dispatchAttemptId), { force: true }).catch(() => undefined);
|
|
1179
|
+
}
|
|
1180
|
+
this.releaseSingletonKeys(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
|
|
1181
|
+
this.releaseParallelProjects(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
|
|
1182
|
+
this.deleteAdmission(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
|
|
1183
|
+
throw error;
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
async updateLease(dispatchAttemptId, fencingToken, expiresAt) {
|
|
1187
|
+
try {
|
|
1188
|
+
uuidHex(dispatchAttemptId, "dispatch attempt");
|
|
1189
|
+
uuidHex(fencingToken, "fencing token");
|
|
1190
|
+
}
|
|
1191
|
+
catch {
|
|
1192
|
+
return;
|
|
1193
|
+
}
|
|
1194
|
+
await this.preparedReadiness.renew(dispatchAttemptId, fencingToken, expiresAt);
|
|
1195
|
+
const active = this.active.get(dispatchAttemptId);
|
|
1196
|
+
if (!active) {
|
|
1197
|
+
if (Number.isFinite(Date.parse(expiresAt))) {
|
|
1198
|
+
const pending = this.pendingRenewals.get(dispatchAttemptId);
|
|
1199
|
+
if (!pending
|
|
1200
|
+
|| pending.fencingToken !== fencingToken
|
|
1201
|
+
|| Date.parse(expiresAt) > Date.parse(pending.expiresAt)) {
|
|
1202
|
+
this.pendingRenewals.set(dispatchAttemptId, { fencingToken, expiresAt });
|
|
1203
|
+
}
|
|
1204
|
+
this.renewAdmissionWaiterDeadline(dispatchAttemptId, fencingToken, expiresAt);
|
|
1205
|
+
}
|
|
1206
|
+
return;
|
|
1207
|
+
}
|
|
1208
|
+
if (active.releasing || active.lease.state === "releasing" || active.lease.state === "released")
|
|
1209
|
+
return;
|
|
1210
|
+
const renewed = renewRuntimeIsolationLease(active.lease, fencingToken, expiresAt);
|
|
1211
|
+
if (!renewed)
|
|
1212
|
+
return;
|
|
1213
|
+
active.lease = renewed;
|
|
1214
|
+
await this.writeLedger(renewed);
|
|
1215
|
+
}
|
|
1216
|
+
async startConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
|
|
1217
|
+
return await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, true);
|
|
1218
|
+
}
|
|
1219
|
+
/**
|
|
1220
|
+
* Launches the configured project. Only the first launch, from the admitted commit's clean
|
|
1221
|
+
* source, may record parallel-safety proof: a restart serves the workspace after the provider
|
|
1222
|
+
* edited it, and a proof observed there would be stored under the admitted commit and could
|
|
1223
|
+
* move this or a later attempt at that commit into shared admission for source it never ran.
|
|
1224
|
+
*/
|
|
1225
|
+
async launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, promote) {
|
|
1226
|
+
const active = this.active.get(dispatchAttemptId);
|
|
1227
|
+
if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
|
|
1228
|
+
throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
|
|
1229
|
+
}
|
|
1230
|
+
if (active.executionClass === "analysis_only") {
|
|
1231
|
+
return {
|
|
1232
|
+
lease: active.lease,
|
|
1233
|
+
environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
|
|
1234
|
+
runtimeContract: active.runtimeContract,
|
|
1235
|
+
executionClass: active.executionClass,
|
|
1236
|
+
};
|
|
1237
|
+
}
|
|
1238
|
+
const configuredPorts = active.runtimeContract.contract.runtime.ports.filter((port) => port.launch !== null);
|
|
1239
|
+
if (configuredPorts.length === 0) {
|
|
1240
|
+
return {
|
|
1241
|
+
lease: active.lease,
|
|
1242
|
+
environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
|
|
1243
|
+
runtimeContract: active.runtimeContract,
|
|
1244
|
+
executionClass: active.executionClass,
|
|
1245
|
+
};
|
|
1246
|
+
}
|
|
1247
|
+
const playwrightConfig = active.runtimeContract.contract.runtime.playwright;
|
|
1248
|
+
// A host without the project's pinned browsers fails here, before any database,
|
|
1249
|
+
// build, launch, or promotion work that the attempt would otherwise waste.
|
|
1250
|
+
if (playwrightConfig)
|
|
1251
|
+
await this.playwrightAdapter.assertBrowserCacheReady(playwrightConfig, active.lease.worktreePath);
|
|
1252
|
+
const owner = hostPortOwner(active.lease);
|
|
1253
|
+
const logDirectory = active.lease.resources.paths.find(entry => entry.role === "logs")?.path;
|
|
1254
|
+
if (!logDirectory)
|
|
1255
|
+
throw new Error("host_runtime_project_invalid: attempt log directory is unavailable.");
|
|
1256
|
+
if (this.databaseBroker && !active.databaseCapability
|
|
1257
|
+
&& configuredPorts.some(port => /^dotnet(?:\.exe)?$/iu.test(path.basename(port.launch.command)))) {
|
|
1258
|
+
// An ASP.NET runtime may require an isolated database (Forge.Api refuses to start in a
|
|
1259
|
+
// managed host attempt without one). Issue it before the first launch. Release waits for
|
|
1260
|
+
// an in-flight provision, so a database issued during release is still dropped.
|
|
1261
|
+
const provision = this.databaseBroker.provision(dispatchAttemptId, fencingToken, signal)
|
|
1262
|
+
.then(capability => {
|
|
1263
|
+
active.databaseCapability = capability;
|
|
1264
|
+
return capability;
|
|
1265
|
+
});
|
|
1266
|
+
active.databaseProvision = provision;
|
|
1267
|
+
await provision;
|
|
1268
|
+
if (active.releasing) {
|
|
1269
|
+
throw new Error("host_runtime_project_unavailable: the host runtime lease was released during database provisioning.");
|
|
1270
|
+
}
|
|
1271
|
+
await onProjectCheckpoint?.({
|
|
1272
|
+
code: "host_runtime_database_provisioned",
|
|
1273
|
+
message: `Provisioned isolated attempt database ${active.databaseCapability.databaseName} on the native test cluster.`,
|
|
1274
|
+
data: { database: active.databaseCapability.databaseName },
|
|
1275
|
+
});
|
|
1276
|
+
}
|
|
1277
|
+
const apiMasterKey = attemptApiMasterKey(active);
|
|
1278
|
+
// Runtime output is persisted to attempt logs; the database login and master key it may print are redacted.
|
|
1279
|
+
const capabilitySecrets = [...attemptDatabaseCapabilitySecrets(active.databaseCapability?.connectionString), apiMasterKey];
|
|
1280
|
+
const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector, capabilitySecrets);
|
|
1281
|
+
for (const configuredPort of configuredPorts) {
|
|
1282
|
+
const workingDirectory = await containedWorkingDirectory(active.lease.worktreePath, configuredPort.launch.workingDirectory);
|
|
1283
|
+
const buildEnvironment = {
|
|
1284
|
+
...configuredPort.launch.environment,
|
|
1285
|
+
...hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
|
|
1286
|
+
};
|
|
1287
|
+
const prebuild = createAspNetRuntimePrebuildPlan({
|
|
1288
|
+
command: configuredPort.launch.command,
|
|
1289
|
+
args: configuredPort.launch.args,
|
|
1290
|
+
cwd: workingDirectory,
|
|
1291
|
+
worktreePath: active.lease.worktreePath,
|
|
1292
|
+
environment: buildEnvironment,
|
|
1293
|
+
inputCommitSha: active.inputCommitSha,
|
|
1294
|
+
runtimeContractFingerprint: active.runtimeContractFingerprint,
|
|
1295
|
+
});
|
|
1296
|
+
if (prebuild) {
|
|
1297
|
+
await onProjectCheckpoint?.({
|
|
1298
|
+
code: "host_runtime_build_started",
|
|
1299
|
+
message: `Preparing the ASP.NET runtime for commit ${active.inputCommitSha.slice(0, 12)} before binding its assigned port.`,
|
|
1300
|
+
data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath },
|
|
1301
|
+
});
|
|
1302
|
+
let hostLoadWaitMs = null;
|
|
1303
|
+
const build = await ensureAspNetRuntimePrebuilt(prebuild,
|
|
1304
|
+
// Only a real build (not a verified cache hit) takes a host load token.
|
|
1305
|
+
async (plan, buildSignal) => await runHostGovernedStep(this.hostLoadGovernor, {
|
|
1306
|
+
classification: aspNetPrebuildStepClass,
|
|
1307
|
+
label: prebuild.projectPath,
|
|
1308
|
+
dispatchAttemptId,
|
|
1309
|
+
priority: this.admissions.get(dispatchAttemptId)?.priority ?? "foreground",
|
|
1310
|
+
signal: buildSignal,
|
|
1311
|
+
onWaiting: async (decision) => await onProjectCheckpoint?.({
|
|
1312
|
+
code: "host_runtime_build_waiting_for_host_capacity",
|
|
1313
|
+
message: `The ASP.NET runtime build is waiting for host capacity: ${decision.detail}`,
|
|
1314
|
+
data: { status: "waiting_for_host_capacity", step_class: aspNetPrebuildStepClass.stepClass, reason: decision.reason },
|
|
1315
|
+
}),
|
|
1316
|
+
}, async (waitMs, control) => {
|
|
1317
|
+
hostLoadWaitMs = waitMs;
|
|
1318
|
+
// A reclaimed token stops the build: its capacity is no longer reserved. So does a
|
|
1319
|
+
// build whose process tree cannot be recorded on its token (a reclaim could not stop it).
|
|
1320
|
+
const unrecorded = new AbortController();
|
|
1321
|
+
const stepSignal = anySignal(buildSignal, control.fenced, unrecorded.signal);
|
|
1322
|
+
return await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, stepSignal, capabilitySecrets, async (metadataPath) => await attachSupervisedStepProcess(control, metadataPath)
|
|
1323
|
+
.catch((error) => { unrecorded.abort(error); }));
|
|
1324
|
+
}), signal);
|
|
1325
|
+
await onProjectCheckpoint?.({
|
|
1326
|
+
code: build.cacheHit ? "host_runtime_build_cached" : "host_runtime_build_completed",
|
|
1327
|
+
message: build.cacheHit
|
|
1328
|
+
? `Reused the verified ASP.NET build for commit ${active.inputCommitSha.slice(0, 12)}.`
|
|
1329
|
+
: `ASP.NET runtime build completed for commit ${active.inputCommitSha.slice(0, 12)}; launching without another build.`,
|
|
1330
|
+
data: {
|
|
1331
|
+
input_commit_sha: active.inputCommitSha,
|
|
1332
|
+
build_fingerprint: build.fingerprint,
|
|
1333
|
+
receipt_path: build.receiptPath,
|
|
1334
|
+
...(hostLoadWaitMs === null ? {} : { host_load_wait_ms: hostLoadWaitMs }),
|
|
1335
|
+
},
|
|
1336
|
+
});
|
|
1337
|
+
}
|
|
1338
|
+
await this.launchNodeRuntime(dispatchAttemptId, fencingToken, configuredPort.name, {
|
|
1339
|
+
command: configuredPort.launch.command,
|
|
1340
|
+
args: configuredPort.launch.args,
|
|
1341
|
+
cwd: workingDirectory,
|
|
1342
|
+
environment: withAttemptApiMasterKey(configuredPort, buildEnvironment, apiMasterKey),
|
|
1343
|
+
}, launcher, signal);
|
|
1344
|
+
}
|
|
1345
|
+
const promotedLease = promote ? await this.promoteVerifiedRuntime(active, active.lease) : active.lease;
|
|
1346
|
+
const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass, active.databaseCapability);
|
|
1347
|
+
const playwright = active.runtimeContract.contract.runtime.playwright;
|
|
1348
|
+
if (!playwright) {
|
|
1349
|
+
return {
|
|
1350
|
+
lease: promotedLease,
|
|
1351
|
+
environment: runtimeEnvironment,
|
|
1352
|
+
runtimeContract: active.runtimeContract,
|
|
1353
|
+
executionClass: active.executionClass,
|
|
1354
|
+
};
|
|
1355
|
+
}
|
|
1356
|
+
const playwrightPort = promotedLease.resources.ports.find(port => port.name === playwright.baseUrlPort);
|
|
1357
|
+
const playwrightPortConfig = active.runtimeContract.contract.runtime.ports
|
|
1358
|
+
.find(port => port.name === playwright.baseUrlPort);
|
|
1359
|
+
if (!playwrightPort || !playwrightPortConfig?.baseUrlEnv) {
|
|
1360
|
+
throw new Error("host_runtime_playwright_unavailable: the configured verified base URL is unavailable.");
|
|
1361
|
+
}
|
|
1362
|
+
if (playwrightPort.hostIp !== "127.0.0.1") {
|
|
1363
|
+
throw new Error("host_runtime_playwright_unavailable: Playwright requires an IPv4 loopback listener.");
|
|
1364
|
+
}
|
|
1365
|
+
const baseUrl = hostPortEnvironment(playwrightPortConfig, playwrightPort.hostIp, playwrightPort.hostPort)[playwrightPortConfig.baseUrlEnv];
|
|
1366
|
+
if (!baseUrl)
|
|
1367
|
+
throw new Error("host_runtime_playwright_unavailable: the configured base URL could not be rendered.");
|
|
1368
|
+
const pathFor = (role) => promotedLease.resources.paths.find(entry => entry.role === role)?.path ?? "";
|
|
1369
|
+
const preparedPlaywright = await this.playwrightAdapter.prepare(playwright, {
|
|
1370
|
+
worktreePath: promotedLease.worktreePath,
|
|
1371
|
+
temporaryDirectory: pathFor("temporary"),
|
|
1372
|
+
testOutputDirectory: pathFor("test_output"),
|
|
1373
|
+
browserProfileDirectory: pathFor("browser_profile"),
|
|
1374
|
+
baseUrl,
|
|
1375
|
+
ownershipToken: uuidHex(promotedLease.dispatchAttemptId, "dispatch attempt"),
|
|
1376
|
+
});
|
|
1377
|
+
return {
|
|
1378
|
+
lease: promotedLease,
|
|
1379
|
+
environment: { ...runtimeEnvironment, ...preparedPlaywright.environment },
|
|
1380
|
+
runtimeContract: active.runtimeContract,
|
|
1381
|
+
executionClass: active.executionClass,
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
/**
|
|
1385
|
+
* Relaunches the configured project so it serves the current workspace. Every
|
|
1386
|
+
* configured process stops (the API port changes, so the dev server's proxy target
|
|
1387
|
+
* must change with it), its port reservation is released and dropped from the
|
|
1388
|
+
* persisted lease, and the regular start path runs again, including the ASP.NET
|
|
1389
|
+
* prebuild, whose receipt rebuilds only when the sources changed.
|
|
1390
|
+
*/
|
|
1391
|
+
async restartConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
|
|
1392
|
+
const active = this.active.get(dispatchAttemptId);
|
|
1393
|
+
if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
|
|
1394
|
+
throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
|
|
1395
|
+
}
|
|
1396
|
+
if (signal?.aborted)
|
|
1397
|
+
throw new Error(String(signal.reason ?? "Host runtime restart was cancelled."));
|
|
1398
|
+
if (active.restartingConfiguredProject) {
|
|
1399
|
+
throw new Error("host_runtime_project_conflict: a configured project restart is already in progress.");
|
|
1400
|
+
}
|
|
1401
|
+
active.restartingConfiguredProject = true;
|
|
1402
|
+
// Release cancels the whole restart through this controller and waits for it to settle.
|
|
1403
|
+
const controller = linkedAbortController(signal);
|
|
1404
|
+
const promise = this.runConfiguredProjectRestart(active, dispatchAttemptId, fencingToken, controller.signal, onProjectCheckpoint);
|
|
1405
|
+
const restart = { controller, promise };
|
|
1406
|
+
active.configuredProjectRestart = restart;
|
|
1407
|
+
try {
|
|
1408
|
+
return await promise;
|
|
1409
|
+
}
|
|
1410
|
+
finally {
|
|
1411
|
+
// The controller is not aborted on settle: adapters this restart launched keep it as their
|
|
1412
|
+
// parent signal for as long as they run, exactly as they would keep the caller's signal.
|
|
1413
|
+
if (active.configuredProjectRestart === restart)
|
|
1414
|
+
active.configuredProjectRestart = null;
|
|
1415
|
+
active.restartingConfiguredProject = false;
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
async runConfiguredProjectRestart(active, dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
|
|
1419
|
+
// The relaunch keeps the admission granted at start. A workspace contract that changed only its
|
|
1420
|
+
// launch environment is adopted; any other change throws host_runtime_contract_changed.
|
|
1421
|
+
const readmitted = readmitHostRuntimeContract(active, await loadHostRuntimeContract(active.lease.worktreePath));
|
|
1422
|
+
active.runtimeContract = readmitted.runtimeContract;
|
|
1423
|
+
active.runtimeContractFingerprint = readmitted.runtimeContractFingerprint;
|
|
1424
|
+
if (readmitted.changed) {
|
|
1425
|
+
await onProjectCheckpoint?.({ code: "host_runtime_contract_readmitted", message: "The workspace's runtime contract changed only its launch environment; the restart runs it under the admission granted at start." });
|
|
1426
|
+
}
|
|
1427
|
+
const portNames = active.executionClass === "analysis_only" ? [] : configuredLaunchPortNames(active.runtimeContract);
|
|
1428
|
+
const pendingPort = portNames.find(name => active.pendingAdapterLaunches.has(name));
|
|
1429
|
+
if (pendingPort) {
|
|
1430
|
+
throw new Error(`host_runtime_project_conflict: configured port '${pendingPort}' is still launching.`);
|
|
1431
|
+
}
|
|
1432
|
+
const temporaryDirectory = active.lease.resources.paths.find(entry => entry.role === "temporary")?.path;
|
|
1433
|
+
if (active.runtimeContract.contract.runtime.playwright && temporaryDirectory) {
|
|
1434
|
+
// The generated Playwright config targets the stack being stopped. If the restart fails, no
|
|
1435
|
+
// config may be left pointing at ports another attempt can now be assigned.
|
|
1436
|
+
await this.playwrightAdapter.discardOverlay(temporaryDirectory);
|
|
1437
|
+
}
|
|
1438
|
+
await this.stopConfiguredProject(active, portNames);
|
|
1439
|
+
// Keeps whatever admission the attempt holds; see launchConfiguredProject.
|
|
1440
|
+
const restarted = await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, false);
|
|
1441
|
+
if (active.releasing) {
|
|
1442
|
+
throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
|
|
1443
|
+
}
|
|
1444
|
+
return restarted;
|
|
1445
|
+
}
|
|
1446
|
+
/** Stops configured project processes in reverse launch order and releases their ports. */
|
|
1447
|
+
async stopConfiguredProject(active, portNames) {
|
|
1448
|
+
const launched = active.lease.resources.ports
|
|
1449
|
+
.map(port => port.name)
|
|
1450
|
+
.filter(name => portNames.includes(name))
|
|
1451
|
+
.reverse();
|
|
1452
|
+
for (const name of launched) {
|
|
1453
|
+
if (active.releasing) {
|
|
1454
|
+
throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
|
|
1455
|
+
}
|
|
1456
|
+
const cleanup = active.adapterCleanupsByPort.get(name);
|
|
1457
|
+
if (!cleanup) {
|
|
1458
|
+
throw new Error(`host_runtime_project_restart_unavailable: configured port '${name}' has no supervised process to stop.`);
|
|
1459
|
+
}
|
|
1460
|
+
// A failed stop keeps the cleanup and the port record for the fenced release retry.
|
|
1461
|
+
await cleanup();
|
|
1462
|
+
removeCleanup(active.adapterCleanups, cleanup);
|
|
1463
|
+
active.adapterCleanupsByPort.delete(name);
|
|
1464
|
+
const runtimeLease = withRuntimeIsolationResources(active.lease, {
|
|
1465
|
+
...active.lease.resources,
|
|
1466
|
+
ports: active.lease.resources.ports.filter(port => port.name !== name),
|
|
1467
|
+
});
|
|
1468
|
+
await this.writeLedger(runtimeLease);
|
|
1469
|
+
active.lease = runtimeLease;
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
providerProcessRunner(dispatchAttemptId, fencingToken) {
|
|
1473
|
+
const active = this.active.get(dispatchAttemptId);
|
|
1474
|
+
if (!active || active.lease.fencingToken !== fencingToken || active.releasing)
|
|
1475
|
+
return null;
|
|
1476
|
+
return new AttemptSupervisedProviderProcessRunner(active.processSupervisor, hostPortOwner(active.lease), this.listenerInspector, active.executionClass === "analysis_only", () => this.markCapacityReservationRunning(dispatchAttemptId, fencingToken));
|
|
1477
|
+
}
|
|
1478
|
+
markCapacityReservationRunning(dispatchAttemptId, fencingToken) {
|
|
1479
|
+
const reservation = this.capacityReservations.get(dispatchAttemptId);
|
|
1480
|
+
if (reservation?.owner.fencingToken === fencingToken)
|
|
1481
|
+
reservation.state = "running";
|
|
1482
|
+
}
|
|
1483
|
+
providerMemoryTelemetry(dispatchAttemptId, fencingToken) {
|
|
1484
|
+
const active = this.active.get(dispatchAttemptId);
|
|
1485
|
+
if (!active || active.lease.fencingToken !== fencingToken || active.releasing)
|
|
1486
|
+
return null;
|
|
1487
|
+
return active.processSupervisor.providerMemoryTelemetry();
|
|
1488
|
+
}
|
|
1489
|
+
async promoteVerifiedRuntime(active, runtimeLease) {
|
|
1490
|
+
if (!active.parallelPromotionEligible)
|
|
1491
|
+
return runtimeLease;
|
|
1492
|
+
const verifiedPortNames = runtimeLease.resources.ports.map(port => port.name).sort((left, right) => left.localeCompare(right));
|
|
1493
|
+
const requiredPortNames = configuredLaunchPortNames(active.runtimeContract);
|
|
1494
|
+
if (requiredPortNames.length !== verifiedPortNames.length
|
|
1495
|
+
|| requiredPortNames.some((name, index) => name !== verifiedPortNames[index])) {
|
|
1496
|
+
return runtimeLease;
|
|
1497
|
+
}
|
|
1498
|
+
const projectKey = projectHostRuntimeSingletonKey(active.repoId);
|
|
1499
|
+
const promotedLease = withRuntimeIsolationResources(runtimeLease, {
|
|
1500
|
+
...runtimeLease.resources,
|
|
1501
|
+
singletonKeys: runtimeLease.resources.singletonKeys.filter(key => key !== projectKey),
|
|
1502
|
+
});
|
|
1503
|
+
await this.writeLedger(promotedLease);
|
|
1504
|
+
active.lease = promotedLease;
|
|
1505
|
+
try {
|
|
1506
|
+
const promotion = await this.promotionStore.observe(active.repoId, active.runtimeContract, runtimeLease.dispatchAttemptId, verifiedPortNames, active.inputCommitSha);
|
|
1507
|
+
this.knownPromotions.set(promotion.repoId, promotion);
|
|
1508
|
+
const owner = {
|
|
1509
|
+
dispatchAttemptId: runtimeLease.dispatchAttemptId,
|
|
1510
|
+
fencingToken: runtimeLease.fencingToken,
|
|
1511
|
+
};
|
|
1512
|
+
if (!this.parallelProjectOwned(projectKey, owner)) {
|
|
1513
|
+
this.convertSingletonToParallelProject(projectKey, owner, promotion);
|
|
1514
|
+
}
|
|
1515
|
+
const admission = this.admissions.get(runtimeLease.dispatchAttemptId);
|
|
1516
|
+
if (admission?.fencingToken === runtimeLease.fencingToken) {
|
|
1517
|
+
this.admissions.set(runtimeLease.dispatchAttemptId, {
|
|
1518
|
+
...admission,
|
|
1519
|
+
keys: promotedLease.resources.singletonKeys,
|
|
1520
|
+
provisionalPromotionFingerprint: promotion.runtimeContractFingerprint,
|
|
1521
|
+
parallelProjectKey: projectKey,
|
|
1522
|
+
});
|
|
1523
|
+
}
|
|
1524
|
+
return promotedLease;
|
|
1525
|
+
}
|
|
1526
|
+
catch {
|
|
1527
|
+
await this.invalidatePromotion(active.repoId).catch(() => undefined);
|
|
1528
|
+
active.lease = runtimeLease;
|
|
1529
|
+
await this.writeLedger(runtimeLease);
|
|
1530
|
+
return runtimeLease;
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
async launchNodeRuntime(dispatchAttemptId, fencingToken, portName, command, launcher, signal) {
|
|
1534
|
+
const active = this.active.get(dispatchAttemptId);
|
|
1535
|
+
if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
|
|
1536
|
+
throw new Error("host_runtime_adapter_unavailable: an active matching host runtime lease is required.");
|
|
1537
|
+
}
|
|
1538
|
+
const portConfig = active.runtimeContract.contract.runtime.ports.find(port => port.name === portName);
|
|
1539
|
+
if (!portConfig)
|
|
1540
|
+
throw new Error(`host_runtime_adapter_invalid: configured port '${portName}' was not found.`);
|
|
1541
|
+
if (active.lease.resources.ports.some(port => port.name === portName) || active.pendingAdapterLaunches.has(portName)) {
|
|
1542
|
+
throw new Error(`host_runtime_adapter_conflict: configured port '${portName}' is already active.`);
|
|
1543
|
+
}
|
|
1544
|
+
const controller = linkedAbortController(signal);
|
|
1545
|
+
let retainedByActiveRuntime = false;
|
|
1546
|
+
const operation = (async () => {
|
|
1547
|
+
const owner = hostPortOwner(active.lease);
|
|
1548
|
+
const launched = await this.nodeAdapter.launch(owner, portConfig, command, launcher, controller.signal);
|
|
1549
|
+
let cleaned = false;
|
|
1550
|
+
const cleanup = async () => {
|
|
1551
|
+
if (cleaned)
|
|
1552
|
+
return;
|
|
1553
|
+
await launcher.stop(launched.value);
|
|
1554
|
+
await this.portBroker.release(launched.reservation.reservationId, owner);
|
|
1555
|
+
cleaned = true;
|
|
1556
|
+
unlinkAbortController(controller, signal);
|
|
1557
|
+
};
|
|
1558
|
+
active.adapterCleanups.push(cleanup);
|
|
1559
|
+
active.adapterCleanupsByPort.set(portName, cleanup);
|
|
1560
|
+
try {
|
|
1561
|
+
if (active.releasing)
|
|
1562
|
+
throw new Error("host_runtime_adapter_cancelled: host runtime release started during launch.");
|
|
1563
|
+
const runtimeLease = withRuntimeIsolationResources(active.lease, {
|
|
1564
|
+
...active.lease.resources,
|
|
1565
|
+
ports: [...active.lease.resources.ports, {
|
|
1566
|
+
name: launched.reservation.name,
|
|
1567
|
+
protocol: launched.reservation.protocol,
|
|
1568
|
+
hostIp: launched.reservation.hostIp,
|
|
1569
|
+
hostPort: launched.reservation.hostPort,
|
|
1570
|
+
targetPort: launched.reservation.targetPort,
|
|
1571
|
+
}],
|
|
1572
|
+
});
|
|
1573
|
+
await this.writeLedger(runtimeLease);
|
|
1574
|
+
active.lease = runtimeLease;
|
|
1575
|
+
retainedByActiveRuntime = true;
|
|
1576
|
+
return { ...launched, runtimeLease };
|
|
1577
|
+
}
|
|
1578
|
+
catch (error) {
|
|
1579
|
+
try {
|
|
1580
|
+
await cleanup();
|
|
1581
|
+
removeCleanup(active.adapterCleanups, cleanup);
|
|
1582
|
+
if (active.adapterCleanupsByPort.get(portName) === cleanup)
|
|
1583
|
+
active.adapterCleanupsByPort.delete(portName);
|
|
1584
|
+
}
|
|
1585
|
+
catch {
|
|
1586
|
+
// Preserve the cleanup and broker claim for the fenced release retry.
|
|
1587
|
+
}
|
|
1588
|
+
throw error;
|
|
1589
|
+
}
|
|
1590
|
+
})();
|
|
1591
|
+
active.pendingAdapterLaunches.set(portName, { controller, promise: operation });
|
|
1592
|
+
try {
|
|
1593
|
+
return await operation;
|
|
1594
|
+
}
|
|
1595
|
+
finally {
|
|
1596
|
+
active.pendingAdapterLaunches.delete(portName);
|
|
1597
|
+
if (!retainedByActiveRuntime)
|
|
1598
|
+
unlinkAbortController(controller, signal);
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
async release(dispatchAttemptId, fencingToken, preservePreparation = false) {
|
|
1602
|
+
if (!preservePreparation)
|
|
1603
|
+
this.preparedReadiness.cancel(dispatchAttemptId, fencingToken);
|
|
1604
|
+
const active = this.active.get(dispatchAttemptId);
|
|
1605
|
+
if (!preservePreparation)
|
|
1606
|
+
this.pendingRenewals.delete(dispatchAttemptId);
|
|
1607
|
+
if (!active) {
|
|
1608
|
+
// Queued steps are cancelled and running ones stopped; each returns its own
|
|
1609
|
+
// token once its processes are gone (never before, or capacity is reused early).
|
|
1610
|
+
this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
|
|
1611
|
+
this.cancelAdmissionWaiters(dispatchAttemptId, fencingToken, "Managed host admission was released before acquisition.");
|
|
1612
|
+
this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
|
|
1613
|
+
this.releaseParallelProjects(dispatchAttemptId, fencingToken);
|
|
1614
|
+
this.deleteAdmission(dispatchAttemptId, fencingToken);
|
|
1615
|
+
return null;
|
|
1616
|
+
}
|
|
1617
|
+
if (active.lease.fencingToken !== fencingToken)
|
|
1618
|
+
return null;
|
|
1619
|
+
active.releasing = true;
|
|
1620
|
+
// Attempt teardown cancels the attempt's queued heavy steps and stops its running
|
|
1621
|
+
// ones. Each running step (an ASP.NET prebuild, an install, a validation step)
|
|
1622
|
+
// returns its own token only after its processes have exited, so the capacity is
|
|
1623
|
+
// not reused while, say, a build is still being terminated.
|
|
1624
|
+
this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
|
|
1625
|
+
for (const pending of active.pendingAdapterLaunches.values()) {
|
|
1626
|
+
pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
|
|
1627
|
+
}
|
|
1628
|
+
await Promise.allSettled([...active.pendingAdapterLaunches.values()].map(pending => pending.promise));
|
|
1629
|
+
const restart = active.configuredProjectRestart;
|
|
1630
|
+
if (restart) {
|
|
1631
|
+
restart.controller.abort("Host runtime release cancelled the configured project restart.");
|
|
1632
|
+
await restart.promise.catch(() => undefined);
|
|
1633
|
+
}
|
|
1634
|
+
await active.databaseProvision?.catch(() => undefined);
|
|
1635
|
+
let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
|
|
1636
|
+
active.lease = releasing;
|
|
1637
|
+
await this.writeLedger(releasing);
|
|
1638
|
+
try {
|
|
1639
|
+
if (!active.runtimeResourcesReleased) {
|
|
1640
|
+
await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
|
|
1641
|
+
// The attempt's MCP servers and process trees are stopped now; tokens they held
|
|
1642
|
+
// belong to dead owners and go back to the host budget at once, including any
|
|
1643
|
+
// without a recorded process tree (their steps were inside the stopped trees).
|
|
1644
|
+
await this.hostLoadGovernor.reclaim().catch(() => undefined);
|
|
1645
|
+
await this.hostLoadGovernor.releaseOrphaned(token => token.dispatchAttemptId === dispatchAttemptId)
|
|
1646
|
+
.catch(() => undefined);
|
|
1647
|
+
// This bridge's own steps whose trees only stopAll could prove gone (a supervised
|
|
1648
|
+
// validation step whose termination failed earlier) return their tokens now.
|
|
1649
|
+
await this.hostLoadGovernor.releaseRetainedAfterTeardown(dispatchAttemptId).catch(() => undefined);
|
|
1650
|
+
await releaseAdapterResources(active.adapterCleanups);
|
|
1651
|
+
active.adapterCleanupsByPort.clear();
|
|
1652
|
+
if (active.databaseCapability && this.databaseBroker) {
|
|
1653
|
+
// A database the broker cannot drop now is reaped later; it must not hold host capacity.
|
|
1654
|
+
await this.databaseBroker.release(dispatchAttemptId, fencingToken).catch(() => "retained");
|
|
1655
|
+
}
|
|
1656
|
+
active.runtimeResourcesReleased = true;
|
|
1657
|
+
// Runtime admission protects live processes, listeners, ports, and their
|
|
1658
|
+
// memory commitment. Once exact process and adapter cleanup succeeds,
|
|
1659
|
+
// diagnostics retention remains retryable evidence work and must not keep
|
|
1660
|
+
// consuming host capacity or blocking the next project dispatch.
|
|
1661
|
+
this.processSupervisors.unregister(dispatchAttemptId, fencingToken);
|
|
1662
|
+
this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
|
|
1663
|
+
this.releaseParallelProjects(dispatchAttemptId, fencingToken);
|
|
1664
|
+
this.deleteAdmission(dispatchAttemptId, fencingToken);
|
|
1665
|
+
}
|
|
1666
|
+
let evidenceRetainedAtAttemptRoot = false;
|
|
1667
|
+
try {
|
|
1668
|
+
const diagnosticsPath = await retainHostDiagnostics(this.stateRoot, active.attemptRoot, dispatchAttemptId, active.attemptRootIdentity, this.executionRoot);
|
|
1669
|
+
releasing = withRuntimeIsolationResources(releasing, {
|
|
1670
|
+
...releasing.resources,
|
|
1671
|
+
paths: [...releasing.resources.paths.filter(entry => entry.role !== "diagnostics_archive"),
|
|
1672
|
+
{ role: "diagnostics_archive", path: diagnosticsPath }],
|
|
1673
|
+
});
|
|
1674
|
+
}
|
|
1675
|
+
catch {
|
|
1676
|
+
// Runtime teardown is already proven above. Diagnostics archival is
|
|
1677
|
+
// deliberately non-destructive and may refuse a changed or unsupported
|
|
1678
|
+
// attempt-root inventory. Preserve that root and its released ledger for
|
|
1679
|
+
// operator inspection/reconciliation without converting completed
|
|
1680
|
+
// teardown into a capacity-owning degraded runtime.
|
|
1681
|
+
evidenceRetainedAtAttemptRoot = true;
|
|
1682
|
+
}
|
|
1683
|
+
if (!evidenceRetainedAtAttemptRoot)
|
|
1684
|
+
await removeHostAttemptRoot(active.attemptRoot);
|
|
1685
|
+
const released = transitionRuntimeIsolationLease(releasing, "released");
|
|
1686
|
+
// Publish the terminal in-memory state before its serialized write. Any writer
|
|
1687
|
+
// that already captured this active owner must observe the terminal fence and
|
|
1688
|
+
// cannot recreate a nonterminal ledger after release completes.
|
|
1689
|
+
active.lease = released;
|
|
1690
|
+
await this.writeLedger(released);
|
|
1691
|
+
if (!evidenceRetainedAtAttemptRoot) {
|
|
1692
|
+
await fs.rm(this.ledgerPath(dispatchAttemptId), { force: true });
|
|
1693
|
+
}
|
|
1694
|
+
releasing = released;
|
|
1695
|
+
this.active.delete(dispatchAttemptId);
|
|
1696
|
+
this.processSupervisors.unregister(dispatchAttemptId, fencingToken);
|
|
1697
|
+
this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
|
|
1698
|
+
this.releaseParallelProjects(dispatchAttemptId, fencingToken);
|
|
1699
|
+
this.deleteAdmission(dispatchAttemptId, fencingToken);
|
|
1700
|
+
return releasing;
|
|
1701
|
+
}
|
|
1702
|
+
catch (error) {
|
|
1703
|
+
const degraded = transitionRuntimeIsolationLease(releasing, "degraded");
|
|
1704
|
+
active.lease = degraded;
|
|
1705
|
+
await this.writeLedger(degraded).catch(() => undefined);
|
|
1706
|
+
throw new HostRuntimeLeaseCleanupError(degraded, error);
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
async readLedgers() {
|
|
1710
|
+
const root = path.join(this.stateRoot, "runtime-ledger", "host");
|
|
1711
|
+
const entries = await fs.readdir(root, { withFileTypes: true }).catch(error => {
|
|
1712
|
+
if (error.code === "ENOENT")
|
|
1713
|
+
return [];
|
|
1714
|
+
throw error;
|
|
1715
|
+
});
|
|
1716
|
+
const ledgers = [];
|
|
1717
|
+
for (const entry of entries) {
|
|
1718
|
+
if (!entry.isFile() || !/^[0-9a-f]{32}\.json$/u.test(entry.name))
|
|
1719
|
+
continue;
|
|
1720
|
+
try {
|
|
1721
|
+
const value = JSON.parse(await fs.readFile(path.join(root, entry.name), "utf8"));
|
|
1722
|
+
if (!validHostRuntimeLedger(value))
|
|
1723
|
+
continue;
|
|
1724
|
+
const expectedName = `${uuidHex(value.runtimeLease.dispatchAttemptId, "dispatch attempt")}.json`;
|
|
1725
|
+
if (entry.name !== expectedName)
|
|
1726
|
+
continue;
|
|
1727
|
+
ledgers.push(value);
|
|
1728
|
+
}
|
|
1729
|
+
catch {
|
|
1730
|
+
// An invalid ledger has no trustworthy ownership identity and is never reaped.
|
|
1731
|
+
}
|
|
1732
|
+
}
|
|
1733
|
+
return ledgers;
|
|
1734
|
+
}
|
|
1735
|
+
async recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity) {
|
|
1736
|
+
const logsRoot = path.join(attemptRoot, "logs");
|
|
1737
|
+
const expectedAttemptRoot = path.resolve(this.attemptRoot(lease.dispatchAttemptId));
|
|
1738
|
+
if (path.resolve(attemptRoot) !== expectedAttemptRoot) {
|
|
1739
|
+
throw new Error("host_runtime_reaper_invalid: attempt path is outside the fenced attempt root.");
|
|
1740
|
+
}
|
|
1741
|
+
await assertHostAttemptRootIdentity(attemptRoot, attemptRootIdentity);
|
|
1742
|
+
const rootEntries = await readPinnedSourceDirectory(attemptRoot, attemptRootIdentity);
|
|
1743
|
+
const logsEntry = rootEntries.find(entry => entry.name === "logs");
|
|
1744
|
+
if (!logsEntry)
|
|
1745
|
+
return [];
|
|
1746
|
+
if (logsEntry.kind !== "directory") {
|
|
1747
|
+
throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
|
|
1748
|
+
}
|
|
1749
|
+
const outcomes = [];
|
|
1750
|
+
const failures = [];
|
|
1751
|
+
try {
|
|
1752
|
+
const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
|
|
1753
|
+
for (const entry of entries) {
|
|
1754
|
+
if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
|
|
1755
|
+
continue;
|
|
1756
|
+
const metadataPath = path.join(logsRoot, entry.name);
|
|
1757
|
+
const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
|
|
1758
|
+
if (!validHostProcessSupervisorMetadata(value, lease)) {
|
|
1759
|
+
throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
|
|
1760
|
+
}
|
|
1761
|
+
outcomes.push(await this.processRecovery.recover(value));
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
catch (error) {
|
|
1765
|
+
failures.push(error);
|
|
1766
|
+
}
|
|
1767
|
+
// Managed commands run in their own process groups and record their ownership apart
|
|
1768
|
+
// from the attempt's supervised children. They are recovered even when recovering a
|
|
1769
|
+
// supervised child failed, and both failures are reported together.
|
|
1770
|
+
try {
|
|
1771
|
+
const managed = await terminateAttemptManagedCommands({
|
|
1772
|
+
logDirectory: logsRoot,
|
|
1773
|
+
dispatchAttemptId: lease.dispatchAttemptId,
|
|
1774
|
+
runtimeLeaseId: lease.executionLeaseId,
|
|
1775
|
+
pinnedLogDirectory: logsEntry.identity,
|
|
1776
|
+
}, { reason: "attempt_teardown" });
|
|
1777
|
+
for (const command of managed) {
|
|
1778
|
+
if (command.outcome === "terminated" || command.outcome === "pid_reused")
|
|
1779
|
+
outcomes.push(command.outcome);
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
catch (error) {
|
|
1783
|
+
failures.push(error);
|
|
1784
|
+
}
|
|
1785
|
+
if (failures.length === 1)
|
|
1786
|
+
throw failures[0];
|
|
1787
|
+
if (failures.length > 1)
|
|
1788
|
+
throw new AggregateError(failures, "host_runtime_reaper_recovery_failed");
|
|
1789
|
+
return outcomes;
|
|
1790
|
+
}
|
|
1791
|
+
async markLedgerDegraded(ledger) {
|
|
1792
|
+
const lease = ledger.runtimeLease;
|
|
1793
|
+
if (lease.state === "released")
|
|
1794
|
+
return;
|
|
1795
|
+
const degraded = transitionHostLeaseForCleanup(lease, "degraded");
|
|
1796
|
+
const repoId = ledger.repoId ?? repoIdFromProjectSingletonKeys(lease.resources.singletonKeys);
|
|
1797
|
+
this.rememberDegraded(degraded, repoId);
|
|
1798
|
+
await this.writeLedger(degraded, repoId ?? undefined, deserializeHostAttemptRootIdentity(ledger.attemptRootIdentity)).catch(() => undefined);
|
|
1799
|
+
}
|
|
1800
|
+
rememberDegraded(lease, repoId) {
|
|
1801
|
+
this.degraded.set(lease.dispatchAttemptId, { lease, repoId });
|
|
1802
|
+
if (!repoId)
|
|
1803
|
+
return;
|
|
1804
|
+
const owner = { dispatchAttemptId: lease.dispatchAttemptId, fencingToken: lease.fencingToken };
|
|
1805
|
+
const projectKey = projectHostRuntimeSingletonKey(repoId);
|
|
1806
|
+
const existing = this.singletonOwners.get(projectKey);
|
|
1807
|
+
if (!existing || sameSingletonOwner(existing, owner))
|
|
1808
|
+
this.singletonOwners.set(projectKey, owner);
|
|
1809
|
+
}
|
|
1810
|
+
forgetDegraded(dispatchAttemptId, fencingToken) {
|
|
1811
|
+
if (this.degraded.get(dispatchAttemptId)?.lease.fencingToken !== fencingToken)
|
|
1812
|
+
return;
|
|
1813
|
+
this.degraded.delete(dispatchAttemptId);
|
|
1814
|
+
this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
|
|
1815
|
+
this.releaseParallelProjects(dispatchAttemptId, fencingToken);
|
|
1816
|
+
}
|
|
1817
|
+
attemptRoot(dispatchAttemptId) {
|
|
1818
|
+
return path.join(this.executionRoot, "a", compactHostAttemptId(dispatchAttemptId));
|
|
1819
|
+
}
|
|
1820
|
+
writeLedger(runtimeLease, explicitRepoId, explicitAttemptRootIdentity) {
|
|
1821
|
+
const activeOwner = this.active.get(runtimeLease.dispatchAttemptId);
|
|
1822
|
+
const write = this.ledgerWriteTail.then(() => {
|
|
1823
|
+
if (activeOwner?.lease.fencingToken === runtimeLease.fencingToken
|
|
1824
|
+
&& activeOwner.lease.state === "released"
|
|
1825
|
+
&& runtimeLease.state !== "released") {
|
|
1826
|
+
return;
|
|
1827
|
+
}
|
|
1828
|
+
return this.writeLedgerAtomic(runtimeLease, explicitRepoId, explicitAttemptRootIdentity);
|
|
1829
|
+
});
|
|
1830
|
+
this.ledgerWriteTail = write.catch(() => undefined);
|
|
1831
|
+
return write;
|
|
1832
|
+
}
|
|
1833
|
+
async writeLedgerAtomic(runtimeLease, explicitRepoId, explicitAttemptRootIdentity) {
|
|
1834
|
+
const root = path.join(this.stateRoot, "runtime-ledger", "host");
|
|
1835
|
+
await ensurePrivateDirectory(root);
|
|
1836
|
+
const target = this.ledgerPath(runtimeLease.dispatchAttemptId);
|
|
1837
|
+
const temporary = `${target}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`;
|
|
1838
|
+
try {
|
|
1839
|
+
const handle = await fs.open(temporary, "wx", 0o600);
|
|
1840
|
+
try {
|
|
1841
|
+
const repoId = explicitRepoId
|
|
1842
|
+
?? this.active.get(runtimeLease.dispatchAttemptId)?.repoId
|
|
1843
|
+
?? this.admissions.get(runtimeLease.dispatchAttemptId)?.repoId
|
|
1844
|
+
?? this.degraded.get(runtimeLease.dispatchAttemptId)?.repoId
|
|
1845
|
+
?? undefined;
|
|
1846
|
+
const attemptRootIdentity = explicitAttemptRootIdentity
|
|
1847
|
+
?? this.active.get(runtimeLease.dispatchAttemptId)?.attemptRootIdentity
|
|
1848
|
+
?? undefined;
|
|
1849
|
+
const ledger = {
|
|
1850
|
+
schemaVersion: 1,
|
|
1851
|
+
...(repoId ? { repoId } : {}),
|
|
1852
|
+
...(attemptRootIdentity
|
|
1853
|
+
? { attemptRootIdentity: serializeHostAttemptRootIdentity(attemptRootIdentity) }
|
|
1854
|
+
: {}),
|
|
1855
|
+
runtimeLease,
|
|
1856
|
+
};
|
|
1857
|
+
await handle.writeFile(`${JSON.stringify(ledger)}\n`);
|
|
1858
|
+
await handle.sync();
|
|
1859
|
+
}
|
|
1860
|
+
finally {
|
|
1861
|
+
await handle.close();
|
|
1862
|
+
}
|
|
1863
|
+
await fs.rename(temporary, target);
|
|
1864
|
+
}
|
|
1865
|
+
catch (error) {
|
|
1866
|
+
await fs.rm(temporary, { force: true }).catch(() => undefined);
|
|
1867
|
+
throw new Error(`host_runtime_ledger_write_failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
ledgerPath(dispatchAttemptId) {
|
|
1871
|
+
const attemptHex = uuidHex(dispatchAttemptId, "dispatch attempt");
|
|
1872
|
+
return path.join(this.stateRoot, "runtime-ledger", "host", `${attemptHex}.json`);
|
|
1873
|
+
}
|
|
1874
|
+
singletonKeysAvailable(keys) {
|
|
1875
|
+
return keys.every(key => !this.singletonOwners.has(key) && !this.parallelProjectOwners.has(key));
|
|
1876
|
+
}
|
|
1877
|
+
assignSingletonKeys(keys, owner) {
|
|
1878
|
+
for (const key of keys)
|
|
1879
|
+
this.singletonOwners.set(key, owner);
|
|
1880
|
+
}
|
|
1881
|
+
releaseSingletonKeys(dispatchAttemptId, fencingToken) {
|
|
1882
|
+
for (const [key, owner] of this.singletonOwners) {
|
|
1883
|
+
if (owner.dispatchAttemptId === dispatchAttemptId && owner.fencingToken === fencingToken) {
|
|
1884
|
+
this.singletonOwners.delete(key);
|
|
1885
|
+
}
|
|
1886
|
+
}
|
|
1887
|
+
this.drainAdmissionWaiters();
|
|
1888
|
+
}
|
|
1889
|
+
convertSingletonToParallelProject(key, owner, promotion) {
|
|
1890
|
+
if (!sameSingletonOwner(this.singletonOwners.get(key), owner)) {
|
|
1891
|
+
throw new Error("host_runtime_parallel_promotion_stale: matching exclusive project admission is required.");
|
|
1892
|
+
}
|
|
1893
|
+
this.assignParallelProject(key, owner);
|
|
1894
|
+
this.singletonOwners.delete(key);
|
|
1895
|
+
for (let index = 0; index < this.singletonWaiters.length;) {
|
|
1896
|
+
const waiter = this.singletonWaiters[index];
|
|
1897
|
+
if (waiter.priority !== "foreground" || waiter.keys.length !== 1 || waiter.keys[0] !== key) {
|
|
1898
|
+
index += 1;
|
|
1899
|
+
continue;
|
|
1900
|
+
}
|
|
1901
|
+
this.singletonWaiters.splice(index, 1);
|
|
1902
|
+
clearAdmissionDeadline(waiter);
|
|
1903
|
+
waiter.signal?.removeEventListener("abort", waiter.abort);
|
|
1904
|
+
this.assignParallelProject(key, waiter.owner);
|
|
1905
|
+
this.knownPromotions.set(promotion.repoId, promotion);
|
|
1906
|
+
waiter.resolve([]);
|
|
1907
|
+
}
|
|
1908
|
+
this.drainAdmissionWaiters();
|
|
1909
|
+
}
|
|
1910
|
+
parallelProjectOwned(key, owner) {
|
|
1911
|
+
return sameSingletonOwner(this.parallelProjectOwners.get(key)?.get(owner.dispatchAttemptId), owner);
|
|
1912
|
+
}
|
|
1913
|
+
parallelProjectAvailable(key, priority = "foreground") {
|
|
1914
|
+
return !this.singletonOwners.has(key)
|
|
1915
|
+
&& !this.singletonWaiters.some(waiter => waiter.keys.includes(key)
|
|
1916
|
+
&& (priority === "background" || waiter.priority === "foreground"));
|
|
1917
|
+
}
|
|
1918
|
+
assignParallelProject(key, owner) {
|
|
1919
|
+
const owners = this.parallelProjectOwners.get(key) ?? new Map();
|
|
1920
|
+
owners.set(owner.dispatchAttemptId, owner);
|
|
1921
|
+
this.parallelProjectOwners.set(key, owners);
|
|
1922
|
+
}
|
|
1923
|
+
releaseParallelProjectNoDrain(key, owner) {
|
|
1924
|
+
const owners = this.parallelProjectOwners.get(key);
|
|
1925
|
+
if (!sameSingletonOwner(owners?.get(owner.dispatchAttemptId), owner))
|
|
1926
|
+
return;
|
|
1927
|
+
owners.delete(owner.dispatchAttemptId);
|
|
1928
|
+
if (owners.size === 0)
|
|
1929
|
+
this.parallelProjectOwners.delete(key);
|
|
1930
|
+
}
|
|
1931
|
+
releaseParallelProjects(dispatchAttemptId, fencingToken) {
|
|
1932
|
+
const owner = { dispatchAttemptId, fencingToken };
|
|
1933
|
+
for (const key of [...this.parallelProjectOwners.keys()]) {
|
|
1934
|
+
this.releaseParallelProjectNoDrain(key, owner);
|
|
1935
|
+
}
|
|
1936
|
+
this.drainAdmissionWaiters();
|
|
1937
|
+
}
|
|
1938
|
+
deleteAdmission(dispatchAttemptId, fencingToken) {
|
|
1939
|
+
if (this.admissions.get(dispatchAttemptId)?.fencingToken === fencingToken) {
|
|
1940
|
+
this.admissions.delete(dispatchAttemptId);
|
|
1941
|
+
}
|
|
1942
|
+
this.releaseHostCapacity(dispatchAttemptId, fencingToken);
|
|
1943
|
+
}
|
|
1944
|
+
renewAdmissionWaiterDeadline(dispatchAttemptId, fencingToken, expiresAt) {
|
|
1945
|
+
for (const waiter of [
|
|
1946
|
+
...this.singletonWaiters,
|
|
1947
|
+
...this.parallelProjectWaiters,
|
|
1948
|
+
...this.capacityWaiters,
|
|
1949
|
+
...this.backgroundAdmissionWaiters,
|
|
1950
|
+
]) {
|
|
1951
|
+
if (!sameSingletonOwner(waiter.owner, { dispatchAttemptId, fencingToken })
|
|
1952
|
+
|| Date.parse(expiresAt) <= Date.parse(waiter.expiresAt))
|
|
1953
|
+
continue;
|
|
1954
|
+
waiter.expiresAt = expiresAt;
|
|
1955
|
+
clearAdmissionDeadline(waiter);
|
|
1956
|
+
waiter.deadlineTimer = scheduleAdmissionDeadline(waiter.expiresAt, waiter.expire);
|
|
1957
|
+
}
|
|
1958
|
+
}
|
|
1959
|
+
clearPendingRenewal(owner) {
|
|
1960
|
+
if (this.pendingRenewals.get(owner.dispatchAttemptId)?.fencingToken === owner.fencingToken) {
|
|
1961
|
+
this.pendingRenewals.delete(owner.dispatchAttemptId);
|
|
1962
|
+
}
|
|
1963
|
+
}
|
|
1964
|
+
cancelAdmissionWaiters(dispatchAttemptId, fencingToken, reason) {
|
|
1965
|
+
const owner = { dispatchAttemptId, fencingToken };
|
|
1966
|
+
for (const waiters of [
|
|
1967
|
+
this.singletonWaiters,
|
|
1968
|
+
this.parallelProjectWaiters,
|
|
1969
|
+
this.capacityWaiters,
|
|
1970
|
+
this.backgroundAdmissionWaiters,
|
|
1971
|
+
]) {
|
|
1972
|
+
for (let index = waiters.length - 1; index >= 0; index -= 1) {
|
|
1973
|
+
const waiter = waiters[index];
|
|
1974
|
+
if (!sameSingletonOwner(waiter.owner, owner))
|
|
1975
|
+
continue;
|
|
1976
|
+
waiters.splice(index, 1);
|
|
1977
|
+
clearAdmissionDeadline(waiter);
|
|
1978
|
+
if ("capacityRecheckTimer" in waiter)
|
|
1979
|
+
clearCapacityRecheck(waiter);
|
|
1980
|
+
waiter.signal?.removeEventListener("abort", waiter.abort);
|
|
1981
|
+
waiter.reject(new Error(`host_runtime_admission_cancelled: ${reason}`));
|
|
1982
|
+
}
|
|
1983
|
+
}
|
|
1984
|
+
this.drainAdmissionWaiters();
|
|
1985
|
+
}
|
|
1986
|
+
drainSingletonWaiters() {
|
|
1987
|
+
for (let index = 0; index < this.singletonWaiters.length;) {
|
|
1988
|
+
const waiter = this.singletonWaiters[index];
|
|
1989
|
+
if (waiter.signal?.aborted) {
|
|
1990
|
+
this.singletonWaiters.splice(index, 1);
|
|
1991
|
+
clearAdmissionDeadline(waiter);
|
|
1992
|
+
waiter.signal.removeEventListener("abort", waiter.abort);
|
|
1993
|
+
this.clearPendingRenewal(waiter.owner);
|
|
1994
|
+
waiter.reject(cancellationError(waiter.signal));
|
|
1995
|
+
continue;
|
|
1996
|
+
}
|
|
1997
|
+
if (admissionExpired(waiter.expiresAt)) {
|
|
1998
|
+
this.singletonWaiters.splice(index, 1);
|
|
1999
|
+
clearAdmissionDeadline(waiter);
|
|
2000
|
+
waiter.signal?.removeEventListener("abort", waiter.abort);
|
|
2001
|
+
this.clearPendingRenewal(waiter.owner);
|
|
2002
|
+
waiter.reject(new HostRuntimeAdmissionExpiredError());
|
|
2003
|
+
continue;
|
|
2004
|
+
}
|
|
2005
|
+
if (!this.singletonKeysAvailable(waiter.keys)) {
|
|
2006
|
+
index += 1;
|
|
2007
|
+
continue;
|
|
2008
|
+
}
|
|
2009
|
+
this.singletonWaiters.splice(index, 1);
|
|
2010
|
+
clearAdmissionDeadline(waiter);
|
|
2011
|
+
waiter.signal?.removeEventListener("abort", waiter.abort);
|
|
2012
|
+
this.assignSingletonKeys(waiter.keys, waiter.owner);
|
|
2013
|
+
waiter.resolve(waiter.keys);
|
|
2014
|
+
}
|
|
2015
|
+
}
|
|
2016
|
+
drainParallelProjectWaiters() {
|
|
2017
|
+
for (let index = 0; index < this.parallelProjectWaiters.length;) {
|
|
2018
|
+
const waiter = this.parallelProjectWaiters[index];
|
|
2019
|
+
if (waiter.signal?.aborted) {
|
|
2020
|
+
this.parallelProjectWaiters.splice(index, 1);
|
|
2021
|
+
clearAdmissionDeadline(waiter);
|
|
2022
|
+
waiter.signal.removeEventListener("abort", waiter.abort);
|
|
2023
|
+
this.clearPendingRenewal(waiter.owner);
|
|
2024
|
+
waiter.reject(cancellationError(waiter.signal));
|
|
2025
|
+
continue;
|
|
2026
|
+
}
|
|
2027
|
+
if (admissionExpired(waiter.expiresAt)) {
|
|
2028
|
+
this.parallelProjectWaiters.splice(index, 1);
|
|
2029
|
+
clearAdmissionDeadline(waiter);
|
|
2030
|
+
waiter.signal?.removeEventListener("abort", waiter.abort);
|
|
2031
|
+
this.clearPendingRenewal(waiter.owner);
|
|
2032
|
+
waiter.reject(new HostRuntimeAdmissionExpiredError());
|
|
2033
|
+
continue;
|
|
2034
|
+
}
|
|
2035
|
+
if (!this.parallelProjectAvailable(waiter.key, waiter.priority)) {
|
|
2036
|
+
index += 1;
|
|
2037
|
+
continue;
|
|
2038
|
+
}
|
|
2039
|
+
this.parallelProjectWaiters.splice(index, 1);
|
|
2040
|
+
clearAdmissionDeadline(waiter);
|
|
2041
|
+
waiter.signal?.removeEventListener("abort", waiter.abort);
|
|
2042
|
+
this.assignParallelProject(waiter.key, waiter.owner);
|
|
2043
|
+
waiter.resolve();
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
drainBackgroundAdmissionWaiters() {
|
|
2047
|
+
if (this.hasForegroundDemand())
|
|
2048
|
+
return;
|
|
2049
|
+
for (let index = 0; index < this.backgroundAdmissionWaiters.length;) {
|
|
2050
|
+
const waiter = this.backgroundAdmissionWaiters[index];
|
|
2051
|
+
if (waiter.signal?.aborted) {
|
|
2052
|
+
this.backgroundAdmissionWaiters.splice(index, 1);
|
|
2053
|
+
clearAdmissionDeadline(waiter);
|
|
2054
|
+
clearCapacityRecheck(waiter);
|
|
2055
|
+
waiter.signal.removeEventListener("abort", waiter.abort);
|
|
2056
|
+
this.clearPendingRenewal(waiter.owner);
|
|
2057
|
+
waiter.reject(cancellationError(waiter.signal));
|
|
2058
|
+
continue;
|
|
2059
|
+
}
|
|
2060
|
+
if (admissionExpired(waiter.expiresAt)) {
|
|
2061
|
+
this.backgroundAdmissionWaiters.splice(index, 1);
|
|
2062
|
+
clearAdmissionDeadline(waiter);
|
|
2063
|
+
clearCapacityRecheck(waiter);
|
|
2064
|
+
waiter.signal?.removeEventListener("abort", waiter.abort);
|
|
2065
|
+
this.clearPendingRenewal(waiter.owner);
|
|
2066
|
+
waiter.reject(new HostRuntimeAdmissionExpiredError());
|
|
2067
|
+
continue;
|
|
2068
|
+
}
|
|
2069
|
+
if (!this.singletonKeysAvailable(waiter.keys) || !this.hostCapacityAvailable(waiter.resources)) {
|
|
2070
|
+
index += 1;
|
|
2071
|
+
continue;
|
|
2072
|
+
}
|
|
2073
|
+
this.backgroundAdmissionWaiters.splice(index, 1);
|
|
2074
|
+
clearAdmissionDeadline(waiter);
|
|
2075
|
+
clearCapacityRecheck(waiter);
|
|
2076
|
+
waiter.signal?.removeEventListener("abort", waiter.abort);
|
|
2077
|
+
this.assignSingletonKeys(waiter.keys, waiter.owner);
|
|
2078
|
+
this.capacityReservations.set(waiter.owner.dispatchAttemptId, {
|
|
2079
|
+
owner: waiter.owner,
|
|
2080
|
+
resources: waiter.resources,
|
|
2081
|
+
state: "pending",
|
|
2082
|
+
});
|
|
2083
|
+
waiter.resolve(waiter.keys);
|
|
2084
|
+
}
|
|
2085
|
+
}
|
|
2086
|
+
async refreshKnownPromotions() {
|
|
2087
|
+
const promotions = await this.promotionStore.list();
|
|
2088
|
+
this.knownPromotions.clear();
|
|
2089
|
+
for (const promotion of promotions)
|
|
2090
|
+
this.knownPromotions.set(promotion.repoId, promotion);
|
|
2091
|
+
}
|
|
2092
|
+
async invalidatePromotion(repoId, scope = "all") {
|
|
2093
|
+
await this.promotionStore.invalidate(repoId, scope);
|
|
2094
|
+
this.knownPromotions.delete(repoId.trim().toLowerCase());
|
|
2095
|
+
}
|
|
2096
|
+
drainAdmissionWaiters() {
|
|
2097
|
+
this.reconcileReservationOwners();
|
|
2098
|
+
this.drainSingletonWaiters();
|
|
2099
|
+
this.drainParallelProjectWaiters();
|
|
2100
|
+
this.drainCapacityWaiters();
|
|
2101
|
+
this.drainBackgroundAdmissionWaiters();
|
|
2102
|
+
}
|
|
2103
|
+
reconcileReservationOwners() {
|
|
2104
|
+
for (const [key, owner] of this.singletonOwners) {
|
|
2105
|
+
if (!this.reservationOwnerIsLive(owner))
|
|
2106
|
+
this.singletonOwners.delete(key);
|
|
2107
|
+
}
|
|
2108
|
+
for (const [key, owners] of this.parallelProjectOwners) {
|
|
2109
|
+
for (const [dispatchAttemptId, owner] of owners) {
|
|
2110
|
+
const awaitingExclusiveUpgrade = this.singletonWaiters.some(waiter => waiter.keys.includes(key) && sameSingletonOwner(waiter.owner, owner));
|
|
2111
|
+
// A parallel owner cannot legitimately keep the shared claim after the
|
|
2112
|
+
// same fenced attempt has queued its exclusive downgrade. Reconcile the
|
|
2113
|
+
// half-upgraded state before testing singleton availability so one missed
|
|
2114
|
+
// release cannot make an attempt wait behind itself until lease expiry.
|
|
2115
|
+
if (awaitingExclusiveUpgrade || !this.reservationOwnerIsLive(owner)) {
|
|
2116
|
+
owners.delete(dispatchAttemptId);
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
if (owners.size === 0)
|
|
2120
|
+
this.parallelProjectOwners.delete(key);
|
|
2121
|
+
}
|
|
2122
|
+
}
|
|
2123
|
+
reservationOwnerIsLive(owner) {
|
|
2124
|
+
if (this.acquiringAdmissions.has(hostRuntimeOwnerKey(owner)))
|
|
2125
|
+
return true;
|
|
2126
|
+
if (this.admissions.get(owner.dispatchAttemptId)?.fencingToken === owner.fencingToken)
|
|
2127
|
+
return true;
|
|
2128
|
+
if (this.active.get(owner.dispatchAttemptId)?.lease.fencingToken === owner.fencingToken)
|
|
2129
|
+
return true;
|
|
2130
|
+
if (this.degraded.get(owner.dispatchAttemptId)?.lease.fencingToken === owner.fencingToken)
|
|
2131
|
+
return true;
|
|
2132
|
+
if (sameSingletonOwner(this.capacityReservations.get(owner.dispatchAttemptId)?.owner, owner))
|
|
2133
|
+
return true;
|
|
2134
|
+
return [
|
|
2135
|
+
...this.singletonWaiters,
|
|
2136
|
+
...this.parallelProjectWaiters,
|
|
2137
|
+
...this.capacityWaiters,
|
|
2138
|
+
...this.backgroundAdmissionWaiters,
|
|
2139
|
+
].some(waiter => sameSingletonOwner(waiter.owner, owner));
|
|
2140
|
+
}
|
|
2141
|
+
hasAttemptRepresentation(dispatchAttemptId, fencingToken) {
|
|
2142
|
+
return this.reservationOwnerIsLive({ dispatchAttemptId, fencingToken });
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
class AttemptSupervisedProviderProcessRunner {
|
|
2146
|
+
supervisor;
|
|
2147
|
+
owner;
|
|
2148
|
+
listenerInspector;
|
|
2149
|
+
enforceNoListeners;
|
|
2150
|
+
onProcessTreeStarted;
|
|
2151
|
+
constructor(supervisor, owner, listenerInspector, enforceNoListeners, onProcessTreeStarted) {
|
|
2152
|
+
this.supervisor = supervisor;
|
|
2153
|
+
this.owner = owner;
|
|
2154
|
+
this.listenerInspector = listenerInspector;
|
|
2155
|
+
this.enforceNoListeners = enforceNoListeners;
|
|
2156
|
+
this.onProcessTreeStarted = onProcessTreeStarted;
|
|
2157
|
+
}
|
|
2158
|
+
async run(request, handlers = {}, signal) {
|
|
2159
|
+
const baselineListeners = this.enforceNoListeners
|
|
2160
|
+
? new Set(await this.listenerInspector.inspectLoopbackListeners())
|
|
2161
|
+
: new Set();
|
|
2162
|
+
const child = await this.supervisor.startChildReady("provider", request, handlers, signal, { maxStartAttempts: request.stdin === undefined ? 1 : 3, retryDelayMs: 100 });
|
|
2163
|
+
this.onProcessTreeStarted();
|
|
2164
|
+
try {
|
|
2165
|
+
return await this.awaitProviderResult(child, baselineListeners, signal);
|
|
2166
|
+
}
|
|
2167
|
+
finally {
|
|
2168
|
+
// The provider tree, and the MCP server inside it, is gone. A managed command that
|
|
2169
|
+
// server started now has no supervisor and no receipt writer, so it must not keep
|
|
2170
|
+
// running into the next provider generation. This never rejects; a command it
|
|
2171
|
+
// cannot prove stopped is left to attempt teardown, which fails closed.
|
|
2172
|
+
await this.supervisor.stopOrphanedManagedCommands();
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
async awaitProviderResult(child, baselineListeners, signal) {
|
|
2176
|
+
if (!this.enforceNoListeners)
|
|
2177
|
+
return await child.result;
|
|
2178
|
+
let settled = false;
|
|
2179
|
+
let inspectionFailure;
|
|
2180
|
+
const monitor = (async () => {
|
|
2181
|
+
while (!settled) {
|
|
2182
|
+
try {
|
|
2183
|
+
const ports = (await this.listenerInspector.inspectOwnedLoopbackListeners(child, this.owner))
|
|
2184
|
+
.filter(port => !baselineListeners.has(port));
|
|
2185
|
+
if (ports.length > 0) {
|
|
2186
|
+
inspectionFailure = new Error(`host_analysis_listener_violation: analysis-only provider opened undeclared loopback listener(s): ${ports.join(", ")}.`);
|
|
2187
|
+
await child.stop(this.owner.fencingToken).catch(() => undefined);
|
|
2188
|
+
return;
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
catch (error) {
|
|
2192
|
+
inspectionFailure = error;
|
|
2193
|
+
await child.stop(this.owner.fencingToken).catch(() => undefined);
|
|
2194
|
+
return;
|
|
2195
|
+
}
|
|
2196
|
+
await waitForAnalysisInspection(250, signal).catch(error => {
|
|
2197
|
+
if (!settled && !signal?.aborted)
|
|
2198
|
+
inspectionFailure = error;
|
|
2199
|
+
});
|
|
2200
|
+
}
|
|
2201
|
+
})();
|
|
2202
|
+
try {
|
|
2203
|
+
const result = await child.result;
|
|
2204
|
+
settled = true;
|
|
2205
|
+
await monitor;
|
|
2206
|
+
if (inspectionFailure)
|
|
2207
|
+
throw inspectionFailure;
|
|
2208
|
+
return result;
|
|
2209
|
+
}
|
|
2210
|
+
catch (error) {
|
|
2211
|
+
settled = true;
|
|
2212
|
+
await monitor.catch(() => undefined);
|
|
2213
|
+
if (inspectionFailure)
|
|
2214
|
+
throw inspectionFailure;
|
|
2215
|
+
throw error;
|
|
2216
|
+
}
|
|
2217
|
+
}
|
|
2218
|
+
}
|
|
2219
|
+
function waitForAnalysisInspection(milliseconds, signal) {
|
|
2220
|
+
if (signal?.aborted)
|
|
2221
|
+
return Promise.reject(cancellationError(signal));
|
|
2222
|
+
return new Promise((resolve, reject) => {
|
|
2223
|
+
const timer = setTimeout(() => {
|
|
2224
|
+
signal?.removeEventListener("abort", abort);
|
|
2225
|
+
resolve();
|
|
2226
|
+
}, milliseconds);
|
|
2227
|
+
const abort = () => {
|
|
2228
|
+
clearTimeout(timer);
|
|
2229
|
+
reject(cancellationError(signal));
|
|
2230
|
+
};
|
|
2231
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
2232
|
+
});
|
|
2233
|
+
}
|
|
2234
|
+
export class HostRuntimeLeaseCleanupError extends Error {
|
|
2235
|
+
lease;
|
|
2236
|
+
constructor(lease, cause) {
|
|
2237
|
+
super(`host_runtime_cleanup_degraded: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
|
|
2238
|
+
this.lease = lease;
|
|
2239
|
+
this.name = "HostRuntimeLeaseCleanupError";
|
|
2240
|
+
}
|
|
2241
|
+
}
|
|
2242
|
+
export class HostRuntimeAdmissionExpiredError extends Error {
|
|
2243
|
+
constructor() {
|
|
2244
|
+
super("host_runtime_admission_expired: dispatch lease expired while waiting for managed host admission.");
|
|
2245
|
+
this.name = "HostRuntimeAdmissionExpiredError";
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
export class HostRuntimeCapacityRequestImpossibleError extends Error {
|
|
2249
|
+
constructor(reason) {
|
|
2250
|
+
super(`host_runtime_capacity_request_impossible: ${reason}`);
|
|
2251
|
+
this.name = "HostRuntimeCapacityRequestImpossibleError";
|
|
2252
|
+
}
|
|
2253
|
+
}
|
|
2254
|
+
export function hostRuntimeEventResources(lease, runtimeContract, executionClass = "managed_runtime") {
|
|
2255
|
+
const requestedHostConcurrency = runtimeContract?.contract.runtime.hostConcurrency ?? "serial";
|
|
2256
|
+
const configuredLaunches = runtimeContract?.contract.runtime.ports.filter(port => port.launch !== null) ?? [];
|
|
2257
|
+
const verifiedLaunches = configuredLaunches.filter(configured => lease.resources.ports.some(port => port.name === configured.name));
|
|
2258
|
+
const effectiveConcurrency = effectiveHostConcurrency(lease, runtimeContract, executionClass);
|
|
2259
|
+
return {
|
|
2260
|
+
agentContainer: null,
|
|
2261
|
+
sidecarContainers: [],
|
|
2262
|
+
networks: [],
|
|
2263
|
+
volumes: [],
|
|
2264
|
+
publishedPorts: lease.resources.ports,
|
|
2265
|
+
hostConcurrency: effectiveConcurrency,
|
|
2266
|
+
requestedHostConcurrency,
|
|
2267
|
+
hostParallelPromotion: effectiveConcurrency === "host_parallel_safe"
|
|
2268
|
+
? executionClass === "analysis_only" ? "analysis_profile_enforced" : "observed_probe_passed"
|
|
2269
|
+
: requestedHostConcurrency !== "parallel"
|
|
2270
|
+
? "not_requested"
|
|
2271
|
+
: configuredLaunches.length > 0 && verifiedLaunches.length === configuredLaunches.length
|
|
2272
|
+
? "pending_live_parallel_proof"
|
|
2273
|
+
: "pending_adapter_probe",
|
|
2274
|
+
verifiedRuntimePorts: verifiedLaunches.map(port => port.name),
|
|
2275
|
+
runtimeContractSource: runtimeContract?.source ?? "default",
|
|
2276
|
+
executionClass,
|
|
2277
|
+
requestedPorts: runtimeContract?.contract.runtime.ports.map(port => port.name) ?? [],
|
|
2278
|
+
singletonKeys: lease.resources.singletonKeys,
|
|
2279
|
+
processSupervisorId: lease.resources.processSupervisorId,
|
|
2280
|
+
runtimeLease: lease,
|
|
2281
|
+
};
|
|
2282
|
+
}
|
|
2283
|
+
export function hostRuntimeSingletonKeys(dispatch) {
|
|
2284
|
+
return [projectHostRuntimeSingletonKey(dispatch.repo.id)];
|
|
2285
|
+
}
|
|
2286
|
+
function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClass, databaseCapability) {
|
|
2287
|
+
const pathFor = (role) => lease.resources.paths.find(entry => entry.role === role)?.path ?? "";
|
|
2288
|
+
const environment = {
|
|
2289
|
+
FORGE_SESSION_ID: sessionId,
|
|
2290
|
+
FORGE_RUNTIME_MODE: "host",
|
|
2291
|
+
FORGE_RESOURCE_LEASE_ID: lease.leaseId,
|
|
2292
|
+
FORGE_DISPATCH_ATTEMPT_ID: lease.dispatchAttemptId,
|
|
2293
|
+
FORGE_E2E_OWNERSHIP_MODE: "attempt",
|
|
2294
|
+
FORGE_E2E_OWNERSHIP_TOKEN: uuidHex(lease.dispatchAttemptId, "dispatch attempt"),
|
|
2295
|
+
FORGE_EXECUTION_LEASE_ID: lease.executionLeaseId,
|
|
2296
|
+
FORGE_FENCING_TOKEN: lease.fencingToken,
|
|
2297
|
+
FORGE_WORKSPACE: lease.worktreePath,
|
|
2298
|
+
FORGE_WORKTREE_PATH: lease.worktreePath,
|
|
2299
|
+
FORGE_TMPDIR: pathFor("temporary"),
|
|
2300
|
+
FORGE_LOG_DIR: pathFor("logs"),
|
|
2301
|
+
FORGE_CACHE_DIR: pathFor("cache"),
|
|
2302
|
+
FORGE_BROWSER_PROFILE_DIR: pathFor("browser_profile"),
|
|
2303
|
+
FORGE_TEST_OUTPUT_DIR: pathFor("test_output"),
|
|
2304
|
+
// Project-authored ASP.NET code must not fall back to the durable Forge
|
|
2305
|
+
// database when no brokered attempt database exists. The API policy treats
|
|
2306
|
+
// this marker as a fail-closed isolation requirement.
|
|
2307
|
+
FORGE_ATTEMPT_DATABASE_POLICY: "isolated_only",
|
|
2308
|
+
FORGE_ATTEMPT_DATABASE_SCHEMA: `forge_attempt_${uuidHex(lease.dispatchAttemptId, "dispatch attempt")}`,
|
|
2309
|
+
FORGE_ATTEMPT_DATABASE_READINESS_PATH: path.join(pathFor("logs"), "attempt-database-readiness.json"),
|
|
2310
|
+
FORGE_PROCESS_SUPERVISOR_ID: lease.resources.processSupervisorId ?? "",
|
|
2311
|
+
FORGE_PROCESS_SUPERVISOR_METADATA_PATH: pathFor("process_supervisor_metadata"),
|
|
2312
|
+
FORGE_HOST_CONCURRENCY: effectiveHostConcurrency(lease, runtimeContract, executionClass),
|
|
2313
|
+
FORGE_HOST_CONCURRENCY_REQUESTED: runtimeContract.contract.runtime.hostConcurrency,
|
|
2314
|
+
FORGE_RUNTIME_EXECUTION_CLASS: executionClass,
|
|
2315
|
+
FORGE_HOST_RUNTIME_CONTRACT_SOURCE: runtimeContract.source,
|
|
2316
|
+
FORGE_SINGLETON_KEYS: lease.resources.singletonKeys.join(","),
|
|
2317
|
+
TMPDIR: pathFor("temporary"),
|
|
2318
|
+
TMP: pathFor("temporary"),
|
|
2319
|
+
TEMP: pathFor("temporary"),
|
|
2320
|
+
XDG_CACHE_HOME: pathFor("cache"),
|
|
2321
|
+
NPM_CONFIG_CACHE: path.join(pathFor("cache"), "npm"),
|
|
2322
|
+
};
|
|
2323
|
+
if (lease.resources.singletonKeys.length === 0)
|
|
2324
|
+
delete environment.FORGE_SINGLETON_KEYS;
|
|
2325
|
+
if (databaseCapability)
|
|
2326
|
+
environment[attemptDatabaseCapabilityEnvironment] = databaseCapability.connectionString;
|
|
2327
|
+
const resolvedBaseUrls = [];
|
|
2328
|
+
for (const assigned of lease.resources.ports) {
|
|
2329
|
+
const configured = runtimeContract.contract.runtime.ports.find(port => port.name === assigned.name);
|
|
2330
|
+
if (!configured || assigned.hostIp !== "127.0.0.1")
|
|
2331
|
+
continue;
|
|
2332
|
+
Object.assign(environment, hostPortEnvironment(configured, assigned.hostIp, assigned.hostPort));
|
|
2333
|
+
const normalizedName = assigned.name.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_");
|
|
2334
|
+
environment[`FORGE_${normalizedName}_PORT`] = String(assigned.hostPort);
|
|
2335
|
+
if (configured.baseUrlEnv && configured.format) {
|
|
2336
|
+
const baseUrl = hostPortEnvironment(configured, assigned.hostIp, assigned.hostPort)[configured.baseUrlEnv];
|
|
2337
|
+
if (baseUrl) {
|
|
2338
|
+
environment[`FORGE_${normalizedName}_URL`] = baseUrl;
|
|
2339
|
+
resolvedBaseUrls.push(baseUrl);
|
|
2340
|
+
}
|
|
2341
|
+
}
|
|
2342
|
+
}
|
|
2343
|
+
if (environment.FORGE_API_URL)
|
|
2344
|
+
environment.FORGE_E2E_API_URL = environment.FORGE_API_URL;
|
|
2345
|
+
if (environment.FORGE_WEB_URL)
|
|
2346
|
+
environment.FORGE_E2E_WEB_URL = environment.FORGE_WEB_URL;
|
|
2347
|
+
if (resolvedBaseUrls.length === 1)
|
|
2348
|
+
environment.FORGE_BASE_URL = resolvedBaseUrls[0];
|
|
2349
|
+
return environment;
|
|
2350
|
+
}
|
|
2351
|
+
/**
|
|
2352
|
+
* Every environment key `hostRuntimeEnvironment` and the Playwright overlay derive from the
|
|
2353
|
+
* configured project's assigned ports. They name a live stack, so they are withheld while the
|
|
2354
|
+
* stack is down: after its ports are released another attempt may be assigned them.
|
|
2355
|
+
*/
|
|
2356
|
+
export function hostRuntimeStackEnvironmentKeys(runtimeContract) {
|
|
2357
|
+
const keys = new Set([
|
|
2358
|
+
"FORGE_E2E_API_URL",
|
|
2359
|
+
"FORGE_E2E_WEB_URL",
|
|
2360
|
+
"FORGE_BASE_URL",
|
|
2361
|
+
"FORGE_PLAYWRIGHT_BASE_URL",
|
|
2362
|
+
// The generated Playwright config embeds the base URL.
|
|
2363
|
+
"FORGE_PLAYWRIGHT_CONFIG",
|
|
2364
|
+
]);
|
|
2365
|
+
for (const port of runtimeContract.contract.runtime.ports) {
|
|
2366
|
+
const normalizedName = port.name.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_");
|
|
2367
|
+
keys.add(port.env);
|
|
2368
|
+
if (port.baseUrlEnv)
|
|
2369
|
+
keys.add(port.baseUrlEnv);
|
|
2370
|
+
keys.add(`FORGE_${normalizedName}_PORT`);
|
|
2371
|
+
keys.add(`FORGE_${normalizedName}_URL`);
|
|
2372
|
+
}
|
|
2373
|
+
return [...keys];
|
|
2374
|
+
}
|
|
2375
|
+
/** The attempt's API master key: issued on first use, then the same for every relaunch of the attempt. */
|
|
2376
|
+
function attemptApiMasterKey(active) {
|
|
2377
|
+
return active.apiMasterKey ??= newAttemptApiMasterKey();
|
|
2378
|
+
}
|
|
2379
|
+
function anySignal(...signals) {
|
|
2380
|
+
return AbortSignal.any(signals.filter((signal) => signal !== undefined));
|
|
2381
|
+
}
|
|
2382
|
+
function effectiveHostConcurrency(lease, runtimeContract, executionClass = "managed_runtime") {
|
|
2383
|
+
if (executionClass === "analysis_only") {
|
|
2384
|
+
const analysisSingletonHeld = lease.resources.singletonKeys.length > 0;
|
|
2385
|
+
return analysisSingletonHeld ? "host_serial_only" : "host_parallel_safe";
|
|
2386
|
+
}
|
|
2387
|
+
if (!runtimeContract || !hostRuntimeParallelEligible(runtimeContract))
|
|
2388
|
+
return "host_serial_only";
|
|
2389
|
+
const requiredPorts = configuredLaunchPortNames(runtimeContract);
|
|
2390
|
+
const everyPortVerified = requiredPorts.length > 0
|
|
2391
|
+
&& requiredPorts.every(name => lease.resources.ports.some(port => port.name === name));
|
|
2392
|
+
const projectSingletonHeld = lease.resources.singletonKeys.some(key => key.endsWith(":host-runtime"));
|
|
2393
|
+
return everyPortVerified && !projectSingletonHeld ? "host_parallel_safe" : "host_serial_only";
|
|
2394
|
+
}
|
|
2395
|
+
function projectHostRuntimeSingletonKey(repoId) {
|
|
2396
|
+
return `project:${repoId.toLowerCase()}:host-runtime`;
|
|
2397
|
+
}
|
|
2398
|
+
function projectHostAnalysisKey(repoId) {
|
|
2399
|
+
return `project:${repoId.toLowerCase()}:host-analysis`;
|
|
2400
|
+
}
|
|
2401
|
+
function hostRuntimeDeclaredSingletonKey(resource) {
|
|
2402
|
+
return `runtime:${resource}`;
|
|
2403
|
+
}
|
|
2404
|
+
function runtimeExecutionClass(dispatch) {
|
|
2405
|
+
return dispatch.runtimeIntent?.executionClass === "analysis_only"
|
|
2406
|
+
&& dispatch.runtimeIntent.applicationRuntimeRequired === false
|
|
2407
|
+
? "analysis_only"
|
|
2408
|
+
: "managed_runtime";
|
|
2409
|
+
}
|
|
2410
|
+
export function runtimeAdmissionPriority(dispatch) {
|
|
2411
|
+
return dispatch.execution.lane.trim().toLowerCase() === "runtime_readiness"
|
|
2412
|
+
|| dispatch.cycleRun.phase.trim().toLowerCase() === "readiness_probe"
|
|
2413
|
+
? "background"
|
|
2414
|
+
: "foreground";
|
|
2415
|
+
}
|
|
2416
|
+
function enqueueAdmissionWaiter(waiters, waiter) {
|
|
2417
|
+
if (waiter.priority === "background") {
|
|
2418
|
+
waiters.push(waiter);
|
|
2419
|
+
return;
|
|
2420
|
+
}
|
|
2421
|
+
const backgroundIndex = waiters.findIndex(candidate => candidate.priority === "background");
|
|
2422
|
+
if (backgroundIndex < 0)
|
|
2423
|
+
waiters.push(waiter);
|
|
2424
|
+
else
|
|
2425
|
+
waiters.splice(backgroundIndex, 0, waiter);
|
|
2426
|
+
}
|
|
2427
|
+
function defaultHostResourceRequest() {
|
|
2428
|
+
const workerMemoryLimitBytes = configuredInteger("FORGE_HOST_DEFAULT_WORKER_MEMORY_LIMIT_BYTES", 2 * 1024 ** 3, 128 * 1024 ** 2, 512 * 1024 ** 3);
|
|
2429
|
+
const runtimeOverheadBytes = 128 * 1024 ** 2;
|
|
2430
|
+
return {
|
|
2431
|
+
sandboxSlots: 1,
|
|
2432
|
+
cpuMillis: 2000,
|
|
2433
|
+
workerMemoryLimitBytes,
|
|
2434
|
+
serviceMemoryLimitBytes: 0,
|
|
2435
|
+
runtimeOverheadBytes,
|
|
2436
|
+
memoryBytes: workerMemoryLimitBytes + runtimeOverheadBytes,
|
|
2437
|
+
workspaceBytes: 10 * 1024 ** 3,
|
|
2438
|
+
pids: 512,
|
|
2439
|
+
buildSlots: 1,
|
|
2440
|
+
};
|
|
2441
|
+
}
|
|
2442
|
+
function minimumSupportedHostResourceRequest() {
|
|
2443
|
+
return {
|
|
2444
|
+
sandboxSlots: 1,
|
|
2445
|
+
cpuMillis: 1000,
|
|
2446
|
+
workerMemoryLimitBytes: 1024 ** 3,
|
|
2447
|
+
serviceMemoryLimitBytes: 0,
|
|
2448
|
+
runtimeOverheadBytes: 128 * 1024 ** 2,
|
|
2449
|
+
memoryBytes: 1152 * 1024 ** 2,
|
|
2450
|
+
workspaceBytes: architectMinimumWorkspaceEstimateBytes,
|
|
2451
|
+
pids: 256,
|
|
2452
|
+
buildSlots: 0,
|
|
2453
|
+
};
|
|
2454
|
+
}
|
|
2455
|
+
function normalizedHostResourceRequest(resources) {
|
|
2456
|
+
const defaults = defaultHostResourceRequest();
|
|
2457
|
+
const workerMemoryLimitBytes = positiveResourceValue(resources?.workerMemoryLimitBytes, defaults.workerMemoryLimitBytes);
|
|
2458
|
+
const serviceMemoryLimitBytes = nonNegativeResourceValue(resources?.serviceMemoryLimitBytes, defaults.serviceMemoryLimitBytes);
|
|
2459
|
+
const runtimeOverheadBytes = nonNegativeResourceValue(resources?.runtimeOverheadBytes, defaults.runtimeOverheadBytes);
|
|
2460
|
+
return {
|
|
2461
|
+
sandboxSlots: positiveResourceValue(resources?.sandboxSlots, defaults.sandboxSlots),
|
|
2462
|
+
cpuMillis: positiveResourceValue(resources?.cpuMillis, defaults.cpuMillis),
|
|
2463
|
+
workerMemoryLimitBytes,
|
|
2464
|
+
serviceMemoryLimitBytes,
|
|
2465
|
+
runtimeOverheadBytes,
|
|
2466
|
+
memoryBytes: workerMemoryLimitBytes + serviceMemoryLimitBytes + runtimeOverheadBytes,
|
|
2467
|
+
workspaceBytes: positiveResourceValue(resources?.workspaceBytes, defaults.workspaceBytes),
|
|
2468
|
+
pids: positiveResourceValue(resources?.pids, defaults.pids),
|
|
2469
|
+
buildSlots: nonNegativeResourceValue(resources?.buildSlots, defaults.buildSlots),
|
|
2470
|
+
};
|
|
2471
|
+
}
|
|
2472
|
+
function positiveResourceValue(value, fallback) {
|
|
2473
|
+
return Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
|
|
2474
|
+
}
|
|
2475
|
+
function nonNegativeResourceValue(value, fallback) {
|
|
2476
|
+
return Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
|
|
2477
|
+
}
|
|
2478
|
+
function configuredInteger(name, fallback, minimum, maximum) {
|
|
2479
|
+
const parsed = Number.parseInt(process.env[name] ?? "", 10);
|
|
2480
|
+
return Number.isFinite(parsed) ? Math.max(minimum, Math.min(maximum, parsed)) : fallback;
|
|
2481
|
+
}
|
|
2482
|
+
/**
|
|
2483
|
+
* Today's max attempts and adaptive memory reserve for this host, before
|
|
2484
|
+
* FORGE_HOST_MAX_CONCURRENT_ATTEMPTS and FORGE_HOST_MEMORY_RESERVE_BYTES
|
|
2485
|
+
* (decision 0014 treats those as bounds on the server's values).
|
|
2486
|
+
*/
|
|
2487
|
+
export function hostCapacityLimitDefaults(capacityResourceSample) {
|
|
2488
|
+
const configuration = loadHostCapacityConfiguration(capacityResourceSample);
|
|
2489
|
+
return {
|
|
2490
|
+
maxConcurrentAttempts: configuration.defaultHardMaxAttempts,
|
|
2491
|
+
memoryReserveBytes: configuration.adaptiveHostReserveBytes,
|
|
2492
|
+
};
|
|
2493
|
+
}
|
|
2494
|
+
function loadHostCapacityConfiguration(capacityResourceSample) {
|
|
2495
|
+
const sampledCpuCount = capacityResourceSample
|
|
2496
|
+
? Math.max(1, Math.floor(capacityResourceSample.totalCpuMillis / 1_000))
|
|
2497
|
+
: os.cpus().length;
|
|
2498
|
+
const totalMemoryBytes = capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
|
|
2499
|
+
const reserveFloorBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_FLOOR_BYTES", 1024 ** 3, 512 * 1024 ** 2, 128 * 1024 ** 3);
|
|
2500
|
+
const reserveCeilingBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_CEILING_BYTES", 4 * 1024 ** 3, reserveFloorBytes, 128 * 1024 ** 3);
|
|
2501
|
+
const adaptiveOptions = {
|
|
2502
|
+
floorBytes: reserveFloorBytes,
|
|
2503
|
+
ceilingBytes: reserveCeilingBytes,
|
|
2504
|
+
percent: configuredNumber("FORGE_HOST_MEMORY_RESERVE_PERCENT", 12.5, 1, 50),
|
|
2505
|
+
};
|
|
2506
|
+
const hostReserveBytes = resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, {
|
|
2507
|
+
...adaptiveOptions,
|
|
2508
|
+
explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
|
|
2509
|
+
});
|
|
2510
|
+
const defaultHardMaxAttempts = Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2)));
|
|
2511
|
+
const idleReserveOverride = Number.parseInt(process.env.FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES ?? "", 10);
|
|
2512
|
+
const idleReserveOverrideBytes = Number.isFinite(idleReserveOverride) ? idleReserveOverride : null;
|
|
2513
|
+
return {
|
|
2514
|
+
hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", defaultHardMaxAttempts, 1, 32),
|
|
2515
|
+
hostReserveBytes,
|
|
2516
|
+
idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, { reserveFloorBytes, idleReserveOverrideBytes }),
|
|
2517
|
+
defaultHardMaxAttempts,
|
|
2518
|
+
adaptiveHostReserveBytes: resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, adaptiveOptions),
|
|
2519
|
+
reserveFloorBytes,
|
|
2520
|
+
idleReserveOverrideBytes,
|
|
2521
|
+
cpuReserveMillis: configuredInteger("FORGE_HOST_CPU_RESERVE_MILLIS", 1000, 0, 32_000),
|
|
2522
|
+
workspaceReserveBytes: configuredInteger("FORGE_HOST_WORKSPACE_RESERVE_BYTES", 10 * 1024 ** 3, 1024 ** 3, Number.MAX_SAFE_INTEGER),
|
|
2523
|
+
memoryRecoverySamples: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLES", 2, 1, 10),
|
|
2524
|
+
memoryRecoverySampleIntervalMs: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLE_INTERVAL_MS", 1_000, 100, 30_000),
|
|
2525
|
+
};
|
|
2526
|
+
}
|
|
2527
|
+
/**
|
|
2528
|
+
* The reserve kept while no attempt holds capacity: FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES
|
|
2529
|
+
* clamped to [512 MiB, reserve], else min(reserve, reserve floor). Never above the reserve.
|
|
2530
|
+
*/
|
|
2531
|
+
function idleHostReserveBytesFor(hostReserveBytes, configuration) {
|
|
2532
|
+
const fallback = Math.min(hostReserveBytes, configuration.reserveFloorBytes);
|
|
2533
|
+
const override = configuration.idleReserveOverrideBytes;
|
|
2534
|
+
return override === null ? fallback : Math.max(512 * 1024 ** 2, Math.min(hostReserveBytes, override));
|
|
2535
|
+
}
|
|
2536
|
+
function configuredOptionalInteger(name, minimum, maximum) {
|
|
2537
|
+
const raw = process.env[name];
|
|
2538
|
+
if (raw === undefined || raw.trim().length === 0)
|
|
2539
|
+
return null;
|
|
2540
|
+
const parsed = Number.parseInt(raw, 10);
|
|
2541
|
+
return Number.isFinite(parsed) ? Math.max(minimum, Math.min(maximum, parsed)) : null;
|
|
2542
|
+
}
|
|
2543
|
+
function configuredNumber(name, fallback, minimum, maximum) {
|
|
2544
|
+
const parsed = Number(process.env[name] ?? "");
|
|
2545
|
+
return Number.isFinite(parsed) && parsed > 0
|
|
2546
|
+
? Math.max(minimum, Math.min(maximum, parsed))
|
|
2547
|
+
: fallback;
|
|
2548
|
+
}
|
|
2549
|
+
function resourceSlots(available, requested) {
|
|
2550
|
+
if (requested <= 0)
|
|
2551
|
+
return Number.MAX_SAFE_INTEGER;
|
|
2552
|
+
return Math.max(0, Math.floor(available / requested));
|
|
2553
|
+
}
|
|
2554
|
+
function removeWaiter(waiters, waiter) {
|
|
2555
|
+
const index = waiters.indexOf(waiter);
|
|
2556
|
+
if (index >= 0)
|
|
2557
|
+
waiters.splice(index, 1);
|
|
2558
|
+
}
|
|
2559
|
+
function capacityProject(projects, repoId) {
|
|
2560
|
+
const normalized = repoId.trim().toLowerCase();
|
|
2561
|
+
const existing = projects.get(normalized);
|
|
2562
|
+
if (existing)
|
|
2563
|
+
return existing;
|
|
2564
|
+
const created = {
|
|
2565
|
+
repoId: normalized,
|
|
2566
|
+
safetyClass: null,
|
|
2567
|
+
activeAttempts: 0,
|
|
2568
|
+
reservedAttempts: 0,
|
|
2569
|
+
waitingAttempts: 0,
|
|
2570
|
+
degradedAttempts: 0,
|
|
2571
|
+
runtimeContractFingerprint: null,
|
|
2572
|
+
runtimeContractSource: null,
|
|
2573
|
+
promotedAt: null,
|
|
2574
|
+
};
|
|
2575
|
+
projects.set(normalized, created);
|
|
2576
|
+
return created;
|
|
2577
|
+
}
|
|
2578
|
+
function conservativeSafetyClass(left, right) {
|
|
2579
|
+
if (!left)
|
|
2580
|
+
return right;
|
|
2581
|
+
const rank = {
|
|
2582
|
+
host_serial_only: 0,
|
|
2583
|
+
host_parallel_candidate: 1,
|
|
2584
|
+
host_parallel_safe: 2,
|
|
2585
|
+
};
|
|
2586
|
+
return rank[right] < rank[left] ? right : left;
|
|
2587
|
+
}
|
|
2588
|
+
function repoIdFromProjectSingletonKeys(keys) {
|
|
2589
|
+
return keys.map(repoIdFromProjectSingletonKey).find((value) => value !== null) ?? null;
|
|
2590
|
+
}
|
|
2591
|
+
function repoIdFromProjectSingletonKey(key) {
|
|
2592
|
+
const prefix = "project:";
|
|
2593
|
+
const suffix = [":host-runtime", ":host-analysis"].find(candidate => key.endsWith(candidate));
|
|
2594
|
+
return key.startsWith(prefix) && suffix
|
|
2595
|
+
? key.slice(prefix.length, -suffix.length)
|
|
2596
|
+
: null;
|
|
2597
|
+
}
|
|
2598
|
+
function sameSingletonOwner(left, right) {
|
|
2599
|
+
return left?.dispatchAttemptId === right.dispatchAttemptId && left.fencingToken === right.fencingToken;
|
|
2600
|
+
}
|
|
2601
|
+
function hostRuntimeOwnerKey(owner) {
|
|
2602
|
+
return `${owner.dispatchAttemptId}:${owner.fencingToken}`;
|
|
2603
|
+
}
|
|
2604
|
+
function hostPortOwner(lease) {
|
|
2605
|
+
const processSupervisorId = lease.resources.processSupervisorId;
|
|
2606
|
+
if (!processSupervisorId) {
|
|
2607
|
+
throw new Error("host_runtime_adapter_invalid: process supervisor identity is required.");
|
|
2608
|
+
}
|
|
2609
|
+
return {
|
|
2610
|
+
dispatchAttemptId: lease.dispatchAttemptId,
|
|
2611
|
+
executionLeaseId: lease.executionLeaseId,
|
|
2612
|
+
fencingToken: lease.fencingToken,
|
|
2613
|
+
processSupervisorId,
|
|
2614
|
+
};
|
|
2615
|
+
}
|
|
2616
|
+
function linkedAbortController(signal) {
|
|
2617
|
+
const controller = new AbortController();
|
|
2618
|
+
if (signal?.aborted) {
|
|
2619
|
+
controller.abort(signal.reason);
|
|
2620
|
+
}
|
|
2621
|
+
else {
|
|
2622
|
+
signal?.addEventListener("abort", () => controller.abort(signal.reason), { once: true, signal: controller.signal });
|
|
2623
|
+
}
|
|
2624
|
+
return controller;
|
|
2625
|
+
}
|
|
2626
|
+
function unlinkAbortController(controller, _signal) {
|
|
2627
|
+
if (!controller.signal.aborted)
|
|
2628
|
+
controller.abort("Host adapter launch settled.");
|
|
2629
|
+
}
|
|
2630
|
+
function removeCleanup(cleanups, cleanup) {
|
|
2631
|
+
const index = cleanups.indexOf(cleanup);
|
|
2632
|
+
if (index >= 0)
|
|
2633
|
+
cleanups.splice(index, 1);
|
|
2634
|
+
}
|
|
2635
|
+
async function releaseAdapterResources(cleanups) {
|
|
2636
|
+
const pending = cleanups.splice(0);
|
|
2637
|
+
const failed = [];
|
|
2638
|
+
let firstError;
|
|
2639
|
+
for (const cleanup of pending.reverse()) {
|
|
2640
|
+
try {
|
|
2641
|
+
await cleanup();
|
|
2642
|
+
}
|
|
2643
|
+
catch (error) {
|
|
2644
|
+
firstError ??= error;
|
|
2645
|
+
failed.unshift(cleanup);
|
|
2646
|
+
}
|
|
2647
|
+
}
|
|
2648
|
+
cleanups.push(...failed);
|
|
2649
|
+
if (firstError !== undefined)
|
|
2650
|
+
throw firstError;
|
|
2651
|
+
}
|
|
2652
|
+
async function removeHostAttemptRoot(attemptRoot) {
|
|
2653
|
+
await fs.rm(attemptRoot, {
|
|
2654
|
+
recursive: true,
|
|
2655
|
+
force: true,
|
|
2656
|
+
maxRetries: 10,
|
|
2657
|
+
retryDelay: 100,
|
|
2658
|
+
});
|
|
2659
|
+
}
|
|
2660
|
+
function cancellationError(signal) {
|
|
2661
|
+
return new Error(String(signal?.reason ?? "Dispatch cancelled while waiting for host runtime singleton ownership."));
|
|
2662
|
+
}
|
|
2663
|
+
function validHostRuntimeLedger(value) {
|
|
2664
|
+
if (typeof value !== "object" || value === null)
|
|
2665
|
+
return false;
|
|
2666
|
+
const ledger = value;
|
|
2667
|
+
return ledger.schemaVersion === 1
|
|
2668
|
+
&& (ledger.repoId === undefined || /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/iu.test(ledger.repoId))
|
|
2669
|
+
&& (ledger.attemptRootIdentity === undefined
|
|
2670
|
+
|| validSerializedHostAttemptRootIdentity(ledger.attemptRootIdentity))
|
|
2671
|
+
&& validRuntimeIsolationLease(ledger.runtimeLease)
|
|
2672
|
+
&& ledger.runtimeLease.mode === "host";
|
|
2673
|
+
}
|
|
2674
|
+
function validSerializedHostAttemptRootIdentity(value) {
|
|
2675
|
+
if (typeof value !== "object" || value === null)
|
|
2676
|
+
return false;
|
|
2677
|
+
const identity = value;
|
|
2678
|
+
return /^-?\d{1,64}$/u.test(identity.dev) && /^-?\d{1,64}$/u.test(identity.ino);
|
|
2679
|
+
}
|
|
2680
|
+
function serializeHostAttemptRootIdentity(identity) {
|
|
2681
|
+
return { dev: identity.dev.toString(), ino: identity.ino.toString() };
|
|
2682
|
+
}
|
|
2683
|
+
function deserializeHostAttemptRootIdentity(identity) {
|
|
2684
|
+
return identity && validSerializedHostAttemptRootIdentity(identity)
|
|
2685
|
+
? { dev: BigInt(identity.dev), ino: BigInt(identity.ino) }
|
|
2686
|
+
: null;
|
|
2687
|
+
}
|
|
2688
|
+
function validHostProcessSupervisorMetadata(value, lease) {
|
|
2689
|
+
if (typeof value !== "object" || value === null)
|
|
2690
|
+
return false;
|
|
2691
|
+
const metadata = value;
|
|
2692
|
+
return metadata.schemaVersion === 1
|
|
2693
|
+
&& /^host-[0-9a-f]{32}$/u.test(metadata.supervisorId)
|
|
2694
|
+
&& (metadata.strategy === "windows_job_object" || metadata.strategy === "unix_process_group")
|
|
2695
|
+
&& Number.isSafeInteger(metadata.rootPid)
|
|
2696
|
+
&& metadata.rootPid > 0
|
|
2697
|
+
&& Number.isFinite(Date.parse(metadata.rootCreatedAt))
|
|
2698
|
+
&& (metadata.rootIdentity == null
|
|
2699
|
+
|| (typeof metadata.rootIdentity === "string" && metadata.rootIdentity.length <= 256))
|
|
2700
|
+
&& /^[0-9a-f]{64}$/u.test(metadata.commandDigest)
|
|
2701
|
+
&& containedMetadataWorktreePath(lease.worktreePath, metadata.worktreePath)
|
|
2702
|
+
&& metadata.runtimeLeaseId === lease.executionLeaseId
|
|
2703
|
+
&& metadata.dispatchAttemptId === lease.dispatchAttemptId
|
|
2704
|
+
&& metadata.fencingToken === lease.fencingToken
|
|
2705
|
+
&& Number.isSafeInteger(metadata.bridgePid)
|
|
2706
|
+
&& metadata.bridgePid > 0;
|
|
2707
|
+
}
|
|
2708
|
+
function containedMetadataWorktreePath(worktreePath, metadataWorktreePath) {
|
|
2709
|
+
const relative = path.relative(path.resolve(worktreePath), path.resolve(metadataWorktreePath));
|
|
2710
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
2711
|
+
}
|
|
2712
|
+
function transitionHostLeaseForCleanup(lease, state) {
|
|
2713
|
+
if (lease.state === state || lease.state === "released")
|
|
2714
|
+
return lease;
|
|
2715
|
+
return transitionRuntimeIsolationLease(lease, state);
|
|
2716
|
+
}
|
|
2717
|
+
function throwIfAdmissionExpired(expiresAt) {
|
|
2718
|
+
if (admissionExpired(expiresAt))
|
|
2719
|
+
throw new HostRuntimeAdmissionExpiredError();
|
|
2720
|
+
}
|
|
2721
|
+
function admissionExpired(expiresAt) {
|
|
2722
|
+
const deadline = Date.parse(expiresAt);
|
|
2723
|
+
return !Number.isFinite(deadline) || deadline <= Date.now();
|
|
2724
|
+
}
|
|
2725
|
+
function scheduleAdmissionDeadline(expiresAt, expire) {
|
|
2726
|
+
const delay = Math.max(0, Date.parse(expiresAt) - Date.now());
|
|
2727
|
+
const timer = setTimeout(expire, Math.min(delay, 2_147_483_647));
|
|
2728
|
+
timer.unref?.();
|
|
2729
|
+
return timer;
|
|
2730
|
+
}
|
|
2731
|
+
function clearAdmissionDeadline(waiter) {
|
|
2732
|
+
if (waiter.deadlineTimer)
|
|
2733
|
+
clearTimeout(waiter.deadlineTimer);
|
|
2734
|
+
waiter.deadlineTimer = null;
|
|
2735
|
+
}
|
|
2736
|
+
function clearCapacityRecheck(waiter) {
|
|
2737
|
+
if (waiter.capacityRecheckTimer)
|
|
2738
|
+
clearInterval(waiter.capacityRecheckTimer);
|
|
2739
|
+
waiter.capacityRecheckTimer = null;
|
|
2740
|
+
}
|
|
2741
|
+
async function ensurePrivateDirectory(directory) {
|
|
2742
|
+
await fs.mkdir(directory, { recursive: true, mode: 0o700 });
|
|
2743
|
+
if (process.platform !== "win32")
|
|
2744
|
+
await fs.chmod(directory, 0o700);
|
|
2745
|
+
}
|
|
2746
|
+
async function containedWorkingDirectory(worktreePath, configuredDirectory) {
|
|
2747
|
+
const [realWorktree, realDirectory] = await Promise.all([
|
|
2748
|
+
fs.realpath(worktreePath),
|
|
2749
|
+
fs.realpath(path.resolve(worktreePath, configuredDirectory)),
|
|
2750
|
+
]);
|
|
2751
|
+
const relative = path.relative(realWorktree, realDirectory);
|
|
2752
|
+
if (relative.startsWith("..") || path.isAbsolute(relative)) {
|
|
2753
|
+
throw new Error("host_runtime_project_invalid: launch working directory must remain inside the prepared worktree.");
|
|
2754
|
+
}
|
|
2755
|
+
return realDirectory;
|
|
2756
|
+
}
|
|
2757
|
+
function uuidHex(value, label) {
|
|
2758
|
+
const normalized = value.replaceAll("-", "").toLowerCase();
|
|
2759
|
+
if (!/^[0-9a-f]{32}$/u.test(normalized)) {
|
|
2760
|
+
throw new Error(`host_runtime_lease_invalid: ${label} id must be a full UUID.`);
|
|
2761
|
+
}
|
|
2762
|
+
return normalized;
|
|
2763
|
+
}
|