@mcoda/mswarm 0.1.133 → 0.1.135-codali.10
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 +44 -0
- package/dist/codali-executor.d.ts +79 -1
- package/dist/codali-executor.d.ts.map +1 -1
- package/dist/codali-executor.js +115 -8
- package/dist/codali-executor.js.map +1 -1
- package/dist/invocation-token.d.ts.map +1 -1
- package/dist/invocation-token.js +1 -0
- package/dist/invocation-token.js.map +1 -1
- package/dist/native-reasoning.d.ts +8 -0
- package/dist/native-reasoning.d.ts.map +1 -0
- package/dist/native-reasoning.js +18 -0
- package/dist/native-reasoning.js.map +1 -0
- package/dist/runtime.d.ts +25 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +226 -22
- package/dist/runtime.js.map +1 -1
- package/dist/server.d.ts +3 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +58 -8
- package/dist/server.js.map +1 -1
- package/dist/vendor/codali/agents/RoleResolution.d.ts.map +1 -1
- package/dist/vendor/codali/agents/RoleResolution.js +4 -4
- package/dist/vendor/codali/api/CodaliApi.d.ts +16 -0
- package/dist/vendor/codali/api/CodaliApi.d.ts.map +1 -1
- package/dist/vendor/codali/api/CodaliApi.js +39 -10
- package/dist/vendor/codali/cli/AskCommand.d.ts +3 -0
- package/dist/vendor/codali/cli/AskCommand.d.ts.map +1 -1
- package/dist/vendor/codali/cli/AskCommand.js +76 -13
- package/dist/vendor/codali/cli/RunCommand.d.ts +4 -0
- package/dist/vendor/codali/cli/RunCommand.d.ts.map +1 -1
- package/dist/vendor/codali/cli/RunCommand.js +110 -24
- package/dist/vendor/codali/cli/TerminalCommand.d.ts +35 -0
- package/dist/vendor/codali/cli/TerminalCommand.d.ts.map +1 -0
- package/dist/vendor/codali/cli/TerminalCommand.js +618 -0
- package/dist/vendor/codali/cli/TerminalCredentials.d.ts +3 -0
- package/dist/vendor/codali/cli/TerminalCredentials.d.ts.map +1 -0
- package/dist/vendor/codali/cli/TerminalCredentials.js +89 -0
- package/dist/vendor/codali/cli/TerminalInput.d.ts +24 -0
- package/dist/vendor/codali/cli/TerminalInput.d.ts.map +1 -0
- package/dist/vendor/codali/cli/TerminalInput.js +98 -0
- package/dist/vendor/codali/cli/TerminalText.d.ts +10 -0
- package/dist/vendor/codali/cli/TerminalText.d.ts.map +1 -0
- package/dist/vendor/codali/cli/TerminalText.js +53 -0
- package/dist/vendor/codali/cli.d.ts.map +1 -1
- package/dist/vendor/codali/cli.js +33 -4
- package/dist/vendor/codali/cognitive/ConfiguredPipeline.d.ts +34 -0
- package/dist/vendor/codali/cognitive/ConfiguredPipeline.d.ts.map +1 -0
- package/dist/vendor/codali/cognitive/ConfiguredPipeline.js +50 -0
- package/dist/vendor/codali/cognitive/ValidationRunner.d.ts +4 -0
- package/dist/vendor/codali/cognitive/ValidationRunner.d.ts.map +1 -1
- package/dist/vendor/codali/cognitive/ValidationRunner.js +18 -41
- package/dist/vendor/codali/config/NodeOrchestration.d.ts +21 -0
- package/dist/vendor/codali/config/NodeOrchestration.d.ts.map +1 -0
- package/dist/vendor/codali/config/NodeOrchestration.js +54 -0
- package/dist/vendor/codali/config/OrchestrationConfig.d.ts +100 -0
- package/dist/vendor/codali/config/OrchestrationConfig.d.ts.map +1 -0
- package/dist/vendor/codali/config/OrchestrationConfig.js +245 -0
- package/dist/vendor/codali/connectors/mcp/McpClient.d.ts +3 -1
- package/dist/vendor/codali/connectors/mcp/McpClient.d.ts.map +1 -1
- package/dist/vendor/codali/connectors/mcp/McpClient.js +3 -2
- package/dist/vendor/codali/connectors/mcp/McpServerRegistry.d.ts +2 -2
- package/dist/vendor/codali/connectors/mcp/McpServerRegistry.d.ts.map +1 -1
- package/dist/vendor/codali/connectors/mcp/McpServerRegistry.js +39 -16
- package/dist/vendor/codali/connectors/mcp/McpToolAdapter.js +2 -2
- package/dist/vendor/codali/connectors/media/ConfiguredMediaTools.d.ts +6 -0
- package/dist/vendor/codali/connectors/media/ConfiguredMediaTools.d.ts.map +1 -0
- package/dist/vendor/codali/connectors/media/ConfiguredMediaTools.js +41 -0
- package/dist/vendor/codali/connectors/media/ImageGenerationTool.js +3 -3
- package/dist/vendor/codali/connectors/media/MediaArtifactReceipt.d.ts +5 -0
- package/dist/vendor/codali/connectors/media/MediaArtifactReceipt.d.ts.map +1 -0
- package/dist/vendor/codali/connectors/media/MediaArtifactReceipt.js +65 -0
- package/dist/vendor/codali/connectors/media/MediaJobStore.d.ts +68 -0
- package/dist/vendor/codali/connectors/media/MediaJobStore.d.ts.map +1 -0
- package/dist/vendor/codali/connectors/media/MediaJobStore.js +199 -0
- package/dist/vendor/codali/connectors/media/MediaJobWorker.d.ts +2 -0
- package/dist/vendor/codali/connectors/media/MediaJobWorker.d.ts.map +1 -0
- package/dist/vendor/codali/connectors/media/MediaJobWorker.js +65 -0
- package/dist/vendor/codali/connectors/media/RemoteMediaJob.d.ts +6 -0
- package/dist/vendor/codali/connectors/media/RemoteMediaJob.d.ts.map +1 -0
- package/dist/vendor/codali/connectors/media/RemoteMediaJob.js +80 -0
- package/dist/vendor/codali/docdex/DocdexClient.d.ts +18 -1
- package/dist/vendor/codali/docdex/DocdexClient.d.ts.map +1 -1
- package/dist/vendor/codali/docdex/DocdexClient.js +135 -19
- package/dist/vendor/codali/docdex/ManagedDocdex.d.ts +29 -0
- package/dist/vendor/codali/docdex/ManagedDocdex.d.ts.map +1 -0
- package/dist/vendor/codali/docdex/ManagedDocdex.js +215 -0
- package/dist/vendor/codali/docdex/ManagedRuntime.d.ts +28 -0
- package/dist/vendor/codali/docdex/ManagedRuntime.d.ts.map +1 -0
- package/dist/vendor/codali/docdex/ManagedRuntime.js +212 -0
- package/dist/vendor/codali/eval/EvaluationProcess.d.ts +13 -0
- package/dist/vendor/codali/eval/EvaluationProcess.d.ts.map +1 -0
- package/dist/vendor/codali/eval/EvaluationProcess.js +76 -0
- package/dist/vendor/codali/eval/LongWorkflowJourney.d.ts +34 -0
- package/dist/vendor/codali/eval/LongWorkflowJourney.d.ts.map +1 -0
- package/dist/vendor/codali/eval/LongWorkflowJourney.js +243 -0
- package/dist/vendor/codali/eval/PlanningCorpus.d.ts +45 -0
- package/dist/vendor/codali/eval/PlanningCorpus.d.ts.map +1 -0
- package/dist/vendor/codali/eval/PlanningCorpus.js +189 -0
- package/dist/vendor/codali/eval/PlanningCorpusRunner.d.ts +13 -0
- package/dist/vendor/codali/eval/PlanningCorpusRunner.d.ts.map +1 -0
- package/dist/vendor/codali/eval/PlanningCorpusRunner.js +89 -0
- package/dist/vendor/codali/eval/TerminalCorpusRunner.d.ts +36 -0
- package/dist/vendor/codali/eval/TerminalCorpusRunner.d.ts.map +1 -0
- package/dist/vendor/codali/eval/TerminalCorpusRunner.js +222 -0
- package/dist/vendor/codali/eval/TerminalTaskCorpus.d.ts +26 -0
- package/dist/vendor/codali/eval/TerminalTaskCorpus.d.ts.map +1 -0
- package/dist/vendor/codali/eval/TerminalTaskCorpus.js +105 -0
- package/dist/vendor/codali/eval/TerminalWorkflowCorpus.d.ts +11 -0
- package/dist/vendor/codali/eval/TerminalWorkflowCorpus.d.ts.map +1 -0
- package/dist/vendor/codali/eval/TerminalWorkflowCorpus.js +119 -0
- package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.d.ts +4 -0
- package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.d.ts.map +1 -0
- package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.js +10 -0
- package/dist/vendor/codali/eval/fixtures/MixedMediaRecoveryJourney.d.ts +6 -0
- package/dist/vendor/codali/eval/fixtures/MixedMediaRecoveryJourney.d.ts.map +1 -0
- package/dist/vendor/codali/eval/fixtures/MixedMediaRecoveryJourney.js +145 -0
- package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.d.ts +4 -0
- package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.d.ts.map +1 -0
- package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.js +136 -0
- package/dist/vendor/codali/gateway/CodaliGateway.d.ts +2 -0
- package/dist/vendor/codali/gateway/CodaliGateway.d.ts.map +1 -1
- package/dist/vendor/codali/gateway/CodaliGateway.js +16 -4
- package/dist/vendor/codali/gateway/ConfiguredGateway.d.ts +23 -0
- package/dist/vendor/codali/gateway/ConfiguredGateway.d.ts.map +1 -0
- package/dist/vendor/codali/gateway/ConfiguredGateway.js +44 -0
- package/dist/vendor/codali/gateway/GatewayTracer.d.ts +1 -1
- package/dist/vendor/codali/gateway/GatewayTracer.d.ts.map +1 -1
- package/dist/vendor/codali/gateway/GatewayTracer.js +2 -27
- package/dist/vendor/codali/gateway/LocalGatewayTaskRunner.d.ts.map +1 -1
- package/dist/vendor/codali/gateway/LocalGatewayTaskRunner.js +13 -1
- package/dist/vendor/codali/index.d.ts +24 -0
- package/dist/vendor/codali/index.d.ts.map +1 -1
- package/dist/vendor/codali/index.js +13 -0
- package/dist/vendor/codali/permissions/PermissionGate.d.ts +44 -0
- package/dist/vendor/codali/permissions/PermissionGate.d.ts.map +1 -0
- package/dist/vendor/codali/permissions/PermissionGate.js +97 -0
- package/dist/vendor/codali/providers/ConfiguredEmbeddings.d.ts +43 -0
- package/dist/vendor/codali/providers/ConfiguredEmbeddings.d.ts.map +1 -0
- package/dist/vendor/codali/providers/ConfiguredEmbeddings.js +87 -0
- package/dist/vendor/codali/providers/ConfiguredModelScope.d.ts +70 -0
- package/dist/vendor/codali/providers/ConfiguredModelScope.d.ts.map +1 -0
- package/dist/vendor/codali/providers/ConfiguredModelScope.js +117 -0
- package/dist/vendor/codali/providers/ConfiguredProvider.d.ts +84 -0
- package/dist/vendor/codali/providers/ConfiguredProvider.d.ts.map +1 -0
- package/dist/vendor/codali/providers/ConfiguredProvider.js +271 -0
- package/dist/vendor/codali/providers/ModelServiceError.d.ts +14 -0
- package/dist/vendor/codali/providers/ModelServiceError.d.ts.map +1 -0
- package/dist/vendor/codali/providers/ModelServiceError.js +67 -0
- package/dist/vendor/codali/providers/MswarmWorkerProvider.d.ts.map +1 -1
- package/dist/vendor/codali/providers/MswarmWorkerProvider.js +4 -0
- package/dist/vendor/codali/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
- package/dist/vendor/codali/providers/OpenAiCompatibleProvider.js +140 -52
- package/dist/vendor/codali/providers/ProviderTypes.d.ts +16 -0
- package/dist/vendor/codali/providers/ProviderTypes.d.ts.map +1 -1
- package/dist/vendor/codali/providers/RequestUsage.d.ts +11 -0
- package/dist/vendor/codali/providers/RequestUsage.d.ts.map +1 -0
- package/dist/vendor/codali/providers/RequestUsage.js +33 -0
- package/dist/vendor/codali/runtime/CodaliJobRuntime.d.ts +6 -0
- package/dist/vendor/codali/runtime/CodaliJobRuntime.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/CodaliJobRuntime.js +36 -1
- package/dist/vendor/codali/runtime/CodaliRuntime.d.ts +31 -0
- package/dist/vendor/codali/runtime/CodaliRuntime.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/CodaliRuntime.js +72 -1
- package/dist/vendor/codali/runtime/CompletionReport.d.ts +5 -0
- package/dist/vendor/codali/runtime/CompletionReport.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/CompletionReport.js +12 -0
- package/dist/vendor/codali/runtime/ProgressTracker.d.ts +17 -0
- package/dist/vendor/codali/runtime/ProgressTracker.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/ProgressTracker.js +27 -0
- package/dist/vendor/codali/runtime/RequestedTestEvidence.d.ts +12 -0
- package/dist/vendor/codali/runtime/RequestedTestEvidence.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/RequestedTestEvidence.js +16 -0
- package/dist/vendor/codali/runtime/RequiredRetrieval.d.ts +13 -0
- package/dist/vendor/codali/runtime/RequiredRetrieval.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/RequiredRetrieval.js +25 -0
- package/dist/vendor/codali/runtime/ReviewContract.d.ts +35 -0
- package/dist/vendor/codali/runtime/ReviewContract.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/ReviewContract.js +131 -0
- package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts +41 -0
- package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/ReviewCoordinator.js +81 -0
- package/dist/vendor/codali/runtime/ReviewSource.d.ts +9 -0
- package/dist/vendor/codali/runtime/ReviewSource.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/ReviewSource.js +54 -0
- package/dist/vendor/codali/runtime/Runner.d.ts +13 -0
- package/dist/vendor/codali/runtime/Runner.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/Runner.js +225 -158
- package/dist/vendor/codali/runtime/SecretRedaction.d.ts +11 -0
- package/dist/vendor/codali/runtime/SecretRedaction.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/SecretRedaction.js +85 -0
- package/dist/vendor/codali/runtime/SessionController.d.ts +150 -0
- package/dist/vendor/codali/runtime/SessionController.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/SessionController.js +1487 -0
- package/dist/vendor/codali/runtime/StructuralEvidence.d.ts +22 -0
- package/dist/vendor/codali/runtime/StructuralEvidence.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/StructuralEvidence.js +87 -0
- package/dist/vendor/codali/runtime/TaskReview.d.ts +25 -0
- package/dist/vendor/codali/runtime/TaskReview.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/TaskReview.js +84 -0
- package/dist/vendor/codali/runtime/TaskReviewContext.d.ts +71 -0
- package/dist/vendor/codali/runtime/TaskReviewContext.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/TaskReviewContext.js +50 -0
- package/dist/vendor/codali/runtime/UsageReconciliation.d.ts +28 -0
- package/dist/vendor/codali/runtime/UsageReconciliation.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/UsageReconciliation.js +68 -0
- package/dist/vendor/codali/runtime/ValidationOutput.d.ts +5 -0
- package/dist/vendor/codali/runtime/ValidationOutput.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/ValidationOutput.js +32 -0
- package/dist/vendor/codali/runtime/VerificationCommand.d.ts +5 -0
- package/dist/vendor/codali/runtime/VerificationCommand.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/VerificationCommand.js +76 -0
- package/dist/vendor/codali/runtime/VerificationReceiptSelection.d.ts +15 -0
- package/dist/vendor/codali/runtime/VerificationReceiptSelection.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/VerificationReceiptSelection.js +30 -0
- package/dist/vendor/codali/runtime/WorkStatusPage.d.ts +15 -0
- package/dist/vendor/codali/runtime/WorkStatusPage.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/WorkStatusPage.js +58 -0
- package/dist/vendor/codali/runtime/WorkspaceLedger.d.ts +13 -0
- package/dist/vendor/codali/runtime/WorkspaceLedger.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/WorkspaceLedger.js +145 -0
- package/dist/vendor/codali/runtime/WorkspaceLock.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/WorkspaceLock.js +20 -17
- package/dist/vendor/codali/runtime/WorkspaceSnapshot.d.ts +13 -0
- package/dist/vendor/codali/runtime/WorkspaceSnapshot.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/WorkspaceSnapshot.js +88 -0
- package/dist/vendor/codali/session/AtomicState.d.ts +13 -0
- package/dist/vendor/codali/session/AtomicState.d.ts.map +1 -0
- package/dist/vendor/codali/session/AtomicState.js +123 -0
- package/dist/vendor/codali/session/SessionStoragePath.d.ts +15 -0
- package/dist/vendor/codali/session/SessionStoragePath.d.ts.map +1 -0
- package/dist/vendor/codali/session/SessionStoragePath.js +101 -0
- package/dist/vendor/codali/session/SessionStore.d.ts +9 -0
- package/dist/vendor/codali/session/SessionStore.d.ts.map +1 -1
- package/dist/vendor/codali/session/SessionStore.js +181 -47
- package/dist/vendor/codali/session/WorkState.d.ts +32 -0
- package/dist/vendor/codali/session/WorkState.d.ts.map +1 -0
- package/dist/vendor/codali/session/WorkState.js +399 -0
- package/dist/vendor/codali/session/WorkTypes.d.ts +102 -0
- package/dist/vendor/codali/session/WorkTypes.d.ts.map +1 -0
- package/dist/vendor/codali/session/WorkTypes.js +1 -0
- package/dist/vendor/codali/tools/ToolRegistry.d.ts +2 -0
- package/dist/vendor/codali/tools/ToolRegistry.d.ts.map +1 -1
- package/dist/vendor/codali/tools/ToolRegistry.js +12 -2
- package/dist/vendor/codali/tools/ToolTypes.d.ts +16 -0
- package/dist/vendor/codali/tools/ToolTypes.d.ts.map +1 -1
- package/dist/vendor/codali/tools/docdex/DocdexTools.d.ts +2 -0
- package/dist/vendor/codali/tools/docdex/DocdexTools.d.ts.map +1 -1
- package/dist/vendor/codali/tools/docdex/DocdexTools.js +17 -2
- package/dist/vendor/codali/tools/filesystem/FileTools.d.ts.map +1 -1
- package/dist/vendor/codali/tools/filesystem/FileTools.js +30 -10
- package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts +19 -0
- package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts.map +1 -0
- package/dist/vendor/codali/tools/shell/AsyncProcess.js +94 -0
- package/dist/vendor/codali/tools/shell/DarwinRuntimeLibraries.d.ts +13 -0
- package/dist/vendor/codali/tools/shell/DarwinRuntimeLibraries.d.ts.map +1 -0
- package/dist/vendor/codali/tools/shell/DarwinRuntimeLibraries.js +130 -0
- package/dist/vendor/codali/tools/shell/HostToolchain.d.ts +19 -0
- package/dist/vendor/codali/tools/shell/HostToolchain.d.ts.map +1 -0
- package/dist/vendor/codali/tools/shell/HostToolchain.js +266 -0
- package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts +15 -0
- package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts.map +1 -0
- package/dist/vendor/codali/tools/shell/IsolatedExecutor.js +138 -0
- package/dist/vendor/codali/tools/shell/ShellTool.d.ts.map +1 -1
- package/dist/vendor/codali/tools/shell/ShellTool.js +9 -29
- package/dist/vendor/codali/tools/shell/ShellWorkingDirectory.d.ts +3 -0
- package/dist/vendor/codali/tools/shell/ShellWorkingDirectory.d.ts.map +1 -0
- package/dist/vendor/codali/tools/shell/ShellWorkingDirectory.js +30 -0
- package/package.json +31 -29
- package/scripts/backend-http-drain.mjs +152 -0
- package/scripts/media_gpu_lock.py +238 -0
- package/scripts/native_load_guard.py +257 -0
- package/scripts/stable-audio-3-openai-server.py +45 -14
- package/scripts/stable-diffusion-cpp-openai-server.py +34 -4
- package/scripts/stable-diffusion-cpp-webm-duration.patch +22 -0
- package/scripts/wan22-openai-server.py +97 -18
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Operator bootstrap for legacy HTTP services without a shutdown handler.
|
|
4
|
+
* Run inside the target container against its loopback Node inspector only.
|
|
5
|
+
* This is not a public administration endpoint. Qualification must pin the
|
|
6
|
+
* runtime/image and prove both request completion and durable-job quiescence.
|
|
7
|
+
*/
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { resolve } from 'node:path';
|
|
10
|
+
|
|
11
|
+
// Self-contained because the inspector evaluates this function in the target.
|
|
12
|
+
export function controlHttpAdmission({ action, role, port, nonce, expectedPid }) {
|
|
13
|
+
if (!['gateway', 'proxy'].includes(role) || !Number.isInteger(port) || port < 1 || port > 65535 ||
|
|
14
|
+
!/^[a-zA-Z0-9-]{16,100}$/.test(nonce) || expectedPid !== process.pid ||
|
|
15
|
+
!['inspect', 'barrier', 'status', 'close', 'restore'].includes(action)) {
|
|
16
|
+
throw new Error('Invalid or mismatched deployment target');
|
|
17
|
+
}
|
|
18
|
+
const key = Symbol.for('mcoda.backend.http-drain.v1');
|
|
19
|
+
let state = globalThis[key];
|
|
20
|
+
if (state?.phase === 'restored' && action === 'barrier') {
|
|
21
|
+
delete globalThis[key];
|
|
22
|
+
state = undefined;
|
|
23
|
+
}
|
|
24
|
+
const snapshot = () => ({
|
|
25
|
+
nonce: state.nonce, role: state.role, port: state.port, pid: process.pid,
|
|
26
|
+
phase: state.phase, blockedRequests: state.blockedRequests,
|
|
27
|
+
controlRequests: state.controlRequests, installedAt: state.installedAt,
|
|
28
|
+
closedAt: state.closedAt, closeError: state.closeError,
|
|
29
|
+
listening: state.server.listening,
|
|
30
|
+
});
|
|
31
|
+
if (state && (state.nonce !== nonce || state.port !== port || state.role !== role)) {
|
|
32
|
+
throw new Error('Another deployment owns this process');
|
|
33
|
+
}
|
|
34
|
+
if (!state) {
|
|
35
|
+
if (!['inspect', 'barrier'].includes(action)) throw new Error('No admission barrier is installed');
|
|
36
|
+
// Legacy bootstrap only: the inspected runtime's HTTP handle shape must be
|
|
37
|
+
// qualified before deployment. Fail closed on additional/bypassing handlers.
|
|
38
|
+
const servers = process._getActiveHandles().filter((handle) =>
|
|
39
|
+
handle?.constructor?.name === 'Server' && typeof handle.address === 'function' &&
|
|
40
|
+
handle.address()?.port === port && typeof handle.closeIdleConnections === 'function');
|
|
41
|
+
if (servers.length !== 1) throw new Error('Expected exactly one qualified HTTP server');
|
|
42
|
+
const server = servers[0];
|
|
43
|
+
const listeners = server.listeners('request');
|
|
44
|
+
if (action === 'inspect') return { nonce, role, port, pid: process.pid, phase: 'unmodified',
|
|
45
|
+
runtimeVersion: process.version, listening: server.listening, requestListeners: listeners.length,
|
|
46
|
+
alternateListeners: Object.fromEntries(['checkContinue', 'checkExpectation', 'upgrade'].map((name) => [name, server.listenerCount(name)])) };
|
|
47
|
+
if (listeners.length !== 1 || ['checkContinue', 'checkExpectation', 'upgrade'].some((name) => server.listenerCount(name))) {
|
|
48
|
+
throw new Error('Unsupported HTTP request dispatch; no listener changed');
|
|
49
|
+
}
|
|
50
|
+
state = { nonce, role, port, server, listeners, address: server.address(),
|
|
51
|
+
phase: 'barrier', installedAt: Date.now(), blockedRequests: 0, controlRequests: 0 };
|
|
52
|
+
const controlPath = /^\/v1\/swarm\/self-hosted\/node\/(?:heartbeat|load|models|jobs\/poll|jobs\/[A-Za-z0-9_-]+\/(?:start|events|result))$/;
|
|
53
|
+
state.listener = function (request, response) {
|
|
54
|
+
const pathname = (request.url ?? '').split('?')[0];
|
|
55
|
+
const health = request.method === 'GET' && pathname === '/healthz';
|
|
56
|
+
if (health || (state.role === 'gateway' && request.method === 'POST' && controlPath.test(pathname))) {
|
|
57
|
+
state.controlRequests++;
|
|
58
|
+
for (const listener of state.listeners) listener.call(this, request, response);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
state.blockedRequests++;
|
|
62
|
+
response.shouldKeepAlive = false;
|
|
63
|
+
response.writeHead(503, { 'content-type': 'application/json', 'retry-after': '15', connection: 'close' });
|
|
64
|
+
response.end(JSON.stringify({ error: { code: 'deployment_draining', message: 'Service deployment is draining; retry shortly.' } }));
|
|
65
|
+
request.resume();
|
|
66
|
+
};
|
|
67
|
+
globalThis[key] = state;
|
|
68
|
+
server.removeListener('request', listeners[0]);
|
|
69
|
+
server.on('request', state.listener);
|
|
70
|
+
}
|
|
71
|
+
if (action === 'inspect' || action === 'barrier' || action === 'status') return snapshot();
|
|
72
|
+
if (action === 'close') {
|
|
73
|
+
if (state.phase === 'barrier') {
|
|
74
|
+
state.phase = 'closing';
|
|
75
|
+
// Never close active connections. The callback proves every HTTP request
|
|
76
|
+
// has finished; the operator separately checks durable queue records.
|
|
77
|
+
state.server.close((error) => {
|
|
78
|
+
clearInterval(state.idleReaper);
|
|
79
|
+
state.closeError = error ? String(error.message) : undefined;
|
|
80
|
+
state.phase = error ? 'close_failed' : 'closed';
|
|
81
|
+
state.closedAt = Date.now();
|
|
82
|
+
});
|
|
83
|
+
state.server.closeIdleConnections();
|
|
84
|
+
// A response accepted before the barrier can become idle after close()
|
|
85
|
+
// starts. Reap only idle sockets as those responses finish.
|
|
86
|
+
state.idleReaper = setInterval(() => state.server.closeIdleConnections(), 100);
|
|
87
|
+
state.idleReaper.unref();
|
|
88
|
+
}
|
|
89
|
+
return snapshot();
|
|
90
|
+
}
|
|
91
|
+
if (state.phase === 'closing' || state.phase === 'close_failed') throw new Error('HTTP close has not completed');
|
|
92
|
+
if (state.phase === 'closed') {
|
|
93
|
+
state.phase = 'restoring';
|
|
94
|
+
state.server.listen({ port: state.port, host: state.address.address }, () => {
|
|
95
|
+
state.server.removeListener('request', state.listener);
|
|
96
|
+
for (const listener of state.listeners) state.server.on('request', listener);
|
|
97
|
+
state.phase = 'restored';
|
|
98
|
+
});
|
|
99
|
+
} else if (state.phase === 'barrier') {
|
|
100
|
+
state.server.removeListener('request', state.listener);
|
|
101
|
+
for (const listener of state.listeners) state.server.on('request', listener);
|
|
102
|
+
state.phase = 'restored';
|
|
103
|
+
}
|
|
104
|
+
return snapshot();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export async function inspectorControl(options) {
|
|
108
|
+
const inspectorPort = options.inspectorPort ?? 9229;
|
|
109
|
+
if (!Number.isInteger(inspectorPort) || inspectorPort < 1 || inspectorPort > 65535) throw new Error('Invalid inspector port');
|
|
110
|
+
if (typeof WebSocket !== 'function') throw new Error('Use Node20 with --experimental-websocket, or Node22');
|
|
111
|
+
const response = await fetch(`http://127.0.0.1:${inspectorPort}/json/list`, { signal: AbortSignal.timeout(5000), redirect: 'error' });
|
|
112
|
+
if (!response.ok) throw new Error(`Inspector discovery failed: ${response.status}`);
|
|
113
|
+
const targets = await response.json();
|
|
114
|
+
if (!Array.isArray(targets) || targets.length !== 1) throw new Error('Inspector target is ambiguous');
|
|
115
|
+
const endpoint = new URL(targets[0].webSocketDebuggerUrl);
|
|
116
|
+
if (endpoint.protocol !== 'ws:' || endpoint.hostname !== '127.0.0.1' || Number(endpoint.port) !== inspectorPort || endpoint.username || endpoint.password) {
|
|
117
|
+
throw new Error('Inspector must remain on the selected container loopback port');
|
|
118
|
+
}
|
|
119
|
+
const socket = new WebSocket(endpoint.href);
|
|
120
|
+
return await new Promise((resolveResult, reject) => {
|
|
121
|
+
const timeout = setTimeout(() => finish(new Error('Inspector operation timed out')), 10_000);
|
|
122
|
+
let finished = false;
|
|
123
|
+
function finish(error, value) {
|
|
124
|
+
if (finished) return;
|
|
125
|
+
finished = true;
|
|
126
|
+
clearTimeout(timeout);
|
|
127
|
+
try { socket.close(); } catch { /* Preserve the original failure. */ }
|
|
128
|
+
if (error) reject(error); else resolveResult(value);
|
|
129
|
+
}
|
|
130
|
+
socket.addEventListener('error', () => finish(new Error('Inspector connection failed')));
|
|
131
|
+
socket.addEventListener('close', () => { if (!finished) finish(new Error('Inspector disconnected')); });
|
|
132
|
+
socket.addEventListener('open', () => socket.send(JSON.stringify({ id: 1, method: 'Runtime.evaluate', params: {
|
|
133
|
+
expression: `(${controlHttpAdmission.toString()})(${JSON.stringify(options)})`, returnByValue: true,
|
|
134
|
+
} })));
|
|
135
|
+
socket.addEventListener('message', ({ data }) => {
|
|
136
|
+
try {
|
|
137
|
+
const message = JSON.parse(String(data));
|
|
138
|
+
if (message.id !== 1) return;
|
|
139
|
+
if (message.error || message.result?.exceptionDetails) return finish(new Error('Target rejected drain operation: ' + JSON.stringify(message.error ?? message.result.exceptionDetails)));
|
|
140
|
+
const value = message.result?.result?.value;
|
|
141
|
+
if (!value || value.pid !== options.expectedPid || value.nonce !== options.nonce) return finish(new Error('Invalid target drain receipt'));
|
|
142
|
+
finish(undefined, value);
|
|
143
|
+
} catch (error) { finish(error); }
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
149
|
+
const options = JSON.parse(process.argv[2] ?? '{}');
|
|
150
|
+
try { console.log(JSON.stringify(await inspectorControl(options))); }
|
|
151
|
+
catch (error) { console.error(error.message); process.exitCode = 1; }
|
|
152
|
+
}
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"""Serialize GPU1 media inference across the independent HTTP services."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import fcntl
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import math
|
|
9
|
+
import os
|
|
10
|
+
import stat
|
|
11
|
+
import threading
|
|
12
|
+
import time
|
|
13
|
+
import uuid
|
|
14
|
+
from contextlib import contextmanager
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Callable, Iterator
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class MediaGpuError(RuntimeError):
|
|
20
|
+
status = 503
|
|
21
|
+
code = "media_gpu_unavailable"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class MediaGpuBusy(MediaGpuError):
|
|
25
|
+
status = 429
|
|
26
|
+
code = "media_gpu_busy"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class MediaGpuCancelled(MediaGpuError):
|
|
30
|
+
code = "service_shutting_down"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class MediaGpuRecoveryRequired(MediaGpuError):
|
|
34
|
+
code = "media_gpu_recovery_required"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _open_scheduler(lock_path: str | None = None) -> int:
|
|
38
|
+
runtime_dir = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}"))
|
|
39
|
+
path = lock_path or os.environ.get("MCODA_MEDIA_GPU_LOCK_PATH", str(runtime_dir / "mcoda-media-gpu1.lock"))
|
|
40
|
+
fd = -1
|
|
41
|
+
try:
|
|
42
|
+
fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_CLOEXEC | os.O_NOFOLLOW, 0o600)
|
|
43
|
+
metadata = os.fstat(fd)
|
|
44
|
+
if (not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != os.geteuid()
|
|
45
|
+
or metadata.st_nlink != 1 or stat.S_IMODE(metadata.st_mode) & 0o077):
|
|
46
|
+
os.close(fd)
|
|
47
|
+
raise MediaGpuError("shared media GPU lock must be a private, owner-owned regular file")
|
|
48
|
+
return fd
|
|
49
|
+
except OSError as error:
|
|
50
|
+
if fd >= 0:
|
|
51
|
+
os.close(fd)
|
|
52
|
+
raise MediaGpuError("cannot access the shared media GPU scheduler") from error
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _read_lease(fd: int) -> dict | None:
|
|
56
|
+
raw = os.pread(fd, 16_385, 0)
|
|
57
|
+
if not raw:
|
|
58
|
+
return None
|
|
59
|
+
try:
|
|
60
|
+
if len(raw) > 16_384:
|
|
61
|
+
raise ValueError("oversized lease")
|
|
62
|
+
value = json.loads(raw)
|
|
63
|
+
if (not isinstance(value, dict) or value.get("version") != 1
|
|
64
|
+
or not isinstance(value.get("id"), str)
|
|
65
|
+
or value.get("status") not in ("active", "uncertain")):
|
|
66
|
+
raise ValueError("invalid lease")
|
|
67
|
+
return value
|
|
68
|
+
except (ValueError, UnicodeDecodeError) as error:
|
|
69
|
+
raise MediaGpuRecoveryRequired("media GPU lease is unreadable; reconcile native inference before recovery") from error
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _write_lease(fd: int, value: dict | None) -> None:
|
|
73
|
+
data = b"" if value is None else json.dumps(value, separators=(",", ":")).encode("utf-8")
|
|
74
|
+
os.lseek(fd, 0, os.SEEK_SET)
|
|
75
|
+
offset = 0
|
|
76
|
+
while offset < len(data):
|
|
77
|
+
written = os.write(fd, data[offset:])
|
|
78
|
+
if written <= 0:
|
|
79
|
+
raise MediaGpuError("cannot persist the shared media GPU lease")
|
|
80
|
+
offset += written
|
|
81
|
+
os.ftruncate(fd, len(data))
|
|
82
|
+
os.fsync(fd)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class MediaGpuLease:
|
|
86
|
+
"""Host-owned receipt; never store prompts, credentials or client URLs."""
|
|
87
|
+
|
|
88
|
+
def __init__(self, fd: int, label: str):
|
|
89
|
+
self._fd = fd
|
|
90
|
+
self._closed = False
|
|
91
|
+
self._uncertain = False
|
|
92
|
+
self.record = {"version": 1, "id": str(uuid.uuid4()), "status": "active",
|
|
93
|
+
"label": label[:128], "pid": os.getpid(), "started_at": time.time()}
|
|
94
|
+
_write_lease(fd, self.record)
|
|
95
|
+
|
|
96
|
+
def mark_uncertain(self, reason: str) -> None:
|
|
97
|
+
if self._closed:
|
|
98
|
+
raise MediaGpuError("media GPU lease is already closed")
|
|
99
|
+
self._uncertain = True
|
|
100
|
+
self.record.update(status="uncertain", reason=reason[:128])
|
|
101
|
+
_write_lease(self._fd, self.record)
|
|
102
|
+
|
|
103
|
+
def record_native_job(self, job_id: str) -> None:
|
|
104
|
+
if self._closed or not isinstance(job_id, str) or not job_id or len(job_id) > 256:
|
|
105
|
+
raise MediaGpuError("invalid native media job receipt")
|
|
106
|
+
self.record["native_job_id"] = job_id
|
|
107
|
+
_write_lease(self._fd, self.record)
|
|
108
|
+
|
|
109
|
+
def record_native_process(self, pid: int) -> None:
|
|
110
|
+
"""Pin a Linux native child's identity without recording its arguments."""
|
|
111
|
+
if self._closed or not isinstance(pid, int) or pid <= 0:
|
|
112
|
+
raise MediaGpuError("invalid native media process receipt")
|
|
113
|
+
try:
|
|
114
|
+
fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()
|
|
115
|
+
boot_id = Path("/proc/sys/kernel/random/boot_id").read_text().strip()
|
|
116
|
+
if int(fields[2]) != pid or not boot_id:
|
|
117
|
+
raise ValueError("native process must own its process group")
|
|
118
|
+
identity = {"pid": pid, "process_group": pid,
|
|
119
|
+
"start_ticks": int(fields[19]), "boot_id": boot_id}
|
|
120
|
+
except (OSError, ValueError, IndexError) as error:
|
|
121
|
+
raise MediaGpuError("cannot establish native media process identity") from error
|
|
122
|
+
self.record["native_process"] = identity
|
|
123
|
+
_write_lease(self._fd, self.record)
|
|
124
|
+
|
|
125
|
+
def confirm_finished(self) -> None:
|
|
126
|
+
if self._closed:
|
|
127
|
+
raise MediaGpuError("media GPU lease is already closed")
|
|
128
|
+
self._uncertain = False
|
|
129
|
+
self.record.update(status="active")
|
|
130
|
+
self.record.pop("reason", None)
|
|
131
|
+
_write_lease(self._fd, self.record)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def reconcile_media_gpu_slot(expected_id: str, terminal_probe: Callable[[dict], bool]) -> bool:
|
|
135
|
+
"""Clear one abandoned receipt only after a trusted backend terminal probe.
|
|
136
|
+
|
|
137
|
+
Process death, elapsed time, HTTP disconnection and a cancel acknowledgement
|
|
138
|
+
are not terminal proof. The caller supplies a backend-specific probe or
|
|
139
|
+
evidence that the native engine was stopped and cannot retain that job.
|
|
140
|
+
"""
|
|
141
|
+
fd = _open_scheduler()
|
|
142
|
+
try:
|
|
143
|
+
try:
|
|
144
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
145
|
+
except BlockingIOError as error:
|
|
146
|
+
raise MediaGpuBusy("media GPU lease is still owned by a running worker") from error
|
|
147
|
+
current = _read_lease(fd)
|
|
148
|
+
if current is None or current["id"] != expected_id:
|
|
149
|
+
return False
|
|
150
|
+
if terminal_probe(dict(current)) is not True:
|
|
151
|
+
return False
|
|
152
|
+
_write_lease(fd, None)
|
|
153
|
+
return True
|
|
154
|
+
finally:
|
|
155
|
+
os.close(fd)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def media_gpu_health() -> str:
|
|
159
|
+
"""Report admission state without exposing a receipt or clearing uncertainty."""
|
|
160
|
+
fd = -1
|
|
161
|
+
try:
|
|
162
|
+
fd = _open_scheduler()
|
|
163
|
+
try:
|
|
164
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
165
|
+
except BlockingIOError:
|
|
166
|
+
return "busy"
|
|
167
|
+
return "ready" if _read_lease(fd) is None else "recovery_required"
|
|
168
|
+
except MediaGpuRecoveryRequired:
|
|
169
|
+
return "recovery_required"
|
|
170
|
+
except MediaGpuError:
|
|
171
|
+
return "unavailable"
|
|
172
|
+
finally:
|
|
173
|
+
if fd >= 0:
|
|
174
|
+
os.close(fd)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@contextmanager
|
|
178
|
+
def media_gpu_slot(
|
|
179
|
+
label: str, *, cancelled: threading.Event | None = None,
|
|
180
|
+
shutdown: threading.Event | None = None,
|
|
181
|
+
) -> Iterator[MediaGpuLease]:
|
|
182
|
+
"""Hold a kernel lock until native inference finishes, even if a client leaves.
|
|
183
|
+
|
|
184
|
+
Never unlink the lock file: waiters must keep referring to the same inode.
|
|
185
|
+
Each call opens its own file description so threads also exclude each other.
|
|
186
|
+
"""
|
|
187
|
+
try:
|
|
188
|
+
timeout = float(os.environ.get("MCODA_MEDIA_GPU_WAIT_SECONDS", "600"))
|
|
189
|
+
except ValueError as error:
|
|
190
|
+
raise MediaGpuError("media GPU wait limit must be a number") from error
|
|
191
|
+
if not math.isfinite(timeout) or timeout < 0:
|
|
192
|
+
raise MediaGpuError("media GPU wait limit must be finite and nonnegative")
|
|
193
|
+
fd = _open_scheduler()
|
|
194
|
+
acquired = False
|
|
195
|
+
lease: MediaGpuLease | None = None
|
|
196
|
+
started = time.monotonic()
|
|
197
|
+
try:
|
|
198
|
+
while True:
|
|
199
|
+
if any(event is not None and event.is_set() for event in (cancelled, shutdown)):
|
|
200
|
+
raise MediaGpuCancelled("media generation stopped while waiting for the GPU")
|
|
201
|
+
try:
|
|
202
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
203
|
+
acquired = True
|
|
204
|
+
break
|
|
205
|
+
except BlockingIOError:
|
|
206
|
+
remaining = timeout - (time.monotonic() - started)
|
|
207
|
+
if remaining <= 0:
|
|
208
|
+
raise MediaGpuBusy("the media GPU is busy; retry the request")
|
|
209
|
+
if cancelled is not None:
|
|
210
|
+
cancelled.wait(min(0.1, remaining))
|
|
211
|
+
else:
|
|
212
|
+
time.sleep(min(0.1, remaining))
|
|
213
|
+
if any(event is not None and event.is_set() for event in (cancelled, shutdown)):
|
|
214
|
+
raise MediaGpuCancelled("media generation stopped before GPU inference")
|
|
215
|
+
if _read_lease(fd) is not None:
|
|
216
|
+
raise MediaGpuRecoveryRequired("an earlier media GPU lease has no confirmed outcome; reconcile native inference before retrying")
|
|
217
|
+
lease = MediaGpuLease(fd, label)
|
|
218
|
+
logging.info(
|
|
219
|
+
"media_gpu_acquired label=%s pid=%d wait_ms=%d monotonic=%.6f",
|
|
220
|
+
label, os.getpid(), int((time.monotonic() - started) * 1000), time.monotonic(),
|
|
221
|
+
)
|
|
222
|
+
yield lease
|
|
223
|
+
finally:
|
|
224
|
+
try:
|
|
225
|
+
if acquired:
|
|
226
|
+
if lease is not None:
|
|
227
|
+
try:
|
|
228
|
+
if not lease._uncertain:
|
|
229
|
+
_write_lease(fd, None)
|
|
230
|
+
finally:
|
|
231
|
+
lease._closed = True
|
|
232
|
+
logging.info(
|
|
233
|
+
"media_gpu_released label=%s pid=%d monotonic=%.6f",
|
|
234
|
+
label, os.getpid(), time.monotonic(),
|
|
235
|
+
)
|
|
236
|
+
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
237
|
+
finally:
|
|
238
|
+
os.close(fd)
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""Opt-in Linux host RAM admission for native model loading and recovery.
|
|
2
|
+
|
|
3
|
+
The embedding runtime must confirm model readiness or confirmed process death
|
|
4
|
+
before leaving the context. Unknown outcomes retain the shared media fence.
|
|
5
|
+
This module never dispatches or replays inference.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import logging
|
|
11
|
+
import math
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import stat
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
import urllib.request
|
|
20
|
+
from urllib.parse import urlsplit
|
|
21
|
+
from contextlib import contextmanager
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
try:
|
|
25
|
+
from .media_gpu_lock import _open_scheduler, _read_lease, _write_lease, MediaGpuLease, MediaGpuError
|
|
26
|
+
except ImportError:
|
|
27
|
+
from media_gpu_lock import _open_scheduler, _read_lease, _write_lease, MediaGpuLease, MediaGpuError
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class NativeLoadError(RuntimeError):
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
_local = threading.local()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def read_policy(path: str) -> dict:
|
|
38
|
+
if not isinstance(path, str) or not os.path.isabs(path):
|
|
39
|
+
raise NativeLoadError("native load policy must be an absolute file path")
|
|
40
|
+
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC)
|
|
41
|
+
try:
|
|
42
|
+
info = os.fstat(fd)
|
|
43
|
+
if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid()
|
|
44
|
+
or info.st_nlink != 1 or stat.S_IMODE(info.st_mode) & 0o077):
|
|
45
|
+
raise NativeLoadError("native load policy must be a private, owner-owned regular file")
|
|
46
|
+
data = os.read(fd, 32769)
|
|
47
|
+
if len(data) > 32768:
|
|
48
|
+
raise NativeLoadError("native load policy is too large")
|
|
49
|
+
policy = json.loads(data)
|
|
50
|
+
finally:
|
|
51
|
+
os.close(fd)
|
|
52
|
+
fields = {"schemaVersion", "lockPath", "waitSeconds", "minAvailableMiB",
|
|
53
|
+
"restoreReserveMiB", "serviceTimeoutSeconds", "services"}
|
|
54
|
+
if not isinstance(policy, dict) or set(policy) != fields or type(policy["schemaVersion"]) is not int or policy["schemaVersion"] != 1:
|
|
55
|
+
raise NativeLoadError("unsupported native load policy fields or version")
|
|
56
|
+
if not isinstance(policy["lockPath"], str) or not os.path.isabs(policy["lockPath"]):
|
|
57
|
+
raise NativeLoadError("native load policy requires an absolute shared lock path")
|
|
58
|
+
for key in ("waitSeconds", "minAvailableMiB", "restoreReserveMiB", "serviceTimeoutSeconds"):
|
|
59
|
+
value = policy[key]
|
|
60
|
+
if type(value) not in (int, float) or not math.isfinite(value) or value <= 0:
|
|
61
|
+
raise NativeLoadError(f"native load policy {key} must be finite and positive")
|
|
62
|
+
if key.endswith("Seconds") and value > 3600:
|
|
63
|
+
raise NativeLoadError(f"native load policy {key} exceeds one hour")
|
|
64
|
+
peers = policy["services"]
|
|
65
|
+
if not isinstance(peers, list) or len(peers) > 16:
|
|
66
|
+
raise NativeLoadError("native load policy services must be a bounded array")
|
|
67
|
+
seen = set()
|
|
68
|
+
for peer in peers:
|
|
69
|
+
if (not isinstance(peer, dict) or set(peer) != {"unit", "restoreMiB", "readyUrl"}
|
|
70
|
+
or not isinstance(peer["unit"], str)
|
|
71
|
+
or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.@-]{0,240}\.service", peer["unit"])
|
|
72
|
+
or peer["unit"] in seen or type(peer["restoreMiB"]) is not int or peer["restoreMiB"] <= 0):
|
|
73
|
+
raise NativeLoadError("invalid or duplicate native load peer")
|
|
74
|
+
url = urlsplit(peer["readyUrl"]) if isinstance(peer["readyUrl"], str) else None
|
|
75
|
+
if (url is None or url.scheme != "http" or url.hostname not in ("127.0.0.1", "::1")
|
|
76
|
+
or url.username or url.password or url.fragment):
|
|
77
|
+
raise NativeLoadError("native load peer readiness must use credential-free loopback HTTP")
|
|
78
|
+
seen.add(peer["unit"])
|
|
79
|
+
return policy
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def available_mib() -> int:
|
|
83
|
+
try:
|
|
84
|
+
for line in Path("/proc/meminfo").read_text().splitlines():
|
|
85
|
+
if line.startswith("MemAvailable:"):
|
|
86
|
+
fields = line.split()
|
|
87
|
+
if len(fields) == 3 and fields[2] == "kB":
|
|
88
|
+
return int(fields[1]) // 1024
|
|
89
|
+
except (OSError, ValueError):
|
|
90
|
+
pass
|
|
91
|
+
raise NativeLoadError("available host RAM cannot be measured")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def service_state(unit: str, timeout: float) -> str:
|
|
95
|
+
try:
|
|
96
|
+
result = subprocess.run(["/usr/bin/systemctl", "--user", "show", unit,
|
|
97
|
+
"--property=LoadState", "--property=ActiveState"],
|
|
98
|
+
check=True, capture_output=True, text=True, timeout=timeout)
|
|
99
|
+
except (OSError, subprocess.SubprocessError) as error:
|
|
100
|
+
raise NativeLoadError(f"cannot inspect native load peer: {unit}") from error
|
|
101
|
+
values = dict(line.split("=", 1) for line in result.stdout.splitlines() if "=" in line)
|
|
102
|
+
if values.get("LoadState") != "loaded":
|
|
103
|
+
raise NativeLoadError(f"configured native load peer is not loaded: {unit}")
|
|
104
|
+
return values.get("ActiveState", "unknown")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def service_action(action: str, unit: str, timeout: float) -> None:
|
|
108
|
+
try:
|
|
109
|
+
subprocess.run(["/usr/bin/systemctl", "--user", action, unit],
|
|
110
|
+
check=True, stdin=subprocess.DEVNULL, capture_output=True, timeout=timeout)
|
|
111
|
+
except (OSError, subprocess.SubprocessError) as error:
|
|
112
|
+
raise NativeLoadError(f"cannot {action} native load peer: {unit}") from error
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def wait_ready(peer: dict, timeout: float) -> None:
|
|
116
|
+
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
117
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
118
|
+
return None
|
|
119
|
+
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
|
|
120
|
+
deadline = time.monotonic() + timeout
|
|
121
|
+
while time.monotonic() < deadline:
|
|
122
|
+
try:
|
|
123
|
+
with opener.open(peer["readyUrl"], timeout=min(2, max(.01, deadline - time.monotonic()))) as response:
|
|
124
|
+
if response.status == 200:
|
|
125
|
+
return
|
|
126
|
+
except (OSError, ValueError):
|
|
127
|
+
pass
|
|
128
|
+
if service_state(peer["unit"], min(5, timeout)) not in ("active", "activating"):
|
|
129
|
+
raise NativeLoadError(f"native load peer stopped during restoration: {peer['unit']}")
|
|
130
|
+
time.sleep(min(.1, max(0, deadline - time.monotonic())))
|
|
131
|
+
raise NativeLoadError(f"native load peer readiness timed out: {peer['unit']}")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class NativeLoadLease:
|
|
135
|
+
def __init__(self, record: MediaGpuLease):
|
|
136
|
+
self.record = record
|
|
137
|
+
self.outcome = None
|
|
138
|
+
|
|
139
|
+
def confirm_ready(self) -> None:
|
|
140
|
+
self.outcome = "ready"
|
|
141
|
+
|
|
142
|
+
def confirm_stopped(self) -> None:
|
|
143
|
+
self.outcome = "stopped"
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _restore(policy: dict, parked: list[dict]) -> None:
|
|
147
|
+
errors = []
|
|
148
|
+
for peer in parked:
|
|
149
|
+
try:
|
|
150
|
+
needed = policy["restoreReserveMiB"] + peer["restoreMiB"]
|
|
151
|
+
if available_mib() < needed:
|
|
152
|
+
raise NativeLoadError(f"insufficient host RAM to restore {peer['unit']}")
|
|
153
|
+
service_action("start", peer["unit"], policy["serviceTimeoutSeconds"])
|
|
154
|
+
if service_state(peer["unit"], policy["serviceTimeoutSeconds"]) != "active":
|
|
155
|
+
raise NativeLoadError(f"native load peer did not become active: {peer['unit']}")
|
|
156
|
+
wait_ready(peer, policy["serviceTimeoutSeconds"])
|
|
157
|
+
except Exception as error:
|
|
158
|
+
# Preserve the other original peers when one cannot restart.
|
|
159
|
+
errors.append(error)
|
|
160
|
+
if errors:
|
|
161
|
+
raise NativeLoadError("native load peer restoration failed; retain the admission fence") from errors[0]
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
@contextmanager
|
|
165
|
+
def native_load_guard(env: dict | None):
|
|
166
|
+
"""Use MCODA_NATIVE_LOAD_POLICY from trusted host configuration only.
|
|
167
|
+
|
|
168
|
+
The caller must have stopped its old model process before entering. Nested
|
|
169
|
+
retries in the same thread retain one lease; other threads/processes wait.
|
|
170
|
+
No configured policy means no lock, filesystem, systemctl or RAM probes.
|
|
171
|
+
"""
|
|
172
|
+
path = (env or {}).get("MCODA_NATIVE_LOAD_POLICY")
|
|
173
|
+
if path is None:
|
|
174
|
+
yield None
|
|
175
|
+
return
|
|
176
|
+
active = getattr(_local, "active", None)
|
|
177
|
+
if active is not None:
|
|
178
|
+
if active[0] != path:
|
|
179
|
+
raise NativeLoadError("cannot nest different native load policies")
|
|
180
|
+
active[1].outcome = None
|
|
181
|
+
yield active[1]
|
|
182
|
+
return
|
|
183
|
+
import fcntl
|
|
184
|
+
try:
|
|
185
|
+
policy = read_policy(path)
|
|
186
|
+
fd = _open_scheduler(policy["lockPath"])
|
|
187
|
+
except (OSError, ValueError, MediaGpuError) as error:
|
|
188
|
+
raise NativeLoadError("cannot open the native load policy or shared lease") from error
|
|
189
|
+
record = None
|
|
190
|
+
parked = []
|
|
191
|
+
entered_model = False
|
|
192
|
+
completed = False
|
|
193
|
+
try:
|
|
194
|
+
deadline = time.monotonic() + policy["waitSeconds"]
|
|
195
|
+
while True:
|
|
196
|
+
try:
|
|
197
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
198
|
+
break
|
|
199
|
+
except BlockingIOError as error:
|
|
200
|
+
if time.monotonic() >= deadline:
|
|
201
|
+
raise NativeLoadError("active media still owns the native load lease") from error
|
|
202
|
+
time.sleep(min(0.1, max(0, deadline - time.monotonic())))
|
|
203
|
+
try:
|
|
204
|
+
previous = _read_lease(fd)
|
|
205
|
+
except MediaGpuError as error:
|
|
206
|
+
raise NativeLoadError("shared native/media lease is unreadable; reconciliation is required") from error
|
|
207
|
+
if previous is not None:
|
|
208
|
+
raise NativeLoadError("an earlier native/media outcome must be reconciled before model loading")
|
|
209
|
+
record = MediaGpuLease(fd, "native-model-load")
|
|
210
|
+
lease = NativeLoadLease(record)
|
|
211
|
+
_local.active = (path, lease)
|
|
212
|
+
for peer in policy["services"]:
|
|
213
|
+
state = service_state(peer["unit"], policy["serviceTimeoutSeconds"])
|
|
214
|
+
if state in ("inactive", "failed"):
|
|
215
|
+
continue
|
|
216
|
+
if state != "active":
|
|
217
|
+
raise NativeLoadError(f"native load peer is changing state: {peer['unit']}")
|
|
218
|
+
# Record before stop: a timed-out stop may still complete.
|
|
219
|
+
parked.append(peer)
|
|
220
|
+
record.record["parked_units"] = [item["unit"] for item in parked]
|
|
221
|
+
_write_lease(fd, record.record)
|
|
222
|
+
service_action("stop", peer["unit"], policy["serviceTimeoutSeconds"])
|
|
223
|
+
if service_state(peer["unit"], policy["serviceTimeoutSeconds"]) != "inactive":
|
|
224
|
+
raise NativeLoadError(f"native load peer has not stopped: {peer['unit']}")
|
|
225
|
+
free = available_mib()
|
|
226
|
+
if free < policy["minAvailableMiB"]:
|
|
227
|
+
raise NativeLoadError(f"native model needs {policy['minAvailableMiB']} MiB available RAM; measured {free}")
|
|
228
|
+
logging.info("native_model_load_admitted available_mib=%d parked_peers=%d", free, len(parked))
|
|
229
|
+
entered_model = True
|
|
230
|
+
try:
|
|
231
|
+
yield lease
|
|
232
|
+
finally:
|
|
233
|
+
# A dead caller or an unconfirmed model process must never admit
|
|
234
|
+
# concurrent media. Keep a durable receipt for native reconciliation.
|
|
235
|
+
if lease.outcome is not None:
|
|
236
|
+
record.mark_uncertain("native_model_peer_restore_pending")
|
|
237
|
+
_restore(policy, parked)
|
|
238
|
+
completed = True
|
|
239
|
+
_write_lease(fd, None)
|
|
240
|
+
else:
|
|
241
|
+
record.mark_uncertain("native_model_load_outcome_unknown")
|
|
242
|
+
if sys.exc_info()[0] is None:
|
|
243
|
+
raise NativeLoadError("native model load returned without readiness or process-death proof")
|
|
244
|
+
finally:
|
|
245
|
+
try:
|
|
246
|
+
if record is not None and not entered_model:
|
|
247
|
+
record.mark_uncertain("native_model_peer_restore_pending")
|
|
248
|
+
_restore(policy, parked)
|
|
249
|
+
completed = True
|
|
250
|
+
_write_lease(fd, None)
|
|
251
|
+
if record is not None and not completed:
|
|
252
|
+
record.mark_uncertain("native_model_load_or_restore_unconfirmed")
|
|
253
|
+
finally:
|
|
254
|
+
if record is not None:
|
|
255
|
+
record._closed = True
|
|
256
|
+
_local.active = None
|
|
257
|
+
os.close(fd)
|