diff --git a/docs/api.md b/docs/api.md index d8d7a8ed..14d69b81 100644 --- a/docs/api.md +++ b/docs/api.md @@ -17,7 +17,7 @@ Worker-group list/get responses retain `workerIds` for direct membership and add Container responses distinguish durable `desiredRuntimeStatus` (`running`/`stopped`) from the current Docker observation. Besides normal states, `starting`, `recovering`, and `unknown` may be returned; `unknown` carries only a safe retryable runtime diagnostic. `POST /api/containers/:id/recover` is the bounded, owner/lock-checked recovery endpoint for an unresponsive worker: persistent mounts are verified, only the disposable container is replaced, managed secrets are bootstrapped, and desired plugins are reconciled. It returns 409 when persistence cannot be verified and 503 when Docker cannot yet clear stale runtime state; it never removes persistent volumes. Management MCP provides the equivalent `workers.recover` tool and projects only structured safe diagnostics (code, operation/phase, retryability, timeout, and preservation state), never Docker command text, environment values, or credentials. -`POST /api/containers/:id/emergency-stop` accepts `{"confirmed":true,"lockPassword":""}` and force-stops existing ordinary or administrative compute without a graceful shutdown. The authenticated owner or administrator may stop an ordinary or group administrative worker; platform administrative workspaces require an administrator. Incus uses a forced stop and Docker sends SIGKILL directly, retaining Docker's manual-stop restart-policy behavior. Persistent storage is retained, but unsaved work may be lost. Stale or unknown health does not prevent an ownership-verified attempt. Pending target lifecycle operations return 409; owner/setup serialization and unresolved recovery fences remain in effect. A missing administrative workspace is never provisioned by this endpoint. +`POST /api/containers/:id/emergency-stop` accepts `{"confirmed":true,"lockPassword":""}` and force-stops existing ordinary or administrative compute without a graceful shutdown. The authenticated owner or administrator may stop an ordinary or group administrative worker; platform administrative workspaces require an administrator. Incus uses a forced stop and Docker sends SIGKILL directly, retaining Docker's manual-stop restart-policy behavior. Persistent storage is retained, but unsaved work may be lost. Stale or unknown health does not prevent an ownership-verified attempt. Stopped intent is saved even when observed state is unknown or another lifecycle request is pending. Runtime mutations remain serialized; an unconfirmed shutdown returns a bounded failure while the stop stays queued behind unresolved mutations. Success requires authoritative shutdown confirmation. A missing administrative workspace is never provisioned by this endpoint. `POST /api/archived/:id/unarchive` accepts an optional explicit catalog recovery choice: @@ -126,3 +126,18 @@ Saving backup settings first copies each additional directory into an Agentor-ma ## All API Routes API routes return JSON unless their OpenAPI metadata explicitly documents a streaming or binary response/body (for example worker import, export artifacts, and workspace downloads). Full interactive reference is at `/api/docs` (Scalar UI) and raw spec at `/api/docs/openapi.json`. + + +### Recovery policy and requested runtime state + +- `GET /api/containers/:id/recovery` reads the durable `maxRetries`, `attempts`, `paused`, safe `lastFailure`, and desired runtime state without guest probing. +- `PUT /api/containers/:id/recovery` accepts `{"maxRetries":3,"lockPassword":""}`. The default is three automatic retries after an explicit start; `0` disables them. Values must be integers from 0 to 100, keeping automatic recovery finite. Changing the limit retains the attempt count and never starts compute. +- `PUT /api/containers/:id/desired-state` accepts `{"desiredRuntimeStatus":"stopped","confirmed":true,"lockPassword":""}` (or `running`). It persists intent even if actual state cannot be observed. The response carries a warning: intent does not confirm that compute started or stopped. Explicit running intent resets the recovery counter; ordinary runtime authorization and storage/identity preflight still apply when reconciliation acts. + +Automatic retry claims are persisted before attempting recovery. Exhaustion survives orchestrator restarts, stops further automatic startup attempts, and leaves persistent storage untouched. A verified successful recovery or explicit Start/Retry resets the counter. Failed probes alone never authorize a reboot. Emergency stop saves stopped intent before waiting for existing runtime mutations; a late startup cannot erase that intent. Unknown shutdown results remain unknown until the backend confirms stop. Exact runtime identity and unresolved mutation fences are retained, so emergency acceptance is not permission to act on foreign or unproven compute. + +The worker settings panel exposes these controls with a warning acknowledgement. Cards show exhausted retry budgets. Official logs report accepted intent, attempt/limit, safe failing phase and exit code, exhausted budgets, cleanup outcomes, and confirmed versus unconfirmed emergency stops. Raw guest stderr and secret values are excluded. + +Management MCP exposes `workers.recovery.get`, `workers.recovery.set`, `workers.desired-state.set`, and `workers.emergency-stop` to platform administrators and to group administrators for ordinary workers in their live group subtree. The state and emergency tools require `confirmed:true`; mutation tools enforce worker protection locks. `admin-workspace.emergency-stop` is platform-only and requires the exact `workerId`. `groups.admin-workspace.emergency-stop` accepts an authorized `groupId`, confirmation, and any required lock password; it can target the bound group or a descendant, and never provisions a missing administrative workspace. Group membership and hierarchy are rechecked when executing, so sibling, ungrouped, foreign-owner and platform-administrative workers remain outside group scope. + +Guest GPU driver installation/repair remains the guest administrator's responsibility. A shared guest udev wait causing unrelated storage preparation to fail is a separate hypothesis requiring disposable reproduction; these controls do not replace drivers or weaken storage validation. diff --git a/orchestrator/app/components/ContainerCard.vue b/orchestrator/app/components/ContainerCard.vue index 99cf4be1..13b4b9b4 100644 --- a/orchestrator/app/components/ContainerCard.vue +++ b/orchestrator/app/components/ContainerCard.vue @@ -137,6 +137,9 @@ function onHScrollWheel(e: WheelEvent) { +

+ Automatic recovery paused ({{ container.recovery.attempts }}/{{ container.recovery.maxRetries }}). Open settings to retry. +

{
+ +
+import { UNKNOWN_STATE_WARNING, type WorkerRecoveryState } from '../../shared/worker-recovery'; +const props = defineProps<{ workerId: string }>(); +const state = ref(); +const maxRetries = ref(3), busy = ref(false), confirmed = ref(false), password = ref(''), needsPassword = ref(false), error = ref(''), outcome = ref(''); +async function refresh() { + state.value = await $fetch(`/api/containers/${encodeURIComponent(props.workerId)}/recovery`); + maxRetries.value = state.value!.maxRetries; +} +onMounted(() => refresh().catch(() => { error.value = 'Recovery status is unavailable. Retry opening settings.'; })); +async function change(desiredRuntimeStatus?: 'running' | 'stopped') { + busy.value = true; error.value = ''; outcome.value = ''; + try { + const result = await $fetch(`/api/containers/${encodeURIComponent(props.workerId)}/${desiredRuntimeStatus ? 'desired-state' : 'recovery'}`, { + method: 'PUT', retry: 0, timeout: 20_000, + body: { ...(desiredRuntimeStatus ? { desiredRuntimeStatus, confirmed: confirmed.value } : { maxRetries: Number(maxRetries.value) }), lockPassword: password.value }, + }); + outcome.value = desiredRuntimeStatus ? `Requested ${result.desiredRuntimeStatus}; runtime confirmation is pending.` : 'Retry limit saved; attempt count retained.'; + await refresh(); await refreshNuxtData('workers'); + } catch (cause: any) { + needsPassword.value ||= (cause?.statusCode ?? cause?.response?.status) === 423; + error.value = cause?.data?.statusMessage || cause?.data?.message || 'Change could not be confirmed. Refresh status before retrying.'; + } finally { busy.value = false; password.value = ''; } +} + + + diff --git a/orchestrator/server/api/containers/[id]/desired-state.put.ts b/orchestrator/server/api/containers/[id]/desired-state.put.ts new file mode 100644 index 00000000..5ef58d91 --- /dev/null +++ b/orchestrator/server/api/containers/[id]/desired-state.put.ts @@ -0,0 +1,22 @@ +defineRouteMeta({ openAPI: { + tags: ['Containers'], summary: 'Set desired runtime state', operationId: 'setWorkerDesiredState', + description: 'Persist desiredRuntimeStatus running or stopped with confirmed true, even when observation is unknown. Warning: intent does not confirm runtime state. Protection locks apply.', + parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }], + responses: { 200: { description: 'Requested policy or intent; observed runtime state is independent' }, 400: { description: 'Invalid retry limit, desired state or missing confirmation' }, 403: { description: 'Access denied' }, 404: { description: 'Worker not found' }, 423: { description: 'Protection lock required' } }, +} }); + +import { requireContainerAccess } from '../../../utils/auth-helpers'; +import { useContainerManager } from '../../../utils/services'; +import { useWorkerProtectionLockStore } from '../../../utils/worker-protection-lock'; +import { rethrowAsHttpError } from '../../../utils/http-errors'; + +export default defineEventHandler(async event => { + try { + const id = getRouterParam(event, 'id')!, manager = useContainerManager(); + requireContainerAccess(event, manager.get(id)); + const body = await readBody(event); + await useWorkerProtectionLockStore().verify(id, body?.lockPassword); + if (body?.confirmed !== true) throw createError({ statusCode: 400, statusMessage: 'Confirm the warning: changing desired state does not confirm runtime state' }); + return await manager.setDesiredState(id, body?.desiredRuntimeStatus); + } catch (error) { rethrowAsHttpError(error); } +}); diff --git a/orchestrator/server/api/containers/[id]/emergency-stop.post.ts b/orchestrator/server/api/containers/[id]/emergency-stop.post.ts index 61531ee3..45ab5f06 100644 --- a/orchestrator/server/api/containers/[id]/emergency-stop.post.ts +++ b/orchestrator/server/api/containers/[id]/emergency-stop.post.ts @@ -2,7 +2,7 @@ defineRouteMeta({ openAPI: { tags: ['Containers'], summary: 'Emergency stop a worker', - description: 'Immediately force-stops the existing worker without a graceful shutdown. Requires explicit confirmation and the protection-lock password when protected. Administrative workspaces retain their dedicated authorization. Pending lifecycle or recovery operations must settle before this action is allowed.', + description: 'Immediately force-stops the existing worker without a graceful shutdown. Requires explicit confirmation and the protection-lock password when protected. Administrative workspaces retain their dedicated authorization. Requests are accepted while lifecycle status is unknown; stopped intent is retained while pending runtime operations settle.', operationId: 'emergencyStopContainer', parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }], requestBody: { required: true, content: { 'application/json': { schema: { @@ -30,7 +30,6 @@ import { useWorkerProtectionLockStore } from '../../../utils/worker-protection-l import { readAdministrativeRuntimeRecord } from '../../../utils/admin-native-authority'; import { useAdminWorkspaceStore } from '../../../utils/admin-workspace-store'; import { useGroupAdminWorkspaceStore, type GroupAdministrativeWorkspaceRecord } from '../../../utils/group-admin-workspace-store'; -import { isWorkerLifecycleMutationPending } from '../../../utils/worker-lifecycle-coordinator'; import { rethrowAsHttpError } from '../../../utils/http-errors'; export default defineEventHandler(async (event) => { @@ -48,8 +47,6 @@ export default defineEventHandler(async (event) => { if (body?.confirmed !== true) throw createError({ statusCode: 400, statusMessage: 'Explicit confirmation is required for emergency stop' }); await useWorkerProtectionLockStore().verify(id, body.lockPassword); - if (isWorkerLifecycleMutationPending(id)) - throw createError({ statusCode: 409, statusMessage: 'Worker lifecycle operation is still pending; refresh status before retrying emergency stop' }); if (administrative?.kind === 'administrative') await useAdminWorkspaceStore().setStatus('stopped', true, id); else if (administrative) { const groupId = (administrative as GroupAdministrativeWorkspaceRecord).groupId; diff --git a/orchestrator/server/api/containers/[id]/recovery.get.ts b/orchestrator/server/api/containers/[id]/recovery.get.ts new file mode 100644 index 00000000..1d2a5f60 --- /dev/null +++ b/orchestrator/server/api/containers/[id]/recovery.get.ts @@ -0,0 +1,19 @@ +defineRouteMeta({ openAPI: { + tags: ['Containers'], summary: 'Get recovery status', operationId: 'getWorkerRecovery', + description: 'Read durable retry policy, attempt count and safe last failure without runtime probing.', + parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }], + responses: { 200: { description: 'Requested policy or intent; observed runtime state is independent' }, 400: { description: 'Invalid retry limit, desired state or missing confirmation' }, 403: { description: 'Access denied' }, 404: { description: 'Worker not found' }, 423: { description: 'Protection lock required' } }, +} }); + +import { requireContainerAccess } from '../../../utils/auth-helpers'; +import { useContainerManager } from '../../../utils/services'; +import { useWorkerProtectionLockStore } from '../../../utils/worker-protection-lock'; +import { rethrowAsHttpError } from '../../../utils/http-errors'; + +export default defineEventHandler(async event => { + try { + const id = getRouterParam(event, 'id')!, manager = useContainerManager(); + requireContainerAccess(event, manager.get(id)); + return await manager.getRecovery(id); + } catch (error) { rethrowAsHttpError(error); } +}); diff --git a/orchestrator/server/api/containers/[id]/recovery.put.ts b/orchestrator/server/api/containers/[id]/recovery.put.ts new file mode 100644 index 00000000..4eb5be1a --- /dev/null +++ b/orchestrator/server/api/containers/[id]/recovery.put.ts @@ -0,0 +1,21 @@ +defineRouteMeta({ openAPI: { + tags: ['Containers'], summary: 'Set recovery retry limit', operationId: 'setWorkerRecovery', + description: 'Set maxRetries from 0 to 100; zero disables automatic retries. Attempts are retained and no runtime action is requested.', + parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }], + responses: { 200: { description: 'Requested policy or intent; observed runtime state is independent' }, 400: { description: 'Invalid retry limit, desired state or missing confirmation' }, 403: { description: 'Access denied' }, 404: { description: 'Worker not found' }, 423: { description: 'Protection lock required' } }, +} }); + +import { requireContainerAccess } from '../../../utils/auth-helpers'; +import { useContainerManager } from '../../../utils/services'; +import { useWorkerProtectionLockStore } from '../../../utils/worker-protection-lock'; +import { rethrowAsHttpError } from '../../../utils/http-errors'; + +export default defineEventHandler(async event => { + try { + const id = getRouterParam(event, 'id')!, manager = useContainerManager(); + requireContainerAccess(event, manager.get(id)); + const body = await readBody(event); + await useWorkerProtectionLockStore().verify(id, body?.lockPassword); + return await manager.setRecovery(id, body?.maxRetries); + } catch (error) { rethrowAsHttpError(error); } +}); diff --git a/orchestrator/server/utils/admin-workspace-store.ts b/orchestrator/server/utils/admin-workspace-store.ts index 1b173367..6286f926 100644 --- a/orchestrator/server/utils/admin-workspace-store.ts +++ b/orchestrator/server/utils/admin-workspace-store.ts @@ -4,7 +4,7 @@ import { isDeepStrictEqual } from 'node:util'; import { createHash, randomUUID } from "node:crypto"; import { lstat, mkdir, readFile, rename, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; -import { useContainerManager } from "./services"; +import { useContainerManager, useLogger } from "./services"; import { withWorkerRuntimeSetup, withOwnerWorkerLifecycleMutation } from "./worker-lifecycle-coordinator"; import { applyAdminNativePatch, validateAdminNativeState, type AdminNativeRuntimeIdentity, type AdminNativeMigration, type AdminNativeAcknowledge } from './admin-native-authority'; @@ -132,6 +132,8 @@ export class AdminWorkspaceStore { private unavailable = false; private runtime?: AdminWorkspaceRuntimeAdapter; private emergencyRuntime?: AdminWorkspaceEmergencyRuntime; + private stopRequested = false; + private stateWrites: Promise = Promise.resolve(); private identityMaterializer?: AdminWorkspaceIdentityMaterializer; private operationTail: Promise = Promise.resolve(); private pendingOperations = 0; @@ -187,6 +189,7 @@ export class AdminWorkspaceStore { return this.loading; } private async save(record: Readonly) { + if (this.stopRequested) record = { ...record, status: "stopped" }; if (this.recordWriter) { await this.recordWriter(structuredClone(record)); return; @@ -198,8 +201,8 @@ export class AdminWorkspaceStore { }); await rename(temp, this.path); } - private exclusive(operation: () => Promise): Promise { - if (this.pendingOperations) return Promise.reject(Object.assign( + private exclusive(operation: () => Promise, queue = false): Promise { + if (this.pendingOperations && !queue) return Promise.reject(Object.assign( new Error('Administrative workspace operation is already in progress. Refresh status before retrying.'), { statusCode: 409 })); return withOperationDeadline(this.serialize(async () => { await this.init(); @@ -223,14 +226,22 @@ export class AdminWorkspaceStore { private async flushPendingCommit(operation: string) { if (!this.pendingCommit) return false; const pending = this.pendingCommit; - await this.save(pending.record); - this.record = structuredClone(pending.record); + await this.commit(pending.record); this.pendingCommit = undefined; return pending.operation === operation; } - private async commit(record: AdministrativeWorkspaceRecord) { - await this.save(record); - this.record = structuredClone(record); + private async commit(record: AdministrativeWorkspaceRecord, intentOnly = false) { + const write = this.stateWrites.then(async () => { + // Stop intent must merge with a late native receipt, never replace it with an older snapshot. + if (intentOnly) { + if (this.record?.id !== record.id) throw Object.assign(new Error("Administrative workspace identity changed"), { statusCode: 409 }); + record = { ...this.record, status: "stopped", updatedAt: record.updatedAt }; + } + await this.save(record); + this.record = structuredClone(this.stopRequested ? { ...record, status: "stopped" as const } : record); + }); + this.stateWrites = write.catch(() => {}); + return write; } private async commitExternal( operation: string, @@ -252,6 +263,8 @@ export class AdminWorkspaceStore { } private nativeAcknowledge(record: AdministrativeWorkspaceRecord): AdminNativeAcknowledge { return async patch => { + if (this.stopRequested && patch.nativeRuntime?.pending?.kind === 'start' && !patch.nativeRuntime.pending.operation) + throw Object.assign(new Error('Administrative start cancelled by emergency stop; stopped intent retained'), { statusCode: 409 }); if (applyAdminNativePatch(record, patch)) await this.commitExternal('native-runtime', record); }; } @@ -366,6 +379,15 @@ export class AdminWorkspaceStore { } async setStatus(status: "running" | "stopped", force = false, expectedId?: string) { const emergency = force && status === "stopped"; + if (emergency) { + if (!this.runtime && !this.emergencyRuntime) this.requireRuntime(); + await this.init(); + if (!this.record || expectedId && this.record.id !== expectedId) + throw Object.assign(new Error("Administrative workspace identity is unavailable or changed"), { statusCode: this.record ? 409 : 404 }); + this.stopRequested = true; + await this.commit({ ...this.record, status: "stopped", updatedAt: new Date().toISOString() }, true); + useLogger().warn(`[admin-workspace] emergency stop intent saved; ${this.pendingOperations ? "waiting for in-flight mutation settlement" : "shutdown confirmation pending"}`); + } const result = this.exclusive(async () => { const runtime = this.runtime ?? (emergency ? this.emergencyRuntime : undefined); if (!runtime) this.requireRuntime(); @@ -382,6 +404,7 @@ export class AdminWorkspaceStore { const candidate = structuredClone(this.record!); if (runtime) { if (status === "running") { + this.stopRequested = false; if (this.identityMaterializer) await this.identityMaterializer( structuredClone(candidate), @@ -401,9 +424,12 @@ export class AdminWorkspaceStore { candidate.updatedAt = new Date().toISOString(); if (runtime) await this.commitExternal(operation, candidate); else await this.commit(candidate); + if (emergency) useLogger().info('[admin-workspace] emergency stop confirmed; persistent data retained'); return this.publicRecord(candidate); - }); - return emergency ? withOperationDeadline(result, 15_000, "Administrative emergency stop") : result; + }, emergency); + if (!emergency) return result; + try { return await withOperationDeadline(result, 15_000, "Administrative emergency stop; stopped intent retained, shutdown confirmation pending"); } + catch (error) { useLogger().warn('[admin-workspace] emergency stop unconfirmed; stopped intent retained, recovery still required'); throw error; } } async rebuild(ownerId?: string) { return this.exclusive(async () => { diff --git a/orchestrator/server/utils/container.ts b/orchestrator/server/utils/container.ts index 160d2cb1..f485049b 100644 --- a/orchestrator/server/utils/container.ts +++ b/orchestrator/server/utils/container.ts @@ -1,3 +1,5 @@ +import { recoveryState, validateRecoveryMaxRetries, UNKNOWN_STATE_WARNING } from "../../shared/worker-recovery"; +import { workerStartupFailure } from "./worker-startup-error"; import { MANAGED_KILO_PARENT } from './managed-volume-kilo-parent'; import { randomUUID } from "node:crypto"; import Docker from 'dockerode'; @@ -462,6 +464,9 @@ export async function removeFailedImportedImage( } export class ContainerManager { + private stoppedIntent = new Set(); + private intentVersions = new Map(); + private recoveryPaused = new Set(); private managedNetworks?: ManagedNetworkManager; /** Restart-persistent ownership handles for custom environments created * implicitly by imports. */ @@ -581,16 +586,20 @@ export class ContainerManager { private async persistDesiredRuntimeStatus( info: ContainerInfo, desired: "running" | "stopped", + operatorIntent = false, ): Promise { - info.desiredRuntimeStatus = desired; - info.updatedAt = new Date().toISOString(); + if (desired === "running" && this.stoppedIntent.has(info.id)) + throw Object.assign(new Error("Start cancelled by a newer stop request; stopped intent retained"), { code: "WORKER_STOP_REQUESTED", statusCode: 409 }); const record = this.workerStore?.get(info.userId, info.id); if (record) await this.workerStore!.setDesiredRuntimeStatus( info.userId, info.id, desired, + operatorIntent, ); + info.desiredRuntimeStatus = desired; + info.updatedAt = new Date().toISOString(); } private markRuntimeUnknown( @@ -604,7 +613,7 @@ export class ContainerManager { code: (error as { code?: string })?.code || "WORKER_RUNTIME_UNRESPONSIVE", operation, message: - "Agentor could not verify the worker runtime. Retry the operation or use managed recovery; persistent volumes were not changed.", + workerStartupFailure(error).message + ". Retry the operation or inspect recovery status; persistent volumes were not changed.", retryable: true, observedAt: info.updatedAt, }; @@ -2087,7 +2096,10 @@ export class ContainerManager { } return info; } - const migration = this.workerStore?.get(info.userId, info.id)?.incusMigration; + const record = this.workerStore?.get(info.userId, info.id); + info.recovery = record?.recovery; + if (record?.desiredRuntimeStatus) info.desiredRuntimeStatus = record.desiredRuntimeStatus; + const migration = record?.incusMigration; return migration && migration.phase !== 'retained' ? { ...info, status: 'error', runtimeDiagnostic: { code: 'WORKER_MIGRATION_RECOVERY_REQUIRED', message: 'Migration is incomplete; original source and destination are retained for explicit administrator recovery', @@ -2752,7 +2764,7 @@ export class ContainerManager { marker.replacementIncarnation = incarnation; await this.workerStore.transitionIncusRecreation(userId, id, { status: 'active', desiredRuntimeStatus: 'stopped', incusRecreation: marker }); - await this.incusRuntime.start(options, incarnation); + await this.incusRuntime.start(options, incarnation, { assertStartAllowed: () => this.assertStartAllowed(id) }); appliedBootstrap = this.appliedIncusBootstrap(options, containerInfo); } else { const container = await this.dockerService.createWorkerContainer(options); @@ -3682,10 +3694,95 @@ for p in sys.argv[1:]: ); } + async setDesiredState(id: string, desired: "running" | "stopped") { + const info = this.containers.get(id); + if (!info) throw Object.assign(new Error("Worker not found"), { statusCode: 404 }); + assertOrdinaryWorkerIdentity(id, info.userId); + if (desired !== "running" && desired !== "stopped") throw Object.assign(new Error("Invalid desired state"), { statusCode: 400 }); + await this.assertOwnerExists(info.userId); + this.intentVersions.set(id, (this.intentVersions.get(id) ?? 0) + 1); + const wasStopped = this.stoppedIntent.has(id); + if (desired === "stopped") this.stoppedIntent.add(id); + else this.stoppedIntent.delete(id); + try { await this.persistDesiredRuntimeStatus(info, desired, true); } + catch (error) { + if (desired === "running" && wasStopped) this.stoppedIntent.add(id); + useLogger().error(`[container] desired state persistence failed for ${id}; runtime unchanged, operator retry required`); + throw error; + } + if (desired === "running") { + await this.workerStore?.updateRecovery(info.userId, id, { reset: true }); + this.recoveryPaused.delete(id); + } + useLogger().info(`[container] desired state ${desired} accepted for ${id}; observed ${info.status}, runtime confirmation pending`); + return { workerId: id, desiredRuntimeStatus: desired, status: info.status, warning: UNKNOWN_STATE_WARNING }; + } + + getRecovery(id: string) { + const info = this.containers.get(id); + if (!info) throw Object.assign(new Error("Worker not found"), { statusCode: 404 }); + assertOrdinaryWorkerIdentity(id, info.userId); + const recovery = recoveryState(this.workerStore?.get(info.userId, id)?.recovery); + return { ...recovery, paused: recovery.attempts >= recovery.maxRetries, desiredRuntimeStatus: info.desiredRuntimeStatus }; + } + + async setRecovery(id: string, maxRetries: unknown) { + const info = this.containers.get(id); + if (!info || !this.workerStore) throw Object.assign(new Error("Worker not found"), { statusCode: 404 }); + assertOrdinaryWorkerIdentity(id, info.userId); + await this.workerStore.updateRecovery(info.userId, id, { maxRetries: validateRecoveryMaxRetries(maxRetries) }); + useLogger().info(`[container] recovery retry limit updated for ${id}; attempts retained, no runtime action requested`); + return this.getRecovery(id); + } + + private assertStartAllowed(id: string) { + if (this.stoppedIntent.has(id)) throw Object.assign(new Error("Start cancelled by a newer stop request; stopped intent retained"), { code: "WORKER_STOP_REQUESTED", statusCode: 409 }); + } + + private async automaticRecovery(info: Pick, operation: () => Promise) { + const current = this.workerStore?.get(info.userId, info.id); + if (!current || current.desiredRuntimeStatus !== "running" || this.stoppedIntent.has(info.id)) return; + const recovery = recoveryState(current.recovery); + if (recovery.attempts >= recovery.maxRetries) { + if (!this.recoveryPaused.has(info.id)) { + this.recoveryPaused.add(info.id); + useLogger().warn(`[container] automatic recovery paused for ${info.id}: ${recovery.attempts}/${recovery.maxRetries} retries used; runtime unchanged, persistent data retained; explicit Start/Retry required`); + } + return; + } + this.recoveryPaused.delete(info.id); + const attempt = await this.workerStore!.updateRecovery(info.userId, info.id, { attempt: true }); + if (!attempt.claimed || this.workerStore?.get(info.userId, info.id)?.desiredRuntimeStatus !== "running") return; + useLogger().info(`[container] automatic recovery ${attempt.attempts}/${attempt.maxRetries} starting for ${info.id}`); + try { + await operation(); + await this.workerStore!.updateRecovery(info.userId, info.id, { reset: true }); + useLogger().info(`[container] automatic recovery completed for ${info.id}; retry budget reset`); + return true; + } catch (error) { + const failure = workerStartupFailure(error); + await this.workerStore!.updateRecovery(info.userId, info.id, { failure }); + useLogger().warn(`[container] automatic recovery ${attempt.attempts}/${attempt.maxRetries} failed for ${info.id}: ${failure.message}; ${attempt.attempts >= attempt.maxRetries ? "automatic recovery paused; explicit Start/Retry required" : "retry pending"}; persistent data retained`); + throw error; + } + } + async emergencyStop(id: string): Promise { - if (isWorkerLifecycleMutationPending(id)) - throw Object.assign(new Error("Worker lifecycle operation is still pending; refresh status before retrying emergency stop"), { statusCode: 409 }); - return this.withExistingWorkerLifecycleMutation(id, () => this.stopUnlocked(id, false, true), true); + await this.setDesiredState(id, "stopped"); + const info = this.containers.get(id)!; + useLogger().warn(`[container] emergency stop accepted for ${id}; ${isWorkerLifecycleMutationPending(id) ? "waiting for in-flight runtime mutation to settle" : "confirming runtime shutdown"}`); + const operation = withOwnerWorkerLifecycleMutation(info.userId, id, async () => { + await this.assertOwnerExists(info.userId); + const current = this.containers.get(id); + if (!current || current.userId !== info.userId) throw new Error("Worker identity changed during emergency stop"); + await this.stopUnlocked(id, false, true); + useLogger().info(`[container] emergency stop confirmed for ${id}; persistent data retained`); + }); + try { await withOperationDeadline(operation, 15_000, "Worker emergency stop; stopped intent retained, shutdown confirmation pending"); } + catch (error) { + useLogger().warn(`[container] emergency stop unconfirmed for ${id}; stopped intent retained, runtime settlement or operator recovery still required`); + throw error; + } } /** Apply a lifecycle action to all ordinary workers directly contained in a @@ -3790,8 +3887,9 @@ for p in sys.argv[1:]: private async stopUnlocked(id: string, verifyRevokedIncus = false, force = false): Promise { const info = this.containers.get(id); if (!info) throw new Error("Container not found"); - this.assertOrdinaryMutation(info, true); - if (info.runtimeKind === 'incus-vm') { + if (force) assertOrdinaryWorkerIdentity(info.id, info.userId); + else this.assertOrdinaryMutation(info, true); + if (!force && info.runtimeKind === 'incus-vm') { const { useManagedVolumeManager } = await import('./managed-volume-manager'); const volumes = useManagedVolumeManager(); await volumes.init(); volumes.assertLiveRecoveryResolved(info.userId, info.id); @@ -3821,7 +3919,12 @@ for p in sys.argv[1:]: useLogger().info(`[container] stopped ${info.containerName}`); } - async restart(id: string): Promise { + async restart(id: string, automatic = false): Promise { + if (!automatic) { + const info = this.containers.get(id); + if (info) this.assertOrdinaryMutation(info); + await this.setDesiredState(id, "running"); + } return this.withExistingWorkerLifecycleMutation(id, () => this.restartUnlocked(id), ); @@ -3852,7 +3955,7 @@ for p in sys.argv[1:]: info.status = "starting"; try { await this.incusRuntime.stop(info, incarnation); - await this.incusRuntime.start(options, incarnation); + await this.incusRuntime.start(options, incarnation, { assertStartAllowed: () => this.assertStartAllowed(id) }); info.status = "running"; info.updatedAt = new Date().toISOString(); info.runtimeDiagnostic = undefined; @@ -3979,6 +4082,9 @@ for p in sys.argv[1:]: * restart, console, or stats operations. Only disposable compute is replaced; * every persistent mount is verified first and no volume is ever removed. */ async recover(id: string): Promise { + const info = this.containers.get(id); + if (info) this.assertOrdinaryMutation(info); + await this.setDesiredState(id, "running"); return this.withExistingWorkerLifecycleMutation(id, () => this.recoverUnlocked(id), ); @@ -4744,6 +4850,9 @@ for p in sys.argv[1:]: } async rebuild(id: string): Promise { + const info = this.containers.get(id); + if (info) this.assertOrdinaryMutation(info); + await this.setDesiredState(id, "running"); return this.withExistingWorkerLifecycleMutation(id, () => this.rebuildUnlocked(id), ); @@ -5102,17 +5211,31 @@ for p in sys.argv[1:]: return containerInfo; } - async unarchive(userId: string, id: string, imageResolution?: WorkerImportOptions['imageResolution']): Promise { + async unarchive(userId: string, id: string, imageResolution?: WorkerImportOptions['imageResolution'], automatic = false): Promise { + const intentVersion = automatic ? undefined : this.intentVersions.get(id) ?? 0; return withOwnerWorkerLifecycleMutation(userId, id, async () => { await this.assertOwnerExists(userId); - return this.unarchiveUnlocked(userId, id, imageResolution); + const record = this.workerStore?.get(userId, id); + if (automatic && record?.desiredRuntimeStatus !== "running") throw new Error("Automatic unarchive cancelled by stopped intent"); + return this.unarchiveUnlocked(userId, id, imageResolution, intentVersion); }); } + private async resetUnarchiveRetry(userId: string, id: string, version: number) { + if ((this.intentVersions.get(id) ?? 0) !== version) { + useLogger().warn(`[container] unarchive cancelled for ${id}; newer operator intent retained, compute unchanged`); + throw Object.assign(new Error('Unarchive cancelled by a newer desired-state request'), { statusCode: 409 }); + } + this.stoppedIntent.delete(id); + await this.workerStore!.setDesiredRuntimeStatus(userId, id, 'running', true); + await this.workerStore!.updateRecovery(userId, id, { reset: true }); + } + private async unarchiveUnlocked( userId: string, id: string, imageResolution?: WorkerImportOptions['imageResolution'], + operatorVersion?: number, ): Promise { assertOrdinaryWorkerIdentity(id, userId); this.assertMigrationSettled({ id, userId }); @@ -5139,7 +5262,7 @@ for p in sys.argv[1:]: const containerName = this.buildContainerName(worker.id); return this.recreateIncusWorker({ ...this.workerRuntimeRecord(worker), runtimeKind: 'incus-vm', containerName, containerId: containerName, imageName: this.config.incusWorkerImage, - imageId: worker.imageDigest ?? '', status: 'creating' }); + imageId: worker.imageDigest ?? '', status: 'creating' }, undefined, false, operatorVersion); } const authorizedMounts = await this.resolveAuthorizedHostMounts( worker.userId, @@ -5242,6 +5365,7 @@ for p in sys.argv[1:]: this.containers.set(worker.id, containerInfo); try { + if (operatorVersion !== undefined) await this.resetUnarchiveRetry(worker.userId, worker.id, operatorVersion); const container = await this.dockerService.createWorkerContainer({ userId: worker.userId, id: worker.id, @@ -5300,7 +5424,7 @@ for p in sys.argv[1:]: /** Replace disposable Incus compute. All desired inputs and canonical data * are checked before removing a running original; no Docker helper is used. */ - private async recreateIncusWorker(snapshot: ContainerInfo, original?: ContainerInfo, applied = false): Promise { + private async recreateIncusWorker(snapshot: ContainerInfo, original?: ContainerInfo, applied = false, operatorVersion?: number): Promise { await this.incusRuntime.assertWorkspaceReplacementSettled(snapshot); if (!this.workerStore) throw new Error('WorkerStore is required for Incus recreation'); const record = this.workerStore.get(snapshot.userId, snapshot.id); @@ -5331,6 +5455,7 @@ for p in sys.argv[1:]: // recreation and unarchive retain their captured immutable VM recipe. const existing = await this.incusRuntime.preflightRecreation(options, applied && options.dockerEnabled, !!original && !applied); if (applied && !original) await assertMissing(); + if (operatorVersion !== undefined) await this.resetUnarchiveRetry(info.userId, info.id, operatorVersion); const marker = { nonce: randomUUID(), originalIncarnation, replacementIncarnation: undefined as string | undefined }; // Persist stopped intent before any destructive operation. The bounded @@ -5368,7 +5493,7 @@ for p in sys.argv[1:]: marker.replacementIncarnation = incarnation; await this.workerStore.transitionIncusRecreation(info.userId, info.id, { status: 'active', desiredRuntimeStatus: 'stopped', incusRecreation: marker }); - await this.incusRuntime.start({ ...options, recreationNonce: marker.nonce }, incarnation); + await this.incusRuntime.start({ ...options, recreationNonce: marker.nonce }, incarnation, { assertStartAllowed: () => this.assertStartAllowed(info.id) }); await (await import('./managed-volume-manager')).useManagedVolumeManager().markDeclared(info.userId, info.id, info.containerId); if (!applied) await useWorkerConfigStore().markApplied(info.userId, info.id, this.appliedIncusBootstrap(options, info), options.configurationRevision); @@ -7333,7 +7458,7 @@ for p in sys.argv[1:]: !runtime.running ) // Failed observability probes must not restart a running worker. - await this.restart(info.id); + await this.automaticRecovery(info, () => this.restart(info.id, true)); if (info.status === 'running') await this.refreshManagedNetworkHosts(info.id, info.containerId).catch(error => { // Optional peer-name configuration is not evidence that this @@ -7354,7 +7479,7 @@ for p in sys.argv[1:]: // selected-path volumes, group identity, and plugin desired state remain // authoritative and are reattached/reconciled there. for (const worker of missingDesiredWorkers) { - await this.unarchive(worker.userId, worker.id).catch((error) => + await this.automaticRecovery(worker, () => this.unarchive(worker.userId, worker.id, undefined, true)).catch((error) => useLogger().warn( `[container] missing worker recreation deferred for ${worker.id}: ${(error as { code?: string })?.code || "runtime unavailable"}`, ), @@ -7408,8 +7533,8 @@ for p in sys.argv[1:]: this.get(record.id)?.containerId.startsWith('incus:')) return; await this.assertOwnerExists(record.userId); const name = this.buildContainerName(record.id); - await this.recreateIncusWorker({ ...this.workerRuntimeRecord(record), runtimeKind: 'incus-vm', containerName: name, - containerId: name, imageName: this.config.incusWorkerImage, imageId: record.imageDigest ?? '', status: 'unknown' }, undefined, true); + await this.automaticRecovery(record, () => this.recreateIncusWorker({ ...this.workerRuntimeRecord(record), runtimeKind: 'incus-vm', containerName: name, + containerId: name, imageName: this.config.incusWorkerImage, imageId: record.imageDigest ?? '', status: 'unknown' }, undefined, true)); }); } catch (error) { const current = this.get(snapshot.id), record = this.workerStore?.get(snapshot.userId, snapshot.id); @@ -7452,6 +7577,7 @@ for p in sys.argv[1:]: const guest = await this.incusRuntime.inspectGuestReadiness(info, incarnation); if (!guest.provisioned || !guest.serviceReady) return true; info.status = 'running'; info.runtimeDiagnostic = undefined; + if (record.recovery?.attempts) await this.workerStore!.updateRecovery(info.userId, info.id, { reset: true }); return this.managedNetworksNeedReconciliation(info); }); if (!repair) { @@ -7488,12 +7614,16 @@ for p in sys.argv[1:]: bootId = guest.bootId; } else if (instance.status !== 'Stopped') throw new Error('Incus guest is not ready for recovery'); const options = await this.incusOptionsForWorker(info, true, info.containerId); - info.status = 'starting'; - await this.incusRuntime.start(options, incarnation, { leaveRunningOnFailure: true }); - const guest = await this.incusRuntime.inspectGuestReadiness(info, incarnation); - if (!guest.provisioned || !guest.serviceReady || (bootId && guest.bootId !== bootId)) - throw new Error('Incus guest rebooted or remained unready during recovery; retry later'); - info.status = 'running'; info.runtimeDiagnostic = undefined; info.updatedAt = new Date().toISOString(); + const recovered = await this.automaticRecovery(info, async () => { + info.status = 'starting'; + this.assertStartAllowed(info.id); + await this.incusRuntime.start(options, incarnation, { leaveRunningOnFailure: true, assertStartAllowed: () => this.assertStartAllowed(info.id) }); + const guest = await this.incusRuntime.inspectGuestReadiness(info, incarnation); + if (!guest.provisioned || !guest.serviceReady || (bootId && guest.bootId !== bootId)) + throw new Error('Incus guest rebooted or remained unready during recovery; retry later'); + info.status = 'running'; info.runtimeDiagnostic = undefined; info.updatedAt = new Date().toISOString(); + }); + if (!recovered) return; useLogCollector().attach(info.containerName, info.containerId, 'worker', info.displayName).catch(() => {}); await this.reconcileManagedNetworksForWorker(info); await this.reconcileWorkerPlugins(info); @@ -7525,8 +7655,9 @@ for p in sys.argv[1:]: updatedAt: info.updatedAt, displayName: info.displayName, status: "active", - ...(info.desiredRuntimeStatus - ? { desiredRuntimeStatus: info.desiredRuntimeStatus } + recovery: this.workerStore?.get(info.userId, info.id)?.recovery, + ...((this.stoppedIntent.has(info.id) ? "stopped" : info.desiredRuntimeStatus) + ? { desiredRuntimeStatus: this.stoppedIntent.has(info.id) ? "stopped" : info.desiredRuntimeStatus } : {}), environmentId: info.environmentId, vcpuCount: info.vcpuCount, diff --git a/orchestrator/server/utils/group-admin-workspace-store.ts b/orchestrator/server/utils/group-admin-workspace-store.ts index 7e3937b4..fbfa3842 100644 --- a/orchestrator/server/utils/group-admin-workspace-store.ts +++ b/orchestrator/server/utils/group-admin-workspace-store.ts @@ -16,7 +16,7 @@ import { publicStartupScriptStatus, validateAdminWorkspaceStartupScript, } from "./admin-workspace-store"; -import { useWorkerGroupStore } from "./services"; +import { useWorkerGroupStore, useLogger } from "./services"; import type { WorkerGroup, WorkerGroupStore } from "./worker-group-store"; import { withWorkerNetworkMutation } from "./worker-group-manager"; import { @@ -46,6 +46,8 @@ export class GroupAdminWorkspaceStore { intent: AdminWorkspaceIdentityMaterializationIntent, ) => Promise; private running = new Set(); + private stopRequested = new Set(); + private stateWrites = new Map>(); private pendingCommits = new Map< string, { operation: string; record: GroupAdministrativeWorkspaceRecord } @@ -96,10 +98,18 @@ export class GroupAdminWorkspaceStore { | undefined; return record ? structuredClone(record) : undefined; } - private async save(record: GroupAdministrativeWorkspaceRecord) { - await this.groups.update(record.ownerId, record.groupId, { - adminWorkspace: structuredClone(record), + private async save(record: GroupAdministrativeWorkspaceRecord, intentOnly = false) { + const write = (this.stateWrites.get(record.groupId) ?? Promise.resolve()).then(async () => { + if (intentOnly) { + const current = this.record(record.groupId); + if (current?.id !== record.id) throw Object.assign(new Error("Group administrative workspace identity changed"), { statusCode: 409 }); + record = { ...current, status: "stopped", updatedAt: record.updatedAt }; + } + if (this.stopRequested.has(record.groupId)) record = { ...record, status: "stopped" }; + await this.groups.update(record.ownerId, record.groupId, { adminWorkspace: structuredClone(record) }); }); + this.stateWrites.set(record.groupId, write.catch(() => {})); + return write; } private async withGroup( groupId: string, @@ -146,7 +156,12 @@ export class GroupAdminWorkspaceStore { throw error; } } - private async run(groupId: string, operation: () => Promise): Promise { + private async run(groupId: string, operation: () => Promise, queue = false): Promise { + if (queue) { + const snapshot = this.group(groupId); + return this.serializeOwner(snapshot.userId, () => withWorkerLifecycleMutation( + snapshot.adminWorkspace?.id ?? `admin-group-bootstrap:${groupId}`, operation)); + } // Lifecycle operations can rebuild images and take longer than an HTTP // proxy timeout. Never queue retries behind an operation whose client has // disconnected: a burst of clicks/MCP retries would otherwise destroy and @@ -178,6 +193,8 @@ export class GroupAdminWorkspaceStore { } private nativeAcknowledge(record: GroupAdministrativeWorkspaceRecord): AdminNativeAcknowledge { return async patch => { + if (this.stopRequested.has(record.groupId) && patch.nativeRuntime?.pending?.kind === 'start' && !patch.nativeRuntime.pending.operation) + throw Object.assign(new Error('Administrative start cancelled by emergency stop; stopped intent retained'), { statusCode: 409 }); if (applyAdminNativePatch(record, patch)) await this.commitExternal('native-runtime', record); }; } @@ -306,6 +323,16 @@ export class GroupAdminWorkspaceStore { expectedId?: string, ) { const emergency = force && status === "stopped"; + if (emergency) { + authorize?.(); + if (!this.runtime && !this.emergencyRuntime) this.requireRuntime(); + const record = this.record(groupId); + if (!record || expectedId && record.id !== expectedId) + throw Object.assign(new Error("Group administrative workspace identity is unavailable or changed"), { statusCode: record ? 409 : 404 }); + this.stopRequested.add(groupId); + await this.save({ ...record, status: "stopped", updatedAt: new Date().toISOString() }, true); + useLogger().warn(`[group-admin-workspace] emergency stop intent saved; ${this.running.has(groupId) ? "waiting for in-flight mutation settlement" : "shutdown confirmation pending"}`); + } const result = this.run(groupId, () => this.withGroup(groupId, false, async (group) => { authorize?.(); @@ -331,6 +358,7 @@ export class GroupAdminWorkspaceStore { const record = this.record(groupId)!; if (runtime) { if (status === "running") { + this.stopRequested.delete(groupId); if (this.identityMaterializer) await this.identityMaterializer( structuredClone(record), @@ -350,10 +378,13 @@ export class GroupAdminWorkspaceStore { record.updatedAt = new Date().toISOString(); if (runtime) await this.commitExternal(operation, record); else await this.save(record); + if (emergency) useLogger().info('[group-admin-workspace] emergency stop confirmed; persistent data retained'); return this.publicRecord(record); - }), + }), emergency, ); - return emergency ? withOperationDeadline(result, 15_000, "Group administrative emergency stop") : result; + if (!emergency) return result; + try { return await withOperationDeadline(result, 15_000, "Group administrative emergency stop; stopped intent retained, shutdown confirmation pending"); } + catch (error) { useLogger().warn('[group-admin-workspace] emergency stop unconfirmed; stopped intent retained, recovery still required'); throw error; } } async rebuild(groupId: string, ownerId?: string, authorize?: () => void) { return this.run(groupId, () => diff --git a/orchestrator/server/utils/incus-worker-runtime.ts b/orchestrator/server/utils/incus-worker-runtime.ts index e6b31ec7..6714c2fb 100644 --- a/orchestrator/server/utils/incus-worker-runtime.ts +++ b/orchestrator/server/utils/incus-worker-runtime.ts @@ -1,3 +1,4 @@ +import { WorkerStartupError, workerStartupFailure } from "./worker-startup-error"; import { sameIncusDevice as sameDevice } from './incus-device-layout'; import { MANAGED_KILO_PARENT, MANAGED_KILO_PARENT_CHECK } from './managed-volume-kilo-parent'; import { effectiveIncusWorkerMemoryLimit } from '../../shared/worker-memory'; @@ -1451,9 +1452,9 @@ export class IncusWorkerRuntime { return instance; } - private async checkedExec(name: string, command: string[]): Promise { + private async checkedExec(name: string, command: string[], phase = "guest bootstrap"): Promise { const result = await this.client.exec(name, command); - if (result.returnCode !== 0) throw new Error(`Incus worker bootstrap command failed (${command[0]}, exit ${result.returnCode})`); + if (result.returnCode !== 0) throw new WorkerStartupError(phase, result.returnCode); } /** Raw paths must be private import scratch, not caller-selected host files. @@ -1860,7 +1861,7 @@ export class IncusWorkerRuntime { } async start(opts: IncusWorkerOptions, incarnation?: string, - recovery: { leaveRunningOnFailure?: boolean } = {}): Promise { + recovery: { leaveRunningOnFailure?: boolean; assertStartAllowed?: () => void } = {}): Promise { this.validateOptions(opts); await this.assertWorkspaceReplacementSettled(opts); await this.assertReady(); @@ -1908,6 +1909,7 @@ export class IncusWorkerRuntime { const current = await this.assertOwned(name, opts.id, opts.userId, instance.config['volatile.uuid']); assertIncusHardwareLayout(current, await this.preflightHardware(opts, current, 'attach')); } + recovery.assertStartAllowed?.(); if (state.status !== "Running") await this.client.startInstance(name); const deadline = Date.now() + 120_000; let ready = false; @@ -1918,7 +1920,10 @@ export class IncusWorkerRuntime { } catch { /* Agent becomes available after the guest has booted. */ } await new Promise((resolve) => setTimeout(resolve, 500)); } - if (!ready) throw new Error("Incus worker agent did not become ready"); + if (!ready) { + useLogger().warn("[incus-worker] guest agent readiness deadline expired; startup unconfirmed, VM retained for recovery"); + throw new WorkerStartupError("guest agent readiness deadline"); + } try { for (const volume of opts.managedVolumes ?? []) if (volume.target === MANAGED_KILO_PARENT) await this.checkedExec(name, ['timeout', '15', '/usr/bin/python3', '-c', MANAGED_KILO_PARENT_CHECK, volume.target]); @@ -1973,7 +1978,7 @@ export class IncusWorkerRuntime { initialize: await storage.dockerInitializationAllowed(opts), }), { uid: 0, gid: 0, mode: 0o600 }); await this.checkedExec(name, ["systemctl", "unmask", "docker", "docker.socket", "containerd", "agentor-docker-storage"]); - await this.checkedExec(name, ["systemctl", "start", "agentor-docker-storage"]); + await this.checkedExec(name, ["systemctl", "start", "agentor-docker-storage"], "Docker storage preparation"); await this.checkedExec(name, ["mountpoint", "-q", "/var/lib/docker"]); await storage.markDockerInitialized(opts); } else { @@ -1982,7 +1987,8 @@ export class IncusWorkerRuntime { // vendor Docker units, masking it would overwrite an installed unit. await this.checkedExec(name, ["systemctl", "mask", "docker", "docker.socket", "containerd"]); } - await this.checkedExec(name, ["systemctl", "start", "agentor-worker.service"]); + recovery.assertStartAllowed?.(); + await this.checkedExec(name, ["systemctl", "start", "agentor-worker.service"], "worker service start"); await this.checkedExec(name, ["systemctl", "is-active", "--quiet", "agentor-worker.service"]); const workerDeadline = Date.now() + 120_000; let workerReady = false; @@ -1992,10 +1998,15 @@ export class IncusWorkerRuntime { if (result.returnCode === 0) { workerReady = true; break; } await new Promise((resolve) => setTimeout(resolve, 500)); } - if (!workerReady) throw new Error("Incus worker service did not complete startup"); + if (!workerReady) throw new WorkerStartupError("worker service readiness deadline"); } catch (error) { - if (!recovery.leaveRunningOnFailure || state.status !== 'Running') - await this.stop(opts, instance.config['volatile.uuid']).catch(() => {}); + let outcome = 'VM retained running; recovery still required'; + if ((error as { code?: string })?.code === 'WORKER_STOP_REQUESTED') outcome = 'startup cancelled; emergency shutdown queued'; + else if (!recovery.leaveRunningOnFailure || state.status !== 'Running') { + try { await this.stop(opts, instance.config['volatile.uuid']); outcome = 'startup VM stopped; persistent data retained'; } + catch { outcome = 'startup cleanup unconfirmed; operator recovery required'; } + } + useLogger().warn(`[incus-worker] ${workerStartupFailure(error).message}; ${outcome}`); throw error; } } @@ -2048,6 +2059,8 @@ export class IncusWorkerRuntime { typeof target === 'string' ? undefined : target.userId, incarnation); const state = force ? instance : await this.client.getInstanceState(name); if (state.status !== "Stopped") await this.client.stopInstance(name, force ? { force: true, timeout: 0 } : { timeout }); + if (force && (await this.assertOwned(name, typeof target === "string" ? undefined : target.id, typeof target === "string" ? undefined : target.userId, incarnation)).status !== "Stopped") + throw Object.assign(new Error("Emergency stop is unconfirmed; stopped intent retained"), { statusCode: 503 }); } async refreshSshKeys(owner: IncusStorageOwner, content: string): Promise { diff --git a/orchestrator/server/utils/management-mcp-store.ts b/orchestrator/server/utils/management-mcp-store.ts index 5bf393af..34d50d52 100644 --- a/orchestrator/server/utils/management-mcp-store.ts +++ b/orchestrator/server/utils/management-mcp-store.ts @@ -121,6 +121,10 @@ const GROUP_ADMIN_TOOLS = new Set([ "worker.start", "workers.update", "workers.restart", + "workers.recovery.get", + "workers.recovery.set", + "workers.desired-state.set", + "workers.emergency-stop", "workers.rebuild", "workers.archive", "workers.unarchive", @@ -210,6 +214,7 @@ const GROUP_ADMIN_TOOLS = new Set([ "groups.admin-workspace.provision", "groups.admin-workspace.start", "groups.admin-workspace.stop", + "groups.admin-workspace.emergency-stop", "groups.admin-workspace.rebuild", "groups.admin-workspace.startup-script.get", "groups.admin-workspace.startup-script.set", @@ -263,6 +268,7 @@ const GROUP_ADMIN_GROUP_TOOLS = new Set([ "groups.admin-workspace.provision", "groups.admin-workspace.start", "groups.admin-workspace.stop", + "groups.admin-workspace.emergency-stop", "groups.admin-workspace.rebuild", "groups.admin-workspace.startup-script.get", "groups.admin-workspace.startup-script.set", @@ -282,6 +288,10 @@ const GROUP_ADMIN_DIRECT_TARGET_TOOLS = new Set([ "worker.start", "workers.update", "workers.restart", + "workers.recovery.get", + "workers.recovery.set", + "workers.desired-state.set", + "workers.emergency-stop", "workers.rebuild", "workers.archive", "workers.unarchive", @@ -2835,6 +2845,7 @@ function publicWorker(worker: any) { displayName: worker.displayName, status: worker.status, desiredRuntimeStatus: worker.desiredRuntimeStatus, + recovery: worker.recovery, runtimeDiagnostic: worker.runtimeDiagnostic, imageName: worker.imageName, environmentId: worker.environmentId, diff --git a/orchestrator/server/utils/management-worker-domain.ts b/orchestrator/server/utils/management-worker-domain.ts index 34af493d..51204859 100644 --- a/orchestrator/server/utils/management-worker-domain.ts +++ b/orchestrator/server/utils/management-worker-domain.ts @@ -1,3 +1,4 @@ +import { useAdminWorkspaceStore } from "./admin-workspace-store"; import { PREDEFINED_ENV_VAR_KEYS, type CreateContainerRequest, type UpdateContainerSettingsRequest } from "../../shared/types"; import { useContainerManager, @@ -130,6 +131,11 @@ export class ManagementWorkerDomain { const names: Array<[string, ManagementDomainTool["group"], string, Record, Record]> = [ ["workers.create", "worker-lifecycle", "Create a worker for an explicit owner, optionally enrolling it directly in one of that owner's worker groups. Host mounts accept only centrally approved pathId references and default to read-only. workerSelfApiAccess is enforced immediately by the orchestrator.", { type:"object", required:["userId"], additionalProperties:false, properties:{ userId:{type:"string"}, displayName:{type:"string"}, environmentId:{type:"string"}, workerGroupId:{type:"string",description:"Optional direct worker-group membership. The group must belong to userId."}, workerSelfApiAccess:workerSelfApiAccessSchema(), imageDefinitionId:{type:"string"}, imageVersion:{type:"string"}, mounts:{type:"array",items:hostMountInputSchema}, hardwareDeviceIds:{type:"array",items:{type:"string",minLength:1}}, excludedGlobalEnvVarKeys:excludedEnvKeysSchema() } }, mutation], ["workers.update", "worker-lifecycle", "Update worker settings. workerSelfApiAccess takes effect immediately without restart or rebuild; protected workers require lockPassword.", workerUpdateInput(), mutation], + ["workers.recovery.get", "worker-lifecycle", "Read a worker's durable automatic recovery retry limit, attempt count and sanitized last failure.", objectWithWorker(), read], + ["workers.recovery.set", "worker-lifecycle", "Set maxRetries (0-100) for automatic recovery. Zero disables automatic retries. Does not reset attempts or start compute.", { type: "object", additionalProperties: false, required: ["workerId", "maxRetries"], properties: { workerId: { type: "string" }, maxRetries: { type: "integer", minimum: 0, maximum: 100 }, lockPassword: { type: "string", writeOnly: true } } }, mutation], + ["workers.desired-state.set", "worker-lifecycle", "Persist running/stopped intent even if observed state is unknown. Warning: intent does not confirm runtime state. Requires confirmed:true; explicit running intent resets automatic retry attempts.", { type: "object", additionalProperties: false, required: ["workerId", "desiredRuntimeStatus", "confirmed"], properties: { workerId: { type: "string" }, desiredRuntimeStatus: { type: "string", enum: ["running", "stopped"] }, confirmed: { type: "boolean", enum: [true] }, lockPassword: { type: "string", writeOnly: true } } }, mutation], + ["workers.emergency-stop", "worker-lifecycle", "Force-stop an ordinary worker, including unknown/pending lifecycle state. Stopped intent is saved before waiting for in-flight mutation settlement. Requires confirmed:true; reports success only after native shutdown confirmation.", confirmedWorkerInput(), { ...mutation, destructiveHint: true }], + ["admin-workspace.emergency-stop", "worker-lifecycle", "Platform administrator only: emergency-stop the exact platform administrative workspace without provisioning or requiring healthy readiness. Requires confirmed:true; saved stop intent does not confirm shutdown.", confirmedWorkerInput(), { ...mutation, destructiveHint: true }], ["workers.restart", "worker-lifecycle", "Restart a worker; protected workers require lockPassword.", objectWithWorker(), mutation], ["workers.recover", "worker-lifecycle", "Recover an unresponsive worker through the bounded Agentor control plane. Persistent mounts are verified, only disposable compute is replaced, managed secrets are bootstrapped, and plugins are reconciled; protected workers require lockPassword.", objectWithWorker(), mutation], ["workers.rebuild", "worker-lifecycle", "Rebuild a worker; protected workers require lockPassword.", objectWithWorker(), mutation], @@ -153,6 +159,7 @@ export class ManagementWorkerDomain { ["groups.admin-workspace.get", "groups", "Get and reconcile the persistent administrative workspace for a worker group; returns 404 if none was provisioned. The server operation deadline defaults to 120 seconds.", groupAdminLifecycleInput, read], ["groups.admin-workspace.provision", "groups", "Provision or return the one persistent trusted administrative workspace for a worker group. The server operation deadline defaults to 120 seconds.", groupAdminLifecycleInput, mutation], ["groups.admin-workspace.start", "groups", "Provision if needed, then start a worker-group administrative workspace. The server operation deadline defaults to 120 seconds.", groupAdminLifecycleInput, mutation], + ["groups.admin-workspace.emergency-stop", "groups", "Emergency-stop an existing administrative workspace in an authorized group subtree, including unknown/pending lifecycle state. Requires confirmed:true; never provisions a missing workspace.", { ...groupAdminLifecycleInput, required: ["groupId", "confirmed"], properties: { ...groupAdminLifecycleInput.properties, confirmed: { type: "boolean", enum: [true] }, lockPassword: { type: "string", writeOnly: true } } }, { ...mutation, destructiveHint: true }], ["groups.admin-workspace.stop", "groups", "Provision if needed, then stop a worker-group administrative workspace without deleting its workspace data. The server operation deadline defaults to 120 seconds.", groupAdminLifecycleInput, mutation], ["groups.admin-workspace.rebuild", "groups", "Provision if needed, then rebuild and start a worker-group administrative workspace while retaining its group binding and data. The server operation deadline defaults to 120 seconds.", groupAdminLifecycleInput, mutation], ["groups.admin-workspace.startup-script.get", "groups", "Read the non-secret startup script and bounded runtime status for an existing group-administrative workspace. The target must be an authorized group; timeoutSeconds bounds the request.", groupAdminStartupScriptInput(false), read], @@ -209,9 +216,17 @@ export class ManagementWorkerDomain { : await operation(); return { handled:true, result }; } + if (name === "admin-workspace.emergency-stop") { + if (args.confirmed !== true) throw status(400, "Explicit emergency-stop confirmation required"); + const id = required(args.workerId, "workerId"); + await locks.verify(id, args.lockPassword); + await useAdminWorkspaceStore().setStatus("stopped", true, id); + return { handled: true, result: { workerId: id, status: "stopped" } }; + } const workerId = required(args.workerId, "workerId"); const worker = cm.get(workerId) ?? useWorkerStore().findById(workerId); if (!worker) throw status(404,"Worker not found"); + if (name === "workers.recovery.get") return { handled: true, result: cm.getRecovery(workerId) }; if (name === "workers.env-keys") { return {handled:true,result:await withinManagementFailFastDeadline(async()=>{ const configured=useUserEnvStore().getOrDefault(worker.userId).envVars.map(({key})=>key); @@ -236,6 +251,16 @@ export class ManagementWorkerDomain { } if (name === "workers.restart") { await locks.verify(workerId,args.lockPassword); await cm.restart(workerId); return {handled:true,result:{workerId,status:"running"}}; } await locks.verify(workerId,args.lockPassword); + if (name === "workers.recovery.set") return { handled: true, result: await cm.setRecovery(workerId, args.maxRetries) }; + if (name === "workers.desired-state.set") { + if (args.confirmed !== true) throw status(400, "Confirm the warning: desired state does not confirm runtime state"); + return { handled: true, result: await cm.setDesiredState(workerId, args.desiredRuntimeStatus as "running" | "stopped") }; + } + if (name === "workers.emergency-stop") { + if (args.confirmed !== true) throw status(400, "Explicit emergency-stop confirmation required"); + await cm.emergencyStop(workerId); + return { handled: true, result: { workerId, status: "stopped" } }; + } if (name === "workers.recover") return {handled:true,result:await cm.recover(workerId)}; if (name === "workers.update") { const updated=await cm.updateSettings(workerId, settings(args)); @@ -315,6 +340,13 @@ export class ManagementWorkerDomain { } if(name==="groups.admin-workspace.provision") return withinGroupAdminLifecycleDeadline(() => workspaces.ensure(group.id,group.userId,authorize), deadline); if(name==="groups.admin-workspace.start") return withinGroupAdminLifecycleDeadline(() => workspaces.setStatus(group.id,"running",authorize), deadline); + if(name==="groups.admin-workspace.emergency-stop") { + if (args.confirmed !== true) throw status(400, "Explicit emergency-stop confirmation required"); + const id = group.adminWorkspace?.id; + if (!id) throw status(404, "Group administrative workspace is not provisioned"); + await useWorkerProtectionLockStore().verify(id, args.lockPassword); + return withinGroupAdminLifecycleDeadline(() => workspaces.setStatus(group.id, "stopped", authorize, true, id), deadline); + } if(name==="groups.admin-workspace.stop") return withinGroupAdminLifecycleDeadline(() => workspaces.setStatus(group.id,"stopped",authorize), deadline); if(name==="groups.admin-workspace.rebuild") return withinGroupAdminLifecycleDeadline(() => workspaces.rebuild(group.id,group.userId,authorize), deadline); } @@ -378,3 +410,9 @@ function withinGroupWorkerLifecycleDeadline(operation: () => Promise, time void operation().then(resolve, reject); }).finally(() => { if (timer) clearTimeout(timer); }); } + +function confirmedWorkerInput() { + return { type: "object", additionalProperties: false, required: ["workerId", "confirmed"], properties: { + workerId: { type: "string" }, confirmed: { type: "boolean", enum: [true] }, lockPassword: { type: "string", writeOnly: true }, + } }; +} diff --git a/orchestrator/server/utils/worker-startup-error.ts b/orchestrator/server/utils/worker-startup-error.ts new file mode 100644 index 00000000..376edab7 --- /dev/null +++ b/orchestrator/server/utils/worker-startup-error.ts @@ -0,0 +1,13 @@ +export class WorkerStartupError extends Error { + readonly code = 'WORKER_BOOTSTRAP_FAILED'; + constructor(readonly phase: string, readonly exitCode?: number) { + super(`Incus worker bootstrap command failed during ${phase}${exitCode === undefined ? '' : ` (exit ${exitCode})`}`); + } +} + +/** Only platform-authored phases and numeric exit codes are public; guest output can contain secrets. */ +export function workerStartupFailure(error: unknown) { + if (error instanceof WorkerStartupError) + return { code: error.code, message: error.message, phase: error.phase, exitCode: error.exitCode }; + return { code: 'WORKER_RECOVERY_FAILED', message: 'Worker recovery failed; runtime readiness or identity could not be confirmed' }; +} diff --git a/orchestrator/server/utils/worker-store.ts b/orchestrator/server/utils/worker-store.ts index 1a3a12dc..47a96ca3 100644 --- a/orchestrator/server/utils/worker-store.ts +++ b/orchestrator/server/utils/worker-store.ts @@ -1,3 +1,4 @@ +import { recoveryState, validateRecoveryMaxRetries, type WorkerRecoveryState } from "../../shared/worker-recovery"; import { UserScopedJsonStore } from "./user-scoped-store"; import type { RepoConfig, @@ -60,6 +61,7 @@ export interface WorkerRecord extends UserOwnedResource { /** Desired runtime state survives daemon/orchestrator restarts. Legacy * records are migrated from the first successfully verified observation. */ desiredRuntimeStatus?: "running" | "stopped"; + recovery?: WorkerRecoveryState; archivedAt?: string; /** Internal fail-closed marker: Docker is already gone, but permanent * resource cleanup must be retried. Such a record cannot be unarchived. */ @@ -108,6 +110,7 @@ export interface WorkerRecord extends UserOwnedResource { export class WorkerStore extends UserScopedJsonStore { private initialization?: Promise; + private operatorStops = new Set(); /** Bootstrap this store once. Repeated live reads must not reload another * owner's in-flight lifecycle state from its JSON representation (which @@ -123,7 +126,7 @@ export class WorkerStore extends UserScopedJsonStore { } constructor(dataDir: string) { - super(dataDir, "workers.json", (w) => { assertImportIncompleteMarker(w); assertIncusMigration(w); assertCpuResize(w); return w.id; }); + super(dataDir, "workers.json", (w) => { assertImportIncompleteMarker(w); assertIncusMigration(w); assertCpuResize(w); recoveryState(w.recovery); return w.id; }); } override get(userId: string, key: string): WorkerRecord | undefined { @@ -203,6 +206,7 @@ export class WorkerStore extends UserScopedJsonStore { normalizeWorkerRuntimeKind(previous.runtimeKind) !== normalized.runtimeKind)) throw new Error('Incus migration authority requires its exact guarded transition'); if (!map) { map = new Map(); this.items.set(normalized.userId, map); } + if (this.operatorStops.has(normalized.userId + "/" + normalized.id)) normalized.desiredRuntimeStatus = "stopped"; map.set(normalized.id, structuredClone(normalized)); try { await this.persistUser(normalized.userId); } catch (error) { @@ -298,6 +302,10 @@ export class WorkerStore extends UserScopedJsonStore { private async persistMigration(userId: string, id: string, map: Map, previous: WorkerRecord, candidate: WorkerRecord): Promise { const next = { ...candidate, updatedAt: new Date().toISOString() }; + if (this.operatorStops.has(userId + "/" + id)) { + if (next.desiredRuntimeStatus === "running") this.storeLogger().warn('[worker-store] late runtime update retained operator stopped intent; startup remains blocked'); + next.desiredRuntimeStatus = "stopped"; + } assertImportIncompleteMarker(next); assertIncusMigration(next); map.set(id, structuredClone(next)); try { await this.persistUser(userId); } @@ -377,15 +385,39 @@ export class WorkerStore extends UserScopedJsonStore { }); } + async updateRecovery(userId: string, id: string, change: { maxRetries?: unknown; reset?: boolean; attempt?: boolean; failure?: WorkerRecoveryState["lastFailure"] }): Promise { + return this.withUserMutation(userId, async () => { + const map = this.items.get(userId), current = map?.get(id); + if (!map || !current) throw Object.assign(new Error("Worker not found"), { statusCode: 404 }); + const recovery = recoveryState(current.recovery); + if (change.maxRetries !== undefined) recovery.maxRetries = validateRecoveryMaxRetries(change.maxRetries); + if (change.reset) { recovery.attempts = 0; delete recovery.lastFailure; } + if (change.attempt) { + if (current.desiredRuntimeStatus !== "running" || recovery.attempts >= recovery.maxRetries) return recovery; + recovery.attempts++; + } + if (change.failure) recovery.lastFailure = change.failure; + await this.persistMigration(userId, id, map, current, { ...current, recovery }); + return { ...recovery, ...(change.attempt ? { claimed: true } : {}) }; + }); + } + async setDesiredRuntimeStatus( userId: string, id: string, desiredRuntimeStatus: "running" | "stopped", + operatorIntent = false, ): Promise { return this.withUserMutation(userId, async () => { const map = this.items.get(userId), current = map?.get(id); if (!map || !current) throw Object.assign(new Error("Worker not found"), { statusCode: 404 }); - return this.persistMigration(userId, id, map, current, { ...current, desiredRuntimeStatus }); + const key = userId + "/" + id, stopped = this.operatorStops.has(key); + if (operatorIntent) { + if (desiredRuntimeStatus === "stopped") this.operatorStops.add(key); + else this.operatorStops.delete(key); + } + try { return await this.persistMigration(userId, id, map, current, { ...current, desiredRuntimeStatus }); } + catch (error) { if (stopped) this.operatorStops.add(key); else this.operatorStops.delete(key); throw error; } }); } diff --git a/orchestrator/shared/types.ts b/orchestrator/shared/types.ts index 646ea64f..e708b2cb 100644 --- a/orchestrator/shared/types.ts +++ b/orchestrator/shared/types.ts @@ -248,6 +248,7 @@ export interface ContainerInfo extends UserOwnedResource { status: ContainerStatus; /** Durable operator intent, distinct from an unreliable Docker observation. */ desiredRuntimeStatus?: "running" | "stopped"; + recovery?: import("./worker-recovery").WorkerRecoveryState; /** Safe, value-free explanation when the runtime cannot be verified. */ runtimeDiagnostic?: WorkerRuntimeDiagnostic; repos?: RepoConfig[]; diff --git a/orchestrator/shared/worker-recovery.ts b/orchestrator/shared/worker-recovery.ts new file mode 100644 index 00000000..7b716187 --- /dev/null +++ b/orchestrator/shared/worker-recovery.ts @@ -0,0 +1,23 @@ +export const DEFAULT_RECOVERY_MAX_RETRIES = 3; +export const UNKNOWN_STATE_WARNING = 'Current runtime state may be unknown. This changes the requested state; it does not confirm that the worker has started or stopped.'; + +export interface WorkerRecoveryState { + maxRetries: number; + attempts: number; + lastFailure?: { code: string; message: string; phase?: string; exitCode?: number }; +} + +export function recoveryState(value?: WorkerRecoveryState): WorkerRecoveryState { + if (value !== undefined) { + validateRecoveryMaxRetries(value.maxRetries); + if (!Number.isSafeInteger(value.attempts) || value.attempts < 0) + throw Object.assign(new Error('Persisted recovery attempt count is invalid; operator recovery required'), { statusCode: 503 }); + } + return { maxRetries: DEFAULT_RECOVERY_MAX_RETRIES, attempts: 0, ...value }; +} + +export function validateRecoveryMaxRetries(value: unknown): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0 || value > 100) + throw Object.assign(new Error('maxRetries must be an integer from 0 to 100'), { statusCode: 400 }); + return value; +} diff --git a/tests/FEATURES.md b/tests/FEATURES.md index 5e62dd60..d7571b8d 100644 --- a/tests/FEATURES.md +++ b/tests/FEATURES.md @@ -1515,3 +1515,9 @@ Existing native administrative status/start preparation re-admits exact host pol Codex MCP subprocess endpoint allowlists are reconciled for canonical management and worker-self commands, including existing sections and existing account profiles, without replacing user configuration or persisting credentials/endpoint values. Terminal WebSocket attachment preserves only the latest validated early resize across authentication/runtime setup; early keystrokes remain discarded and disconnect cancels pending resize delivery. The shared handler covers ordinary and administrative terminals. + + +- Bounded automatic worker recovery: configurable finite per-worker retry limits (default 3; 0 disables), durable counters, explicit reset and safe failure phases. +- Operator desired-state controls remain available with an explicit warning when actual runtime state is unknown; desired and observed state remain distinct. +- Emergency-stop intent is accepted during pending worker/platform/group lifecycle operations, preserves runtime identity/settlement fences and reports confirmation separately. +- Equivalent REST/GUI/management MCP controls; group administrators are restricted to live descendant groups and member workers, while platform administrative shutdown is platform-only. diff --git a/tests/TESTS.md b/tests/TESTS.md index 52269ec8..f507526b 100644 --- a/tests/TESTS.md +++ b/tests/TESTS.md @@ -649,3 +649,6 @@ Default workspace-only native imports without runtime-source metadata use the sa Admin memory host-policy regression coverage now includes applied 6 GiB VM admission for platform and group admins, pending desired-vs-applied changes, canonical finite memory spellings, and invalid/unbounded/oversized values rejected before host calls. The bounded `--update-policy --config` installer path is tested without provisioning, image conversion, or routing dispatch. Both Python suites run from `api/admin-native-runtime.spec.ts` in module CI. Native runtime/store tests verify observed status, unchanged desired state, rejected identity, stale inspection and redacted actionable host-policy errors. Chromium modal coverage clears stale running state after rejected inspection; the isolated sidebar fixture verifies admin cards navigate to confirmed management controls. All fixtures use synthetic authority and mocked host operations; actual native host acceptance remains required. + + +Recovery controls (#61): `api/worker-recovery-controls.spec.ts` covers finite limits, atomic durable reservations/reload, safe startup errors, REST/MCP confirmation and protection locks, global/group tool discovery, descendant authorization and revocation. `ui/worker-recovery-isolated.spec.ts` runs the actual production panel with HTTP fixtures to verify unknown-state warnings and retained counters. Native worker lifecycle and administrative transaction suites cover stop intent during in-flight/late-settling starts and native retry exhaustion. diff --git a/tests/api/admin-emergency-initialization.spec.ts b/tests/api/admin-emergency-initialization.spec.ts index 04c8d1cb..b2a996bd 100644 --- a/tests/api/admin-emergency-initialization.spec.ts +++ b/tests/api/admin-emergency-initialization.spec.ts @@ -77,8 +77,8 @@ test('unbound admin status and failed emergency observation never report stale d f.platform.setEmergencyRuntimeAdapter(runtime); f.groups.setEmergencyRuntimeAdapter(runtime); for (const stop of [() => f.platform.setStatus('stopped', true), () => f.groups.setStatus(f.group.id, 'stopped', undefined, true)]) await expect(stop()).rejects.toMatchObject({ statusCode: 503 }); - expect(f.platform.getRecord()?.status).toBe('running'); - expect(f.groups.findByWorkspaceId('group-emergency')?.status).toBe('running'); + expect(f.platform.getRecord()?.status).toBe('stopped'); + expect(f.groups.findByWorkspaceId('group-emergency')?.status).toBe('stopped'); for (const read of [() => f.platform.getStatus(), () => f.groups.getStatus(f.group.id)]) await expect(read()).rejects.toMatchObject({ statusCode: 503 }); } finally { await f.cleanup(); } @@ -95,11 +95,11 @@ test('emergency timeout returns bounded feedback while both admin lifecycle fenc globalThis.setTimeout = ((callback: any, delay: number, ...args: any[]) => originalTimeout(callback, delay === 15_000 ? 50 : delay, ...args)) as any; try { const stopping = [f.platform.setStatus('stopped', true), f.groups.setStatus(f.group.id, 'stopped', undefined, true)]; - for (const result of stopping) await expect(result).rejects.toMatchObject({ statusCode: 504 }); + await Promise.all(stopping.map(result => expect(result).rejects.toMatchObject({ statusCode: 504 }))); for (const id of ['platform-emergency', 'group-emergency']) expect(isWorkerLifecycleMutationPending(id)).toBe(true); await expect(f.platform.getStatus()).rejects.toMatchObject({ statusCode: 503 }); - await expect(f.platform.setStatus('stopped', true)).rejects.toMatchObject({ statusCode: 409 }); - await expect(f.groups.setStatus(f.group.id, 'stopped', undefined, true)).rejects.toMatchObject({ statusCode: 409 }); + await expect(f.platform.setStatus('stopped', true)).rejects.toMatchObject({ statusCode: 504 }); + await expect(f.groups.setStatus(f.group.id, 'stopped', undefined, true)).rejects.toMatchObject({ statusCode: 504 }); release(); await expect.poll(() => isWorkerLifecycleMutationPending('platform-emergency') || isWorkerLifecycleMutationPending('group-emergency')).toBe(false); await expect(f.platform.getStatus()).resolves.toMatchObject({ status: 'stopped' }); diff --git a/tests/api/admin-workspace-store-transactions.spec.ts b/tests/api/admin-workspace-store-transactions.spec.ts index a8804bb2..045f1574 100644 --- a/tests/api/admin-workspace-store-transactions.spec.ts +++ b/tests/api/admin-workspace-store-transactions.spec.ts @@ -1,3 +1,4 @@ +(globalThis as any).useLogger ??= () => ({ info() {}, warn() {}, error() {}, debug() {} }); import { expect, test } from "@playwright/test"; import { AdminWorkspaceStore, @@ -618,3 +619,27 @@ for (const scoped of [false, true]) test(`${scoped ? 'group' : 'platform'} confi } finally { release(); await stopping; } await expect(get()).resolves.toMatchObject({ memoryLimit: '4GiB' }); }); + +for (const scoped of [false, true]) test(`${scoped ? 'group' : 'platform'} emergency stop saves intent before queued startup settles`, async () => { + const fake = new FakeGroups(), { group } = groupRecord('queued-owner', `queued-${scoped}-${Date.now()}`); + fake.records.set(group.id, group); + const platform = new AdminWorkspaceStore(`/tmp/agentor-queued-${Date.now()}`, async () => {}); + const groups = new GroupAdminWorkspaceStore(fake as any); + let entered!: () => void, release!: () => void; + const ready = new Promise(resolve => { entered = resolve; }), blocked = new Promise(resolve => { release = resolve; }); + const calls: string[] = []; + const adapter = runtime({ start: async () => { entered(); await blocked; }, stop: async (_record, _ack, force) => { + expect(force).toBe(true); calls.push('forced-stop'); + } }); + platform.setRuntimeAdapter(adapter); groups.setRuntimeAdapter(adapter); + if (!scoped) await platform.ensure(); + const start = scoped ? groups.setStatus(group.id, 'running') : platform.setStatus('running'); + await ready; + const stop = scoped ? groups.setStatus(group.id, 'stopped', () => {}, true) : platform.setStatus('stopped', true); + try { + await expect.poll(() => scoped ? fake.findById(group.id)?.adminWorkspace?.status : platform.getRecord()?.status).toBe('stopped'); + expect(calls).toEqual([]); + } finally { release(); await start; await stop; } + expect(calls).toEqual(['forced-stop']); + expect(scoped ? fake.findById(group.id)?.adminWorkspace?.status : platform.getRecord()?.status).toBe('stopped'); +}); diff --git a/tests/api/container-store-quarantine.spec.ts b/tests/api/container-store-quarantine.spec.ts index e768db9c..ee095bb3 100644 --- a/tests/api/container-store-quarantine.spec.ts +++ b/tests/api/container-store-quarantine.spec.ts @@ -444,7 +444,8 @@ test("a failed secret bootstrap is recoverable by stop/start without rebuilding" ); manager.setWorkerStore({ get: () => record, - setDesiredRuntimeStatus: async () => record, + setDesiredRuntimeStatus: async (_owner: string, _id: string, desired: string) => { (record as any).desiredRuntimeStatus = desired; return record; }, + updateRecovery: async (_owner: string, _id: string, change: any) => ({ maxRetries: 3, attempts: change.attempt ? 1 : 0, claimed: change.attempt }), } as any); // Production lifecycle entry points revalidate the owner through auth. This // focused unit test deliberately supplies only Docker/store doubles, so keep @@ -587,7 +588,8 @@ function reconciliationFixture(running: boolean) { upsert: async () => undefined, listActive: () => [record], listArchived: () => [], - setDesiredRuntimeStatus: async () => record, + setDesiredRuntimeStatus: async (_owner: string, _id: string, desired: string) => { (record as any).desiredRuntimeStatus = desired; return record; }, + updateRecovery: async (_owner: string, _id: string, change: any) => ({ maxRetries: 3, attempts: change.attempt ? 1 : 0, claimed: change.attempt }), } as any); const worker = { ...record, status: "running", containerId: "docker-worker-1", diff --git a/tests/api/incus-worker-lifecycle.spec.ts b/tests/api/incus-worker-lifecycle.spec.ts index 906c77f8..fab8c0e2 100644 --- a/tests/api/incus-worker-lifecycle.spec.ts +++ b/tests/api/incus-worker-lifecycle.spec.ts @@ -1576,19 +1576,21 @@ test('emergency stop reaches captured native runtime even with stale stopped hea }); }); -test('emergency stop rejects a pending lifecycle request promptly and retains its fence', async () => { - await fixture(async (manager, _store, calls, info) => { +test('emergency stop saves intent during pending lifecycle work and confirms stop after settlement', async () => { + await fixture(async (manager, store, calls, info) => { let release!: () => void, admitted!: () => void; const entered = new Promise(resolve => { admitted = resolve; }); const settlement = new Promise(resolve => { release = resolve; }); - const mutation = withOwnerWorkerLifecycleMutation(info.userId, info.id, async () => { - admitted(); await settlement; - }); + (manager as any).incusRuntime.stop = async () => { calls.push('forced-stop'); }; + const mutation = withOwnerWorkerLifecycleMutation(info.userId, info.id, async () => { admitted(); await settlement; }); + await entered; + const stopping = manager.emergencyStop(info.id); try { - await entered; - await expect(manager.emergencyStop(info.id)).rejects.toMatchObject({ statusCode: 409 }); + await expect.poll(() => store.get(info.userId, info.id)?.desiredRuntimeStatus).toBe('stopped'); expect(calls).toEqual([]); expect(isWorkerLifecycleMutationPending(info.id)).toBe(true); - } finally { release(); await mutation; } + await expect((manager as any).persistDesiredRuntimeStatus(info, 'running')).rejects.toMatchObject({ code: 'WORKER_STOP_REQUESTED' }); + } finally { release(); await mutation; await stopping; } + expect(calls).toEqual(['forced-stop']); expect(info.status).toBe('stopped'); }); }); @@ -1608,15 +1610,50 @@ test('ordinary Docker emergency stop dispatches SIGKILL without graceful stop an }); }); -test('emergency stop cannot bypass a timed-out request whose native mutation has not settled', async () => { - await fixture(async (manager, _store, calls, info) => { +test('emergency stop accepts intent without bypassing late native settlement', async () => { + await fixture(async (manager, store, calls, info) => { let release!: () => void; const settlement = new Promise(resolve => { release = resolve; }); const error = Object.assign(Error('request timed out'), { [operationSettlement]: settlement }); + (manager as any).incusRuntime.stop = async () => { calls.push('forced-stop'); }; + await expect(withOwnerWorkerLifecycleMutation(info.userId, info.id, async () => { throw error; })).rejects.toThrow('timed out'); + const stopping = manager.emergencyStop(info.id); try { - await expect(withOwnerWorkerLifecycleMutation(info.userId, info.id, async () => { throw error; })).rejects.toThrow('timed out'); - await expect(manager.emergencyStop(info.id)).rejects.toMatchObject({ statusCode: 409 }); + await expect.poll(() => store.get(info.userId, info.id)?.desiredRuntimeStatus).toBe('stopped'); expect(isWorkerLifecycleMutationPending(info.id)).toBe(true); expect(calls).toEqual([]); - } finally { release(); await settlement; } + } finally { release(); await stopping; } + expect(calls).toEqual(['forced-stop']); + }); +}); + + test('native startup failures exhaust a durable configurable retry budget without promoting readiness', async () => { + await reconciliationFixture(async (manager, store, calls, info, state) => { + state.status = 'Stopped'; state.provisioned = false; state.serviceReady = false; + await manager.setRecovery(info.id, 2); + (manager as any).incusRuntime.start = async () => { calls.push('failed-start'); throw new Error('PRIVATE-STDERR-SENTINEL'); }; + for (let i = 0; i < 5; i++) await manager.reconcileIncusWorkers(); + expect(calls.filter(value => value === 'failed-start')).toHaveLength(2); + expect(manager.getRecovery(info.id)).toMatchObject({ maxRetries: 2, attempts: 2, paused: true }); + expect(info.status).not.toBe('running'); + const reloaded = new WorkerStore((store as any).dataDir); await reloaded.init(); + expect(reloaded.get(info.userId, info.id)?.recovery).toMatchObject({ attempts: 2, maxRetries: 2 }); + expect(JSON.stringify(reloaded.get(info.userId, info.id)?.recovery)).not.toContain('PRIVATE-STDERR-SENTINEL'); + await manager.setDesiredState(info.id, 'stopped'); + await manager.reconcileIncusWorkers(); + expect(calls.filter(value => value === 'failed-start')).toHaveLength(2); + await manager.setDesiredState(info.id, 'running'); + await manager.reconcileIncusWorkers(); + expect(calls.filter(value => value === 'failed-start')).toHaveLength(3); + }); +}); + +test('a queued unarchive cannot reset a newer operator intent or recovery budget', async () => { + await fixture(async (manager, store, calls, info) => { + await manager.setRecovery(info.id, 1); + await manager.setDesiredState(info.id, 'stopped'); + const before = store.get(info.userId, info.id); + await expect((manager as any).resetUnarchiveRetry(info.userId, info.id, 0)).rejects.toMatchObject({ statusCode: 409 }); + expect(store.get(info.userId, info.id)).toEqual(before); + expect(calls).toEqual([]); }); }); diff --git a/tests/api/incus-worker-runtime.spec.ts b/tests/api/incus-worker-runtime.spec.ts index 465b86c9..119d51f3 100644 --- a/tests/api/incus-worker-runtime.spec.ts +++ b/tests/api/incus-worker-runtime.spec.ts @@ -1556,9 +1556,12 @@ test('forced native stop sends no grace period and refuses a replaced incarnatio const calls: unknown[] = []; instance.status = 'Frozen'; client.getInstanceState = async () => { throw Error('Emergency stop must not wait for guest telemetry'); }; - client.stopInstance = async (...args: unknown[]) => { calls.push(args); }; + client.stopInstance = async (...args: unknown[]) => { calls.push(args); instance.status = "Stopped"; }; await runtime.stop(opts, uuid, 30, true); expect(calls).toEqual([[opts.containerName, { force: true, timeout: 0 }]]); + instance.status = 'Frozen'; + client.stopInstance = async () => {}; + await expect(runtime.stop(opts, uuid, 30, true)).rejects.toMatchObject({ statusCode: 503 }); calls.length = 0; instance.config['volatile.uuid'] = randomUUID(); await expect(runtime.stop(opts, uuid, 30, true)).rejects.toThrow(); diff --git a/tests/api/physical-gpu-access.spec.ts b/tests/api/physical-gpu-access.spec.ts index 89e5281e..c3153446 100644 --- a/tests/api/physical-gpu-access.spec.ts +++ b/tests/api/physical-gpu-access.spec.ts @@ -137,7 +137,7 @@ test('MCP worker cloning omits physical GPU ownership while retaining USB and me './workspace-access': { OfflineWorkspaceAccess: class { async cloneInto() {} } }, './worker-self-access': { withEffectiveWorkerSelfApiAccess: (value: any) => value }, './image-catalog': {}, './worker-config-response': {}, './worker-group-manager': {}, - './group-admin-workspace-store': {}, './worker-group-hierarchy': {}, './worker-group-env': {}, './worker-group-response': {}, + './admin-workspace-store': {}, './group-admin-workspace-store': {}, './worker-group-hierarchy': {}, './worker-group-env': {}, './worker-group-response': {}, }); await expect(new ManagementWorkerDomain().execute('workers.clone', { workerId: worker.id })).resolves.toMatchObject({ handled: true }); expect(request.hardwareDeviceIds).toEqual(['usb', 'mediated']); diff --git a/tests/api/worker-emergency-stop.spec.ts b/tests/api/worker-emergency-stop.spec.ts index e3fe9969..7311c9e6 100644 --- a/tests/api/worker-emergency-stop.spec.ts +++ b/tests/api/worker-emergency-stop.spec.ts @@ -85,9 +85,9 @@ test('emergency stop handler enforces confirmation, lock passwords and separate const pending = withWorkerLifecycleMutation(workerId, async () => { entered(); await new Promise(resolve => { release = resolve; }); }); try { await ready; - await expect(route(event(workerId))).rejects.toMatchObject({ statusCode: 409 }); + await expect(route(event(workerId))).resolves.toEqual({ ok: true }); } finally { release(); await pending; } - expect(calls).toEqual(['ordinary', 'platform', 'group', 'ordinary', 'platform', 'group']); + expect(calls).toEqual(['ordinary', 'platform', 'group', 'ordinary', 'platform', 'group', 'ordinary']); } finally { containers.get = saved.get; containers.emergencyStop = saved.emergency; groups.findByWorkspaceId = saved.groupFind; groups.setStatus = saved.groupStatus; diff --git a/tests/api/worker-recovery-controls.spec.ts b/tests/api/worker-recovery-controls.spec.ts new file mode 100644 index 00000000..aa3bab5c --- /dev/null +++ b/tests/api/worker-recovery-controls.spec.ts @@ -0,0 +1,148 @@ +import { test, expect } from '@playwright/test'; +import { createRequire } from 'node:module'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { WorkerStore } from '../../orchestrator/server/utils/worker-store'; +import { workerStartupFailure, WorkerStartupError } from '../../orchestrator/server/utils/worker-startup-error'; +import { recoveryState, validateRecoveryMaxRetries } from '../../orchestrator/shared/worker-recovery'; +import { ManagementWorkerDomain } from '../../orchestrator/server/utils/management-worker-domain'; + +(globalThis as any).useLogger ??= () => ({ info() {}, warn() {}, error() {}, debug() {} }); + +test('recovery limits validate finite integers and defaults disable no existing worker implicitly', () => { + expect(recoveryState()).toEqual({ attempts: 0, maxRetries: 3 }); + for (const input of [undefined, null, '3', -1, 1.5, Infinity, NaN, 101]) expect(() => validateRecoveryMaxRetries(input)).toThrow('integer from 0 to 100'); + for (const input of [0, 3, 100]) expect(validateRecoveryMaxRetries(input)).toBe(input); +}); + +test('retry reservations are atomic, survive reload, retain limits and reset only explicitly', async () => { + const directory = await mkdtemp(join(tmpdir(), 'agentor-recovery-limit-')); + try { + const store = new WorkerStore(directory); await store.init(); + await store.upsert({ id: 'worker', userId: 'owner', displayName: 'fixture', status: 'active', desiredRuntimeStatus: 'running', createdAt: new Date(0).toISOString(), updatedAt: new Date(0).toISOString() }); + await store.updateRecovery('owner', 'worker', { maxRetries: 1 }); + const results = await Promise.all([store.updateRecovery('owner', 'worker', { attempt: true }), store.updateRecovery('owner', 'worker', { attempt: true })]); + expect(results.filter(value => value.claimed)).toHaveLength(1); + const reloaded = new WorkerStore(directory); await reloaded.init(); + expect(reloaded.get('owner', 'worker')?.recovery).toEqual({ maxRetries: 1, attempts: 1 }); + await reloaded.updateRecovery('owner', 'worker', { maxRetries: 0 }); + expect((await reloaded.updateRecovery('owner', 'worker', { attempt: true })).claimed).not.toBe(true); + expect(reloaded.get('owner', 'worker')?.recovery?.attempts).toBe(1); + await reloaded.updateRecovery('owner', 'worker', { reset: true }); + expect(reloaded.get('owner', 'worker')?.recovery).toEqual({ maxRetries: 0, attempts: 0 }); + } finally { await rm(directory, { recursive: true, force: true }); } +}); + +test('startup diagnostics expose safe failing phase and exit status without raw guest output', () => { + expect(workerStartupFailure(new WorkerStartupError('Docker storage preparation', 1))).toEqual({ code: 'WORKER_BOOTSTRAP_FAILED', message: 'Incus worker bootstrap command failed during Docker storage preparation (exit 1)', phase: 'Docker storage preparation', exitCode: 1 }); + const raw = Object.assign(new Error('PRIVATE-GUEST-TOKEN'), { stderr: 'PRIVATE-GUEST-TOKEN' }); + expect(JSON.stringify(workerStartupFailure(raw))).not.toContain('PRIVATE-GUEST-TOKEN'); +}); + +test('MCP declares confirmation, read-only status and retry configuration contracts', () => { + const tools = new Map(new ManagementWorkerDomain().tools().map(tool => [tool.name, tool])); + for (const name of ['workers.emergency-stop', 'admin-workspace.emergency-stop', 'groups.admin-workspace.emergency-stop', 'workers.desired-state.set']) { + expect(tools.get(name)?.inputSchema.required).toContain('confirmed'); + expect((tools.get(name)?.inputSchema.properties as any).confirmed.enum).toEqual([true]); + } + expect(tools.get('workers.recovery.get')?.annotations.readOnlyHint).toBe(true); + expect((tools.get('workers.recovery.set')?.inputSchema.properties as any).maxRetries).toMatchObject({ type: 'integer', minimum: 0, maximum: 100 }); +}); + + +test('REST and MCP recovery mutations enforce owner access, confirmation and protection locks', async () => { + const { useContainerManager } = await import('../../orchestrator/server/utils/services'); + const { useWorkerProtectionLockStore } = await import('../../orchestrator/server/utils/worker-protection-lock'); + const manager = useContainerManager(), locks = useWorkerProtectionLockStore(); + const saved = { get: manager.get, getRecovery: manager.getRecovery, setRecovery: manager.setRecovery, setDesiredState: manager.setDesiredState, emergencyStop: manager.emergencyStop, verify: locks.verify }; + const globals = globalThis as any, names = ['defineRouteMeta', 'defineEventHandler', 'getRouterParam', 'readBody', 'createError']; + const previous = Object.fromEntries(names.map(key => [key, Object.getOwnPropertyDescriptor(globals, key)])); + const { createError } = createRequire(new URL('../../orchestrator/package.json', import.meta.url))('h3'); + const calls: string[] = []; + let protectedWorker = false; + try { + Object.assign(globals, { defineRouteMeta: () => {}, defineEventHandler: (handler: unknown) => handler, getRouterParam: (event: any) => event.id, readBody: async (event: any) => event.body, createError }); + manager.get = ((id: string) => id === 'owned-worker' ? { id, userId: 'owner', status: 'unknown' } : undefined) as any; + manager.getRecovery = () => ({ maxRetries: 3, attempts: 1, paused: false }); + manager.setRecovery = async (_id, count) => { validateRecoveryMaxRetries(count); calls.push('limit'); return manager.getRecovery('owned-worker'); }; + manager.setDesiredState = async (_id, desired) => { if (!['running', 'stopped'].includes(desired)) throw Object.assign(new Error('Invalid state'), { statusCode: 400 }); calls.push(desired); return { workerId: 'owned-worker', desiredRuntimeStatus: desired, status: 'unknown', warning: 'Intent does not confirm runtime state' }; }; + manager.emergencyStop = async () => { calls.push('emergency'); }; + locks.verify = async (_id, password) => { if (protectedWorker && password !== 'fixture-password') throw Object.assign(new Error('Locked'), { statusCode: 423 }); return true; }; + const get = (await import('../../orchestrator/server/api/containers/[id]/recovery.get')).default as any; + const put = (await import('../../orchestrator/server/api/containers/[id]/recovery.put')).default as any; + const desired = (await import('../../orchestrator/server/api/containers/[id]/desired-state.put')).default as any; + const event = (body: unknown, owner = 'owner') => ({ id: 'owned-worker', body, context: { auth: { user: { id: owner, role: 'user' }, session: {} } } }); + await expect(get(event({}))).resolves.toMatchObject({ attempts: 1 }); + for (const handler of [get, put, desired]) await expect(handler(event({}, 'outsider'))).rejects.toMatchObject({ statusCode: 403 }); + await expect(desired(event({ desiredRuntimeStatus: 'stopped' }))).rejects.toMatchObject({ statusCode: 400 }); + await expect(put(event({ maxRetries: -1 }))).rejects.toMatchObject({ statusCode: 400 }); + protectedWorker = true; + await expect(put(event({ maxRetries: 2 }))).rejects.toMatchObject({ statusCode: 423 }); + const domain = new ManagementWorkerDomain(); + for (const name of ['workers.recovery.set', 'workers.desired-state.set', 'workers.emergency-stop']) await expect(domain.execute(name, { workerId: 'owned-worker', confirmed: true, desiredRuntimeStatus: 'stopped', maxRetries: 2 })).rejects.toMatchObject({ statusCode: 423 }); + await domain.execute('workers.recovery.set', { workerId: 'owned-worker', maxRetries: 2, lockPassword: 'fixture-password' }); + await domain.execute('workers.desired-state.set', { workerId: 'owned-worker', desiredRuntimeStatus: 'stopped', confirmed: true, lockPassword: 'fixture-password' }); + await expect(domain.execute('workers.emergency-stop', { workerId: 'owned-worker', lockPassword: 'fixture-password' })).rejects.toMatchObject({ statusCode: 400 }); + await domain.execute('workers.emergency-stop', { workerId: 'owned-worker', confirmed: true, lockPassword: 'fixture-password' }); + expect(calls).toEqual(['limit', 'stopped', 'emergency']); + } finally { + Object.assign(manager, { get: saved.get, getRecovery: saved.getRecovery, setRecovery: saved.setRecovery, setDesiredState: saved.setDesiredState, emergencyStop: saved.emergencyStop }); locks.verify = saved.verify; + for (const [key, descriptor] of Object.entries(previous)) { if (descriptor) Object.defineProperty(globals, key, descriptor); else delete globals[key]; } + } +}); + +test('global MCP discovers all controls; group MCP limits discovery and live authorization to subtree members', async () => { + const { ManagementMcpStore } = await import('../../orchestrator/server/utils/management-mcp-store'); + const { useWorkerGroupStore, useContainerManager } = await import('../../orchestrator/server/utils/services'); + const groups = useWorkerGroupStore(), manager = useContainerManager(); + const saved = { findById: groups.findById, get: groups.get, listForUser: groups.listForUser, list: manager.list, archived: manager.listArchived }; + const stamp = new Date(0).toISOString(); + const records = [{ id: 'root', userId: 'owner', workerIds: ['member'], name: 'root', createdAt: stamp, updatedAt: stamp }, { id: 'child', parentId: 'root', userId: 'owner', workerIds: ['descendant'], name: 'child', createdAt: stamp, updatedAt: stamp }, { id: 'sibling', userId: 'owner', workerIds: ['outsider'], name: 'sibling', createdAt: stamp, updatedAt: stamp }]; + const directory = await mkdtemp(join(tmpdir(), 'agentor-recovery-mcp-scope-')); + try { + groups.findById = (id => records.find(group => group.id === id)) as any; + groups.get = ((userId, id) => records.find(group => group.id === id && group.userId === userId)) as any; + groups.listForUser = (userId => records.filter(group => group.userId === userId)) as any; + manager.list = (() => ['member', 'descendant', 'outsider'].map(id => ({ id, userId: 'owner' }))) as any; manager.listArchived = () => []; + const store = new ManagementMcpStore(directory, async () => {}); + await store.init(); + (store as any).state.policy.groups['worker-lifecycle'].enabled = true; (store as any).state.policy.groups.groups.enabled = true; + const identity: any = { scope: 'group', workspaceId: 'root-admin', ownerId: 'owner', groupId: 'root' }; + const names = ['workers.recovery.get', 'workers.recovery.set', 'workers.desired-state.set', 'workers.emergency-stop']; + const platformTools = await store.listTools(), groupTools = await store.listTools(identity); + for (const name of [...names, 'admin-workspace.emergency-stop', 'groups.admin-workspace.emergency-stop']) expect(platformTools.some(tool => tool.name === name)).toBe(true); + expect(groupTools.some(tool => tool.name === 'admin-workspace.emergency-stop')).toBe(false); + for (const name of names) { + expect(groupTools.some(tool => tool.name === name)).toBe(true); + for (const workerId of ['member', 'descendant']) await (store as any).authorizeGroupInvocation(identity, name, { workerId }); + for (const workerId of ['outsider', 'root-admin', 'platform-admin']) await expect((store as any).authorizeGroupInvocation(identity, name, { workerId })).rejects.toMatchObject({ statusCode: 404 }); + } + for (const groupId of ['root', 'child']) await (store as any).authorizeGroupInvocation(identity, 'groups.admin-workspace.emergency-stop', { groupId }); + await expect((store as any).authorizeGroupInvocation(identity, 'groups.admin-workspace.emergency-stop', { groupId: 'sibling' })).rejects.toMatchObject({ statusCode: 404 }); + records[1]!.parentId = 'sibling'; + await expect((store as any).authorizeGroupInvocation(identity, 'workers.desired-state.set', { workerId: 'descendant' })).rejects.toMatchObject({ statusCode: 404 }); + await expect((store as any).authorizeGroupInvocation(identity, 'admin-workspace.emergency-stop', { workerId: 'platform-admin' })).rejects.toMatchObject({ statusCode: 403 }); + } finally { + groups.findById = saved.findById; groups.get = saved.get; groups.listForUser = saved.listForUser; manager.list = saved.list; manager.listArchived = saved.archived; + await rm(directory, { recursive: true, force: true }); + } +}); + + +test('late runtime records cannot erase durable operator stop intent', async () => { + const directory = await mkdtemp(join(tmpdir(), 'agentor-stop-intent-')); + try { + const store = new WorkerStore(directory); await store.init(); + const record = { id: 'worker', userId: 'owner', displayName: 'fixture', status: 'active' as const, desiredRuntimeStatus: 'running' as const, createdAt: new Date(0).toISOString(), updatedAt: new Date(0).toISOString() }; + await store.upsert(record); + await store.setDesiredRuntimeStatus('owner', 'worker', 'stopped', true); + await store.upsert(record); + await store.setDesiredRuntimeStatus('owner', 'worker', 'running'); + expect(store.get('owner', 'worker')?.desiredRuntimeStatus).toBe('stopped'); + const reloaded = new WorkerStore(directory); await reloaded.init(); + expect(reloaded.get('owner', 'worker')?.desiredRuntimeStatus).toBe('stopped'); + await store.setDesiredRuntimeStatus('owner', 'worker', 'running', true); + expect(store.get('owner', 'worker')?.desiredRuntimeStatus).toBe('running'); + } finally { await rm(directory, { recursive: true, force: true }); } +}); diff --git a/tests/playwright.modules.config.ts b/tests/playwright.modules.config.ts index 52592156..6cfa385d 100644 --- a/tests/playwright.modules.config.ts +++ b/tests/playwright.modules.config.ts @@ -136,6 +136,8 @@ export default defineConfig({ "api/worker-reconstruction.spec.ts", "api/worker-lifecycle-coordinator.spec.ts", "api/worker-emergency-stop.spec.ts", + "api/worker-recovery-controls.spec.ts", + "ui/worker-recovery-isolated.spec.ts", "api/admin-emergency-initialization.spec.ts", "api/incus-client.spec.ts", "api/incus-vcpu.spec.ts", diff --git a/tests/ui/worker-recovery-isolated.spec.ts b/tests/ui/worker-recovery-isolated.spec.ts new file mode 100644 index 00000000..3e0c3338 --- /dev/null +++ b/tests/ui/worker-recovery-isolated.spec.ts @@ -0,0 +1,62 @@ +import { test, expect } from '@playwright/test'; +import { createServer } from 'node:http'; +import { createRequire } from 'node:module'; +import { readFile } from 'node:fs/promises'; + +const require = createRequire(new URL('../../orchestrator/package.json', import.meta.url)); +const { parse, compileScript } = require('@vue/compiler-sfc'); +const { build } = require('esbuild'); + +test('actual recovery panel warns before unknown-state intent changes and saves a finite retry limit', async ({ page }) => { + const source = await readFile(new URL('../../orchestrator/app/components/WorkerRecoveryPanel.vue', import.meta.url), 'utf8'); + const { descriptor } = parse(source); + const script = compileScript(descriptor, { id: 'isolated-worker-recovery', inlineTemplate: true, genDefaultAs: 'RecoveryPanel' }); + const prelude = `import { createApp, ref, onMounted, h } from 'vue'; +const refreshNuxtData = async () => {}; +async function $fetch(url, options) { const response = await fetch(url, { method: options?.method || 'GET', body: options?.body ? JSON.stringify(options.body) : undefined }); const data = await response.json(); if (!response.ok) throw Object.assign(Error('Fixture API failed'), { statusCode: response.status, data }); return data; } +`; + const suffix = ` +const app = createApp({ render: () => h(RecoveryPanel, { workerId: 'fixture-worker' }) }); +app.component('UButton', { props: ['disabled'], setup(props, { slots, attrs }) { return () => h('button', { ...attrs, disabled: props.disabled }, slots.default?.()); } }); +app.component('UFormField', { props: ['label', 'description'], setup(props, { slots }) { return () => h('label', [props.label, slots.default?.(), h('small', props.description)]); } }); +app.component('UInput', { props: ['modelValue', 'type', 'disabled'], emits: ['update:modelValue'], setup(props, { emit, attrs }) { return () => h('input', { ...attrs, value: props.modelValue, type: props.type, disabled: props.disabled, onInput: event => emit('update:modelValue', props.type === 'number' ? Number(event.target.value) : event.target.value) }); } }); +app.component('UCheckbox', { props: ['modelValue', 'label', 'disabled'], emits: ['update:modelValue'], setup(props, { emit }) { return () => h('label', [h('input', { type: 'checkbox', checked: props.modelValue, disabled: props.disabled, onChange: event => emit('update:modelValue', event.target.checked) }), props.label]); } }); +app.mount('#app');`; + const bundle = await build({ stdin: { contents: prelude + script.content + suffix, + resolveDir: new URL('../../orchestrator/app/components', import.meta.url).pathname, loader: 'ts' }, bundle: true, write: false, format: 'iife', + define: { 'process.env.NODE_ENV': '"production"', __VUE_OPTIONS_API__: 'true', __VUE_PROD_DEVTOOLS__: 'false', __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: 'false' } }); + const mutations: any[] = [], errors: string[] = []; + let state = { maxRetries: 3, attempts: 3, paused: true, desiredRuntimeStatus: 'running' }; + page.on('pageerror', error => errors.push(error.message)); + const server = createServer((request, response) => { + if (request.url === '/component.js') { response.setHeader('Content-Type', 'application/javascript'); response.end(bundle.outputFiles[0].text); return; } + if (request.url?.startsWith('/api/')) { + response.setHeader('Content-Type', 'application/json'); + if (request.method === 'GET') { response.end(JSON.stringify(state)); return; } + let body = ''; request.on('data', chunk => { body += chunk; }); request.on('end', () => { + const input = JSON.parse(body); mutations.push(input); + if (input.desiredRuntimeStatus) state.desiredRuntimeStatus = input.desiredRuntimeStatus; + else state = { ...state, maxRetries: input.maxRetries, paused: state.attempts >= input.maxRetries }; + response.end(JSON.stringify(input.desiredRuntimeStatus ? { desiredRuntimeStatus: input.desiredRuntimeStatus, status: 'unknown' } : state)); + }); return; + } + response.setHeader('Content-Type', 'text/html'); response.end('
'); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + try { + const address = server.address() as { port: number }; + await page.goto(`http://127.0.0.1:${address.port}`); + await expect(page.getByText('Automatic recovery paused.', { exact: false })).toBeVisible(); + await expect(page.getByRole('button', { name: 'Request stopped', exact: true })).toBeDisabled(); + await expect(page.getByText('Current runtime state may be unknown.', { exact: false })).toBeVisible(); + await page.getByRole('checkbox').check(); + await page.getByRole('button', { name: 'Request stopped', exact: true }).click(); + await expect(page.getByRole('status').filter({ hasText: 'Requested stopped; runtime confirmation is pending.' })).toBeVisible(); + expect(mutations[0]).toMatchObject({ desiredRuntimeStatus: 'stopped', confirmed: true }); + await page.getByRole('spinbutton').fill('0'); + await page.getByRole('button', { name: 'Save limit' }).click(); + await expect(page.getByText('Retry limit saved; attempt count retained.')).toBeVisible(); + expect(mutations[1]).toMatchObject({ maxRetries: 0 }); + expect(state.attempts).toBe(3); expect(errors).toEqual([]); + } finally { await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); } +});