diff --git a/apps/api/src/db/migrations/0257_node_task_provisioned.sql b/apps/api/src/db/migrations/0257_node_task_provisioned.sql new file mode 100644 index 0000000000..adafddd200 --- /dev/null +++ b/apps/api/src/db/migrations/0257_node_task_provisioned.sql @@ -0,0 +1,3 @@ +-- Positive server-written provenance survives release/replacement of a task's current node. +-- Existing rows keep their indexed task-link/snapshot proofs; no legacy authority is removed. +ALTER TABLE nodes ADD COLUMN task_provisioned INTEGER NOT NULL DEFAULT 0 CHECK (task_provisioned IN (0, 1)); diff --git a/apps/api/src/durable-objects/task-runner/incompatible-node-drain.ts b/apps/api/src/durable-objects/task-runner/incompatible-node-drain.ts index 58b54a3ade..78b28ccbdd 100644 --- a/apps/api/src/durable-objects/task-runner/incompatible-node-drain.ts +++ b/apps/api/src/durable-objects/task-runner/incompatible-node-drain.ts @@ -7,6 +7,7 @@ import * as schema from '../../db/schema'; import { log } from '../../lib/logger'; import { parsePositiveInt } from '../../lib/route-helpers'; import { normalizeAgentVersion } from '../../services/node-agent-compatibility'; +import { taskProvisionedNodeConditionSql } from '../../services/node-teardown-provenance'; import { ensureSessionSnapshotForSleep } from '../../services/session-snapshots'; import { persistPlacementDiagnostics } from './placement-diagnostics'; import type { TaskRunnerContext, TaskRunnerState } from './types'; @@ -35,7 +36,7 @@ export async function requestIncompatiblePoolNodeDrain( AND n.status = 'running' AND n.runtime = 'vm' AND n.node_role = 'workspace' AND n.node_class = 'managed' AND (n.agent_version IS NULL OR TRIM(n.agent_version) != ?) - AND EXISTS (SELECT 1 FROM tasks t WHERE t.auto_provisioned_node_id = n.id) + AND ${taskProvisionedNodeConditionSql('n')} AND w.status IN ('running', 'recovery') AND w.project_id IS NOT NULL AND w.chat_session_id IS NOT NULL AND s.sleep_status IS NULL AND s.sleeping_at IS NULL diff --git a/apps/api/src/durable-objects/task-runner/index.ts b/apps/api/src/durable-objects/task-runner/index.ts index 26f9536c65..3eae66a8a4 100644 --- a/apps/api/src/durable-objects/task-runner/index.ts +++ b/apps/api/src/durable-objects/task-runner/index.ts @@ -247,6 +247,10 @@ export class TaskRunner extends DurableObject { lastD1Step: null, // Failure replay belongs to the previous attempt, not this fresh claim. wakeFailureMessage: undefined, + // A new wake is a new placement episode; replay of the same attempt returned above. + rejectedAutoProvisionedNodeId: undefined, + workspacePlacementRejections: 0, + startupBacklogConflicts: 0, completed: false, }; await transaction.put('state', state); diff --git a/apps/api/src/durable-objects/task-runner/node-provisioning-recovery.ts b/apps/api/src/durable-objects/task-runner/node-provisioning-recovery.ts index c297264c04..db9d4e23c6 100644 --- a/apps/api/src/durable-objects/task-runner/node-provisioning-recovery.ts +++ b/apps/api/src/durable-objects/task-runner/node-provisioning-recovery.ts @@ -31,7 +31,7 @@ export async function adoptProvisionedNodeAfterCrash( .bind(state.taskId) .first<{ auto_provisioned_node_id: string | null }>(); const recoveredNodeId = taskRow?.auto_provisioned_node_id ?? null; - if (recoveredNodeId) { + if (recoveredNodeId && recoveredNodeId !== state.rejectedAutoProvisionedNodeId) { const existing = await rc.env.DATABASE.prepare( `SELECT id, diff --git a/apps/api/src/durable-objects/task-runner/node-selection-shared.ts b/apps/api/src/durable-objects/task-runner/node-selection-shared.ts index 62227aa2b8..917c82c740 100644 --- a/apps/api/src/durable-objects/task-runner/node-selection-shared.ts +++ b/apps/api/src/durable-objects/task-runner/node-selection-shared.ts @@ -20,12 +20,8 @@ import { resolveReusableNodeCapacitySnapshot, } from '../../services/placement-resolver'; import { filterReusableNodesByCurrentAuthority } from '../../services/reusable-node-authority'; -import { - type TrustedWorkspaceNodeCapacityRow, -} from '../../services/workspace-admission-sql'; -import { - loadActiveWorkspaceReservationUsage, -} from '../../services/workspace-reservation-usage'; +import { type TrustedWorkspaceNodeCapacityRow } from '../../services/workspace-admission-sql'; +import { loadActiveWorkspaceReservationUsage } from '../../services/workspace-reservation-usage'; import type { TaskRunnerContext, TaskRunnerState } from './types'; export interface ReusableNodeSelection { @@ -89,7 +85,8 @@ export function resolveReusableNodeSelection( state: TaskRunnerState, node: NodePlacementFields ): ReusableNodeSelection | null { - if (node.id === state.config.excludedNodeId) return null; + if (node.id === state.config.excludedNodeId || node.id === state.rejectedAutoProvisionedNodeId) + return null; const capacityPlacementSnapshot = resolveReusableNodeCapacitySnapshot({ selection: state.config.capacityPoolSelection, node: node as CapacityAwareNodePlacementRow, @@ -110,6 +107,7 @@ export async function currentReusableNodeIds( nodes: readonly NodePlacementFields[] ): Promise> { return filterReusableNodesByCurrentAuthority(rc.env.DATABASE, { + requestingTaskId: state.taskId, userId: state.userId, projectId: state.projectId, selections: nodes.flatMap((node) => { diff --git a/apps/api/src/durable-objects/task-runner/node-steps.ts b/apps/api/src/durable-objects/task-runner/node-steps.ts index 65f4f530a8..144f2f648f 100644 --- a/apps/api/src/durable-objects/task-runner/node-steps.ts +++ b/apps/api/src/durable-objects/task-runner/node-steps.ts @@ -199,6 +199,7 @@ export async function handleNodeSelection( } const authoritativeNodes = await filterReusableNodesByCurrentAuthority(rc.env.DATABASE, { + requestingTaskId: state.taskId, userId: state.userId, projectId: state.projectId, selections: [{ nodeId: node.id, capacityPlacementSnapshot }], diff --git a/apps/api/src/durable-objects/task-runner/types.ts b/apps/api/src/durable-objects/task-runner/types.ts index d27ae6fd49..b51d55b8fb 100644 --- a/apps/api/src/durable-objects/task-runner/types.ts +++ b/apps/api/src/durable-objects/task-runner/types.ts @@ -217,9 +217,12 @@ export interface TaskRunnerState { agentReadyStartedAt: number | null; /** * Consecutive final-reservation refusals in this run (`workspace-placement-rejection.ts`). - * Reset when a reservation succeeds; at `operations.workspacePlacementMaxRejections` the task fails. + * Reset on successful reservation or the single provisioned-node fallback. At the configured + * cap, a run that has already used its fallback fails. */ workspacePlacementRejections?: number; + /** One fallback per execution: never re-adopt this capacity-rejected provisioned node. */ + rejectedAutoProvisionedNodeId?: string; /** * Final reservations refused only because the chosen node's startup backlog grew after it was * ranked (`workspace-placement-rejection.ts`), counted since this run's last successful diff --git a/apps/api/src/durable-objects/task-runner/warm-node-claim.ts b/apps/api/src/durable-objects/task-runner/warm-node-claim.ts index b2ac872d75..55b7520cb9 100644 --- a/apps/api/src/durable-objects/task-runner/warm-node-claim.ts +++ b/apps/api/src/durable-objects/task-runner/warm-node-claim.ts @@ -3,9 +3,7 @@ * `node-selection.ts` (rule 18), which re-exports it. */ -import { - normalizePlacementHostSignals, -} from '@simple-agent-manager/scheduler-core'; +import { normalizePlacementHostSignals } from '@simple-agent-manager/scheduler-core'; import { log } from '../../lib/logger'; import { isNodeAgentVersionCompatible } from '../../services/node-agent-compatibility'; @@ -19,12 +17,8 @@ import { SessionRecoveryAuthorityRevokedError, type SessionRecoverySourceTaskGuard, } from '../../services/session-recovery-authority'; -import { - trustedWorkspaceNodeCapacityColumnsSql, -} from '../../services/workspace-admission-sql'; -import { - loadActiveWorkspaceReservationUsage, -} from '../../services/workspace-reservation-usage'; +import { trustedWorkspaceNodeCapacityColumnsSql } from '../../services/workspace-admission-sql'; +import { loadActiveWorkspaceReservationUsage } from '../../services/workspace-reservation-usage'; import type { NodeLifecycle } from '../node-lifecycle'; import { currentReusableNodeIds, @@ -105,6 +99,7 @@ async function claimWarmNodeCandidate( ): Promise { const nodeId = selection.nodeId; const eligible = await filterReusableNodesByCurrentAuthority(rc.env.DATABASE, { + requestingTaskId: state.taskId, userId: state.userId, projectId: state.projectId, selections: [selection], diff --git a/apps/api/src/durable-objects/task-runner/workspace-placement-fallback.ts b/apps/api/src/durable-objects/task-runner/workspace-placement-fallback.ts new file mode 100644 index 0000000000..ec0e2895a4 --- /dev/null +++ b/apps/api/src/durable-objects/task-runner/workspace-placement-fallback.ts @@ -0,0 +1,82 @@ +import { log } from '../../lib/logger'; +import { handOffEmptyWorkspaceNode } from '../../services/node-warm-handoff'; +import { releaseVmProvisioningLease } from '../../services/vm-admission-control'; +import { TaskExecutionAuthorityRevokedError } from './task-execution-authority'; +import type { TaskRunnerContext, TaskRunnerState } from './types'; + +/** + * Resume the single fallback after any crash boundary. The intent is persisted before releasing + * D1 ownership. A node-local proof retains cleanup and lifetime provenance even after a + * replacement overwrites auto_provisioned_node_id. Never delete or quarantine the rejected host. + */ +export async function resumeWorkspacePlacementFallback( + state: TaskRunnerState, + rc: TaskRunnerContext +): Promise { + const nodeId = state.rejectedAutoProvisionedNodeId; + if (!nodeId || state.stepResults.nodeId !== nodeId) return false; + await rc.assertRecoveryAuthority(state); + const database = rc.env.DATABASE; + const transfer = await database.batch([ + database + .prepare( + `UPDATE nodes SET task_provisioned = 1 + WHERE id = ? AND user_id = ? AND node_class = 'managed' AND runtime = 'vm' AND node_role = 'workspace' + AND EXISTS (SELECT 1 FROM tasks t WHERE t.id = ? AND t.project_id = ? AND t.user_id = nodes.user_id + AND t.auto_provisioned_node_id = nodes.id AND t.workspace_id IS NULL + AND t.status IN ('queued', 'delegated', 'in_progress'))` + ) + .bind(nodeId, state.userId, state.taskId, state.projectId), + database + .prepare( + `UPDATE tasks SET auto_provisioned_node_id = NULL, updated_at = ? + WHERE id = ? AND user_id = ? AND project_id = ? + AND auto_provisioned_node_id = ? AND workspace_id IS NULL + AND status IN ('queued', 'delegated', 'in_progress') + AND EXISTS (SELECT 1 FROM nodes n WHERE n.id = tasks.auto_provisioned_node_id AND n.user_id = tasks.user_id + AND n.task_provisioned = 1 AND n.node_class = 'managed' AND n.runtime = 'vm' AND n.node_role = 'workspace')` + ) + .bind(new Date().toISOString(), state.taskId, state.userId, state.projectId, nodeId), + ]); + if ((transfer[1]?.meta.changes ?? 0) === 0) { + // Replay is safe only after the exact pointer was released (or its node was deleted). + const released = await database + .prepare( + `SELECT t.id FROM tasks t + WHERE t.id = ? AND t.user_id = ? AND t.project_id = ? AND t.workspace_id IS NULL + AND t.status IN ('queued', 'delegated', 'in_progress') AND t.auto_provisioned_node_id IS NULL + AND (NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = ?) + OR EXISTS (SELECT 1 FROM nodes n WHERE n.id = ? AND n.user_id = t.user_id AND n.task_provisioned = 1))` + ) + .bind(state.taskId, state.userId, state.projectId, nodeId, nodeId) + .first(); + if (!released) throw new TaskExecutionAuthorityRevokedError(); + } + await handOffEmptyWorkspaceNode(rc.env, { + nodeId, + expectedUserId: state.userId, + sourceProjectId: state.projectId, + reason: 'provisioned_node_placement_fallback', + }); + await releaseVmProvisioningLease( + rc.env, + state.admissionScopeKey, + state.taskId, + state.admissionLeaseToken, + 'provisioned_node_placement_fallback' + ); + state.admissionScopeKey = null; + state.admissionLeaseToken = null; + state.workspacePlacementRejections = 0; + state.startupBacklogConflicts = 0; + state.provisioningStartedAt = null; + state.agentReadyStartedAt = null; + state.stepResults.nodeId = null; + state.stepResults.autoProvisioned = false; + state.stepResults.provisionedVmSize = null; + state.stepResults.capacityPlacementSnapshot = null; + state.stepResults.rankedStartupBacklog = null; + log.info('task_runner_do.provisioned_node_placement_fallback', { taskId: state.taskId, nodeId }); + await rc.advanceToStep(state, 'node_selection'); + return true; +} diff --git a/apps/api/src/durable-objects/task-runner/workspace-placement-rejection.ts b/apps/api/src/durable-objects/task-runner/workspace-placement-rejection.ts index 349ee5c437..c0be158032 100644 --- a/apps/api/src/durable-objects/task-runner/workspace-placement-rejection.ts +++ b/apps/api/src/durable-objects/task-runner/workspace-placement-rejection.ts @@ -7,8 +7,8 @@ * node can never admit this request. Before the cap, a freshly provisioned node * that its own task could not fit was re-adopted from `tasks.auto_provisioned_node_id` * every ~6 s until the 15-minute provisioning timeout (2026-11-05 staging). The cap - * fails the task fast instead, with the refusal reasons, and keeps the node on the - * run so failure cleanup hands a node this task provisioned to the warm pool. + * permits one fallback to normal placement, retaining the rejected host's provenance. + * Exhausting the budget again fails the run with the refusal reasons. * * One refusal is not a capacity verdict at all: a startup-backlog conflict, where the node's * startup queue grew after this run ranked it above another admitted node @@ -28,16 +28,13 @@ import { LIFETIME_ADMISSION_CUTOFF_REASON, } from '../../services/node-lifetime-admission'; import { releaseVmProvisioningLease } from '../../services/vm-admission-control'; -import { - trustedWorkspaceNodeCapacityColumnsSql, -} from '../../services/workspace-admission-sql'; -import { - loadActiveWorkspaceReservationUsage, -} from '../../services/workspace-reservation-usage'; +import { trustedWorkspaceNodeCapacityColumnsSql } from '../../services/workspace-admission-sql'; +import { loadActiveWorkspaceReservationUsage } from '../../services/workspace-reservation-usage'; import { getTaskReservation } from './node-selection-shared'; import { persistPlacementDiagnostics } from './placement-diagnostics'; import type { TaskRunnerContext, TaskRunnerState } from './types'; import { relinquishWarmClaim } from './warm-node-claim'; +import { resumeWorkspacePlacementFallback } from './workspace-placement-fallback'; /** Prefix of the placement-diagnostics note this module owns; replaced on each refusal. */ export const WORKSPACE_PLACEMENT_REFUSED_NOTE_PREFIX = 'Workspace placement refused'; @@ -149,6 +146,17 @@ export async function handleWorkspacePlacementRefused( ); } + if ( + rejections >= maxRejections && + state.stepResults.autoProvisioned && + !state.rejectedAutoProvisionedNodeId + ) { + // One fallback episode per execution, never renewed by crashes or another provisioned node. + state.rejectedAutoProvisionedNodeId = nodeId; + await rc.ctx.storage.put('state', state); + await resumeWorkspacePlacementFallback(state, rc); + return; + } if (rejections >= maxRejections) { // Keep stepResults.nodeId/autoProvisioned: cleanupOnFailure warm-hands-off a node this // task provisioned and leaves a reused node alone. diff --git a/apps/api/src/durable-objects/task-runner/workspace-steps.ts b/apps/api/src/durable-objects/task-runner/workspace-steps.ts index 987f7dd6b0..c41e02fe4c 100644 --- a/apps/api/src/durable-objects/task-runner/workspace-steps.ts +++ b/apps/api/src/durable-objects/task-runner/workspace-steps.ts @@ -23,6 +23,7 @@ import { persistPlacementDiagnostics, updatePlacementDiagnostics } from './place import { ensureSessionLinked } from './state-machine'; import type { TaskRunnerContext, TaskRunnerState } from './types'; import { ensureBranchExistsOnRemote } from './workspace-branch'; +import { resumeWorkspacePlacementFallback } from './workspace-placement-fallback'; import { handleWorkspacePlacementRefused, resolveStartupBacklogGuard, @@ -44,6 +45,7 @@ export async function handleWorkspaceCreation( state: TaskRunnerState, rc: TaskRunnerContext ): Promise { + if (await resumeWorkspacePlacementFallback(state, rc)) return; await rc.updateD1ExecutionStep(state.taskId, 'workspace_creation'); if (!state.stepResults.nodeId) { diff --git a/apps/api/src/scheduled/node-cleanup/max-lifetime-candidates.ts b/apps/api/src/scheduled/node-cleanup/max-lifetime-candidates.ts index b3227449a3..ce19576ead 100644 --- a/apps/api/src/scheduled/node-cleanup/max-lifetime-candidates.ts +++ b/apps/api/src/scheduled/node-cleanup/max-lifetime-candidates.ts @@ -3,6 +3,7 @@ * `node-phases.ts` (`.claude/rules/18-file-size-limits.md`). */ import type { Env } from '../../env'; +import { taskProvisionedNodeConditionSql } from '../../services/node-teardown-provenance'; import { boundedWarmPlacementClaimGuardSql, type CleanupConfig, @@ -45,10 +46,7 @@ export async function selectMaxLifetimeCandidates( WHERE n.status NOT IN ('stopped', 'destroying', 'deleted') AND n.node_role = 'workspace' AND n.node_class != 'user-owned' - AND EXISTS ( - SELECT 1 FROM tasks t - WHERE t.auto_provisioned_node_id = n.id - ) + AND ${taskProvisionedNodeConditionSql('n')} AND (n.cleanup_backoff_until IS NULL OR n.cleanup_backoff_until <= ?) ${boundedWarmPlacementClaimGuardSql('n.id')} ${sleepingContainerRetentionGuardSql('n')} diff --git a/apps/api/src/scheduled/node-cleanup/node-phases.ts b/apps/api/src/scheduled/node-cleanup/node-phases.ts index c9594b2ffd..bd613ae83d 100644 --- a/apps/api/src/scheduled/node-cleanup/node-phases.ts +++ b/apps/api/src/scheduled/node-cleanup/node-phases.ts @@ -15,6 +15,7 @@ import { eq } from 'drizzle-orm'; import * as schema from '../../db/schema'; import type { Env } from '../../env'; import { log } from '../../lib/logger'; +import { taskProvisionedNodeConditionSql } from '../../services/node-teardown-provenance'; import { preservedVmRetirementActivitySql } from '../../services/preserved-vm-retirement'; import { prepareAbsoluteLifetimeRelease } from './absolute-lifetime-preservation'; import { selectMaxLifetimeCandidates } from './max-lifetime-candidates'; @@ -57,10 +58,7 @@ export async function sweepStaleWarmNodes( AND n.status = 'running' AND n.node_role = 'workspace' AND n.node_class != 'user-owned' - AND EXISTS ( - SELECT 1 FROM tasks t - WHERE t.auto_provisioned_node_id = n.id - ) + AND ${taskProvisionedNodeConditionSql('n')} AND (n.cleanup_backoff_until IS NULL OR n.cleanup_backoff_until <= ?) ${boundedWarmPlacementClaimGuardSql('n.id')} GROUP BY n.id, n.user_id, n.status, n.warm_since, n.created_at @@ -285,10 +283,7 @@ export async function sweepIncompatibleVmAgentNodes( WHERE n.status = 'running' AND n.node_role = 'workspace' AND n.node_class != 'user-owned' - AND EXISTS ( - SELECT 1 FROM tasks t - WHERE t.auto_provisioned_node_id = n.id - ) + AND ${taskProvisionedNodeConditionSql('n')} AND (n.cleanup_backoff_until IS NULL OR n.cleanup_backoff_until <= ?) ${boundedWarmPlacementClaimGuardSql('n.id')} AND (n.runtime IS NULL OR n.runtime = 'vm') @@ -397,10 +392,7 @@ export async function sweepIdleOrphanNodes( WHERE n.status = 'running' AND n.node_role = 'workspace' AND n.node_class != 'user-owned' - AND EXISTS ( - SELECT 1 FROM tasks t - WHERE t.auto_provisioned_node_id = n.id - ) + AND ${taskProvisionedNodeConditionSql('n')} AND (n.cleanup_backoff_until IS NULL OR n.cleanup_backoff_until <= ?) ${boundedWarmPlacementClaimGuardSql('n.id')} AND n.warm_since IS NULL diff --git a/apps/api/src/services/admin-settings-core-definitions.ts b/apps/api/src/services/admin-settings-core-definitions.ts index 767b29f346..5e13388e08 100644 --- a/apps/api/src/services/admin-settings-core-definitions.ts +++ b/apps/api/src/services/admin-settings-core-definitions.ts @@ -385,7 +385,7 @@ export const CORE_SETTINGS: AdminSettingDefinition[] = [ 'operations.workspacePlacementMaxRejections', DEFAULT_WORKSPACE_PLACEMENT_MAX_REJECTIONS, 'Operations', - 'Consecutive times the node a task selected may refuse its final workspace reservation before the task fails with the refusal reasons. The count resets when a reservation succeeds.', + 'Consecutive final workspace reservation refusals per placement episode. An owned provisioned node gets one fallback to normal placement; exhausting the budget again fails the run. A successful reservation or new wake resets the episode.', { min: 1, max: 20 } ), integerDefinition( diff --git a/apps/api/src/services/node-lifetime-admission.ts b/apps/api/src/services/node-lifetime-admission.ts index 3e60de8e27..3ca98309e8 100644 --- a/apps/api/src/services/node-lifetime-admission.ts +++ b/apps/api/src/services/node-lifetime-admission.ts @@ -7,7 +7,8 @@ * The condition is "the lifetime sweep will reap this node soon". The signal is the node's age * against the same ceiling, over the same population as `sweepMaxLifetimeNodes` * (`scheduled/node-cleanup/node-phases.ts`), so the two cannot diverge: a node the sweep never - * reaps (user-owned, or not auto-provisioned by a task) is never cut off. + * reaps (user-owned, or not auto-provisioned by a task) is never cut off. Released placement + * fallback history retains auto-provisioning provenance after the task chooses another host. * * Enforced in the final atomic reservation (`workspace-admission-sql.ts`) and, as a hint, in the * task runner's candidate queries (`task-runner/node-selection.ts`), per rule 69. @@ -24,6 +25,7 @@ import { import type { Env } from '../env'; import { parsePositiveInt } from '../lib/route-helpers'; import { resolveAdminSetting } from './admin-settings-resolution'; +import { taskProvisionedNodeConditionSql } from './node-teardown-provenance'; /** * The node age at which new placements stop, or null when the cutoff is disabled (0 percent). @@ -60,10 +62,7 @@ export async function resolvePlacementAdmissionPolicy( function pastCutoffCondition(alias: string): string { return `( ${alias}.node_class != 'user-owned' - AND EXISTS ( - SELECT 1 FROM tasks lifetime_task - WHERE lifetime_task.auto_provisioned_node_id = ${alias}.id - ) + AND ${taskProvisionedNodeConditionSql(alias)} AND ${alias}.created_at < ? )`; } diff --git a/apps/api/src/services/node-teardown-provenance.ts b/apps/api/src/services/node-teardown-provenance.ts index d15876f0d2..4257ff0e7d 100644 --- a/apps/api/src/services/node-teardown-provenance.ts +++ b/apps/api/src/services/node-teardown-provenance.ts @@ -2,7 +2,8 @@ * Server-written proof that SAM owns a managed node and can finish tearing it down. * * A node qualifies through either: - * - a task that auto-provisioned it (`tasks.auto_provisioned_node_id`), or + * - a task that auto-provisioned it (`tasks.auto_provisioned_node_id`, or the released + * node-local `task_provisioned` proof), or * - its own server-written pool/credential snapshot. Direct and pool-placed provisioning has * no task link, and a woken conversation clears the one it had, so the snapshot is the * durable proof. It is independent of current pool revisions so retiring a source cannot @@ -42,10 +43,7 @@ export function cleanupNodeProvenanceSql( ] .map((column) => `NULLIF(TRIM(${alias}.${column}), '') IS NOT NULL`) .join('\n AND '); - return `(EXISTS ( - SELECT 1 FROM tasks auto_task - WHERE auto_task.auto_provisioned_node_id = ${alias}.id - ) OR ( + return `(${taskProvisionedNodeConditionSql(alias)} OR ( ${alias}.status IN (${managedPoolStatuses}) AND ${alias}.node_class = 'managed' AND ${alias}.runtime = 'vm' @@ -112,3 +110,11 @@ export async function isNodeCapacitySourceReleased( .first<{ released: number }>(); return row?.released === 1; } + +/** Historical auto-provisioning proof only: never use this in active ownership/adoption gates. */ +export function taskProvisionedNodeConditionSql(alias: string): string { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(alias)) throw new Error('Unsafe SQL alias'); + return `(COALESCE(${alias}.task_provisioned, 0) = 1 OR EXISTS ( + SELECT 1 FROM tasks auto_task WHERE auto_task.auto_provisioned_node_id = ${alias}.id + ))`; +} diff --git a/apps/api/src/services/provisioned-node-ownership.ts b/apps/api/src/services/provisioned-node-ownership.ts new file mode 100644 index 0000000000..fe23b8d681 --- /dev/null +++ b/apps/api/src/services/provisioned-node-ownership.ts @@ -0,0 +1,25 @@ +import type { PlacementAuthoritySqlPredicate } from './placement-authority'; + +/** + * Reserve a task's provisioned node until placement or a terminal lifecycle state. + * Exclude the whole host to preserve exclusive and legacy reservations too. + * Applies at workspace admission, not node allocation validation during boot. + * The existing partial auto_provisioned_node_id index bounds each host lookup. + */ +export function buildProvisionedNodeHoldSqlPredicate( + nodeAlias: string, + requestingTaskId?: string | null +): PlacementAuthoritySqlPredicate { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(nodeAlias)) throw new Error('Unsafe SQL alias'); + const alias = nodeAlias; + return { + sql: `AND NOT EXISTS ( + SELECT 1 FROM tasks provisioned_node_owner + WHERE provisioned_node_owner.auto_provisioned_node_id = ${alias}.id + AND provisioned_node_owner.workspace_id IS NULL + AND provisioned_node_owner.status IN ('queued', 'delegated', 'in_progress') + AND provisioned_node_owner.id IS NOT ? + )`, + binds: [requestingTaskId ?? null], + }; +} diff --git a/apps/api/src/services/reusable-node-authority.ts b/apps/api/src/services/reusable-node-authority.ts index b56b398a58..e5b882fd01 100644 --- a/apps/api/src/services/reusable-node-authority.ts +++ b/apps/api/src/services/reusable-node-authority.ts @@ -2,6 +2,7 @@ import type { CapacityPlacementSnapshot } from '@simple-agent-manager/shared'; import { D1_MAX_BOUND_PARAMETERS } from '../lib/d1-limits'; import { buildPlacementAuthoritySqlPredicate } from './placement-authority'; +import { buildProvisionedNodeHoldSqlPredicate } from './provisioned-node-ownership'; export interface ReusableNodeAuthoritySelection { nodeId: string; @@ -17,6 +18,7 @@ export interface ReusableNodeAuthoritySelection { export async function filterReusableNodesByCurrentAuthority( database: D1Database, input: { + requestingTaskId?: string | null; userId: string; projectId: string; selections: readonly ReusableNodeAuthoritySelection[]; @@ -42,7 +44,8 @@ export async function filterReusableNodesByCurrentAuthority( capacityPlacementSnapshot: first.capacityPlacementSnapshot, authorityMode: 'existing-node', }); - const chunkSize = D1_MAX_BOUND_PARAMETERS - predicate.binds.length; + const hold = buildProvisionedNodeHoldSqlPredicate('n', input.requestingTaskId); + const chunkSize = D1_MAX_BOUND_PARAMETERS - predicate.binds.length - hold.binds.length; if (chunkSize <= 0) throw new Error('Placement authority exceeds D1 parameter limit'); for (let offset = 0; offset < selections.length; offset += chunkSize) { const ids = selections.slice(offset, offset + chunkSize).map((selection) => selection.nodeId); @@ -51,9 +54,10 @@ export async function filterReusableNodesByCurrentAuthority( `SELECT n.id FROM nodes n WHERE n.id IN (${ids.map(() => '?').join(', ')}) AND n.status = 'running' - ${predicate.sql}` + ${predicate.sql} + ${hold.sql}` ) - .bind(...ids, ...predicate.binds) + .bind(...ids, ...predicate.binds, ...hold.binds) .all<{ id: string }>(); for (const row of rows.results) eligible.add(row.id); } diff --git a/apps/api/src/services/session-sleep-eligibility.ts b/apps/api/src/services/session-sleep-eligibility.ts index 05d890c3b2..62ab44856a 100644 --- a/apps/api/src/services/session-sleep-eligibility.ts +++ b/apps/api/src/services/session-sleep-eligibility.ts @@ -10,6 +10,7 @@ import type { Env } from '../env'; import { parsePositiveInt } from '../lib/route-helpers'; import { resolveAdminSetting } from './admin-settings'; import { recordNodeLifecycleDecision } from './node-lifecycle-decisions'; +import { taskProvisionedNodeConditionSql } from './node-teardown-provenance'; import * as projectDataService from './project-data'; import { classifySessionIdleness, @@ -181,8 +182,7 @@ export async function checkAutomaticSessionSleepEligibility( nodeCreatedAt: schema.nodes.createdAt, nodeRole: schema.nodes.nodeRole, nodeClass: schema.nodes.nodeClass, - nodeAutoProvisioned: sql`EXISTS (SELECT 1 FROM tasks auto_task - WHERE auto_task.auto_provisioned_node_id = ${schema.workspaces.nodeId})`, + nodeAutoProvisioned: sql`${sql.raw(taskProvisionedNodeConditionSql('nodes'))}`, }) .from(schema.workspaces) .leftJoin(schema.nodes, eq(schema.nodes.id, schema.workspaces.nodeId)) diff --git a/apps/api/src/services/session-sleep-workspace.ts b/apps/api/src/services/session-sleep-workspace.ts index a26af01991..c61ef88d00 100644 --- a/apps/api/src/services/session-sleep-workspace.ts +++ b/apps/api/src/services/session-sleep-workspace.ts @@ -7,6 +7,7 @@ import { drizzle } from 'drizzle-orm/d1'; import * as schema from '../db/schema'; import type { Env } from '../env'; +import { taskProvisionedNodeConditionSql } from './node-teardown-provenance'; export async function loadSleepWorkspace(env: Env, workspaceId: string, userId: string) { const db = drizzle(env.DATABASE, { schema }); @@ -25,8 +26,7 @@ export async function loadSleepWorkspace(env: Env, workspaceId: string, userId: nodeCreatedAt: schema.nodes.createdAt, nodeRole: schema.nodes.nodeRole, nodeClass: schema.nodes.nodeClass, - nodeAutoProvisioned: sql`EXISTS (SELECT 1 FROM tasks auto_task - WHERE auto_task.auto_provisioned_node_id = ${schema.workspaces.nodeId})`, + nodeAutoProvisioned: sql`${sql.raw(taskProvisionedNodeConditionSql('nodes'))}`, taskId: schema.tasks.id, taskStatus: schema.tasks.status, taskCompletedAt: sql< diff --git a/apps/api/src/services/workspace-admission-sql.ts b/apps/api/src/services/workspace-admission-sql.ts index 1c46cc7f95..84eeb8e073 100644 --- a/apps/api/src/services/workspace-admission-sql.ts +++ b/apps/api/src/services/workspace-admission-sql.ts @@ -3,13 +3,12 @@ * the node scope, the requested and active reservations, and the eligibility predicate. * Split out of `workspace-placement.ts` (`.claude/rules/18-file-size-limits.md`). */ -import { - type WorkspaceAdmissionPolicy, -} from '@simple-agent-manager/scheduler-core'; +import { type WorkspaceAdmissionPolicy } from '@simple-agent-manager/scheduler-core'; import { resolveResourceReservation } from '@simple-agent-manager/shared'; import { lifetimeAdmissionCutoffSql } from './node-lifetime-admission'; import { buildPlacementAuthoritySqlPredicate } from './placement-authority'; +import { buildProvisionedNodeHoldSqlPredicate } from './provisioned-node-ownership'; import type { WorkspacePlacementInput } from './workspace-placement'; import { ACTIVE_WORKSPACE_RESERVATION_STATUS_SQL, @@ -26,6 +25,7 @@ export function buildWorkspaceAdmissionSql( | 'resolvedReservation' | 'capacityPlacementSnapshot' | 'authorityNodeClass' + | 'taskLifecycleGuard' >, policy: WorkspaceAdmissionPolicy, /** @@ -52,6 +52,7 @@ export function buildWorkspaceAdmissionSql( requireProjectMembership: true, authorityMode: 'existing-node', }); + const hold = buildProvisionedNodeHoldSqlPredicate('n', input.taskLifecycleGuard?.taskId); const requestedReservationJson = JSON.stringify(resolvedReservation); const admissionAt = new Date(); const admissionNow = admissionAt.toISOString(); @@ -107,7 +108,8 @@ export function buildWorkspaceAdmissionSql( AND n.user_id = ? AND n.status = 'running' AND n.node_role = 'workspace' - ${capacityPredicate.sql} + ${capacityPredicate.sql} + ${hold.sql} ${lifetimeCutoff.sql} ), requested_reservation AS ( @@ -163,6 +165,7 @@ export function buildWorkspaceAdmissionSql( input.nodeId, input.userId, ...capacityPredicate.binds, + ...hold.binds, ...lifetimeCutoff.binds, requestedReservationJson, resolvedReservation.cpuMillis, diff --git a/apps/api/tests/integration/capacity-pool-node-limit-handler.test.ts b/apps/api/tests/integration/capacity-pool-node-limit-handler.test.ts index 754fd10b96..b0b686bbf1 100644 --- a/apps/api/tests/integration/capacity-pool-node-limit-handler.test.ts +++ b/apps/api/tests/integration/capacity-pool-node-limit-handler.test.ts @@ -7,6 +7,7 @@ import type { TaskRunnerContext, TaskRunnerState, } from '../../src/durable-objects/task-runner/types'; +import { resumeWorkspacePlacementFallback } from '../../src/durable-objects/task-runner/workspace-placement-fallback'; import * as nodesService from '../../src/services/nodes'; import { capacityPoolMaxNodesMigrationSql } from '../helpers/capacity-pool-migrations'; import { createAllSchemaTables, createSqliteD1 } from '../helpers/sqlite-d1'; @@ -16,10 +17,12 @@ describe('capacity pool node-limit handler boundary', () => { afterEach(() => sqlite.close()); - it('translates the real trigger abort and never reaches provider provisioning', async () => { - sqlite = new Database(':memory:'); - createAllSchemaTables(sqlite, schema); - sqlite.exec(` + it.each([false, true])( + 'translates the real trigger abort, including after fallback (%s)', + async (afterFallback) => { + sqlite = new Database(':memory:'); + createAllSchemaTables(sqlite, schema); + sqlite.exec(` INSERT INTO users (id) VALUES ('user-1'); INSERT INTO tasks (id, project_id, user_id, status) VALUES ('task-1', 'project-1', 'user-1', 'queued'); INSERT INTO capacity_pools @@ -29,162 +32,177 @@ describe('capacity pool node-limit handler boundary', () => { (id, user_id, name, status, capacity_pool_id, node_role, node_class) VALUES ('existing-node', 'user-1', 'Existing', 'running', 'pool-1', 'workspace', 'managed'); `); - const triggerOffset = capacityPoolMaxNodesMigrationSql.indexOf('CREATE TRIGGER'); - if (triggerOffset < 0) throw new Error('capacity pool trigger missing from migration'); - sqlite.exec(capacityPoolMaxNodesMigrationSql.slice(triggerOffset)); + const triggerOffset = capacityPoolMaxNodesMigrationSql.indexOf('CREATE TRIGGER'); + if (triggerOffset < 0) throw new Error('capacity pool trigger missing from migration'); + sqlite.exec(capacityPoolMaxNodesMigrationSql.slice(triggerOffset)); - const snapshot = { - capacityPoolId: 'pool-1', - capacityPoolScope: 'user' as const, - capacityPoolRevision: 1, - capacitySourceId: 'source-1', - capacityPoolCandidateId: 'candidate-1', - placementCredentialSource: 'user' as const, - placementCredentialReference: 'credentials:credential-1', - placementCredentialVersion: 1, - capacityPoolProjectId: null, - workloadRole: 'workspace' as const, - providerInstanceType: 'cx42', - providerInstanceVcpuCount: 8, - providerInstanceMemoryMb: 16 * 1024, - providerInstanceDiskGb: 160, - placementExplanationJson: '{"kind":"capacity_pool_default"}', - }; - const state = { - version: 1, - taskId: 'task-1', - projectId: 'project-1', - userId: 'user-1', - currentStep: 'node_provisioning', - stepResults: { - nodeId: null, - autoProvisioned: false, - workspaceId: null, - chatSessionId: null, - agentSessionId: null, - agentStarted: false, - mcpToken: null, - provisionedVmSize: null, - capacityPlacementSnapshot: snapshot, - }, - config: { - vmSize: 'large', - vmLocation: 'fsn1', - branch: 'main', - preferredNodeId: null, - userName: null, - userEmail: null, - githubId: null, - taskTitle: 'Pool trigger race', - taskDescription: null, - repository: 'owner/repo', - installationId: 'install-1', - outputBranch: null, - defaultBranch: 'main', - projectDefaultVmSize: null, - chatSessionId: null, - agentType: null, - workspaceProfile: null, - devcontainerConfigName: null, - cloudProvider: 'hetzner', - credentialAttributionUserId: 'user-1', - credentialAttributionProjectId: null, - credentialAttributionSource: 'user', - taskMode: 'task', - model: null, - effort: null, - permissionMode: null, - systemPromptAppend: null, - agentProfileHint: null, - attachments: null, - projectScaling: null, - vmSizeSource: 'task', - resolvedReservation: { - version: 3, - cpuMillis: 1000, - memoryMb: 1024, - diskMb: 2048, - exclusiveNode: false, - source: 'task', - sourceId: 'task-1', + const snapshot = { + capacityPoolId: 'pool-1', + capacityPoolScope: 'user' as const, + capacityPoolRevision: 1, + capacitySourceId: 'source-1', + capacityPoolCandidateId: 'candidate-1', + placementCredentialSource: 'user' as const, + placementCredentialReference: 'credentials:credential-1', + placementCredentialVersion: 1, + capacityPoolProjectId: null, + workloadRole: 'workspace' as const, + providerInstanceType: 'cx42', + providerInstanceVcpuCount: 8, + providerInstanceMemoryMb: 16 * 1024, + providerInstanceDiskGb: 160, + placementExplanationJson: '{"kind":"capacity_pool_default"}', + }; + const state = { + version: 1, + taskId: 'task-1', + projectId: 'project-1', + userId: 'user-1', + currentStep: 'node_provisioning', + stepResults: { + nodeId: null, + autoProvisioned: false, + workspaceId: null, + chatSessionId: null, + agentSessionId: null, + agentStarted: false, + mcpToken: null, + provisionedVmSize: null, + capacityPlacementSnapshot: snapshot, }, - capacityPoolSelection: { - poolId: 'pool-1', - scope: 'user', - revision: 1, - strategy: 'pack', - exhaustionPolicy: 'fail', - maxNodes: 2, - capacityPoolProjectId: null, - workloadRole: 'workspace', - poolSnapshot: { ...snapshot, capacitySourceId: null, capacityPoolCandidateId: null }, - candidates: [ - { - id: 'candidate-1', - poolId: 'pool-1', - capacitySourceId: 'source-1', - provider: 'hetzner', - location: 'fsn1', - workloadRole: 'workspace', - runtime: 'vm', - machineClass: 'shared-vm', - machineSize: 'large', - providerInstanceType: 'cx42', - providerInstanceVcpuCount: 8, - providerInstanceMemoryMb: 16 * 1024, - providerInstanceDiskGb: 160, - priority: 0, - candidateOrder: 0, - credentialAttributionSource: 'user', - placementCredentialSource: 'user', - placementCredentialReference: 'credentials:credential-1', - placementCredentialVersion: 1, - capacityPoolProjectId: null, - snapshot, - }, - ], + config: { + vmSize: 'large', + vmLocation: 'fsn1', + branch: 'main', + preferredNodeId: null, + userName: null, + userEmail: null, + githubId: null, + taskTitle: 'Pool trigger race', + taskDescription: null, + repository: 'owner/repo', + installationId: 'install-1', + outputBranch: null, + defaultBranch: 'main', + projectDefaultVmSize: null, + chatSessionId: null, + agentType: null, + workspaceProfile: null, + devcontainerConfigName: null, + cloudProvider: 'hetzner', + credentialAttributionUserId: 'user-1', + credentialAttributionProjectId: null, + credentialAttributionSource: 'user', + taskMode: 'task', + model: null, + effort: null, + permissionMode: null, + systemPromptAppend: null, + agentProfileHint: null, + attachments: null, + projectScaling: null, + vmSizeSource: 'task', + resolvedReservation: { + version: 3, + cpuMillis: 1000, + memoryMb: 1024, + diskMb: 2048, + exclusiveNode: false, + source: 'task', + sourceId: 'task-1', + }, + capacityPoolSelection: { + poolId: 'pool-1', + scope: 'user', + revision: 1, + strategy: 'pack', + exhaustionPolicy: 'fail', + maxNodes: 2, + capacityPoolProjectId: null, + workloadRole: 'workspace', + poolSnapshot: { ...snapshot, capacitySourceId: null, capacityPoolCandidateId: null }, + candidates: [ + { + id: 'candidate-1', + poolId: 'pool-1', + capacitySourceId: 'source-1', + provider: 'hetzner', + location: 'fsn1', + workloadRole: 'workspace', + runtime: 'vm', + machineClass: 'shared-vm', + machineSize: 'large', + providerInstanceType: 'cx42', + providerInstanceVcpuCount: 8, + providerInstanceMemoryMb: 16 * 1024, + providerInstanceDiskGb: 160, + priority: 0, + candidateOrder: 0, + credentialAttributionSource: 'user', + placementCredentialSource: 'user', + placementCredentialReference: 'credentials:credential-1', + placementCredentialVersion: 1, + capacityPoolProjectId: null, + snapshot, + }, + ], + }, }, - }, - retryCount: 0, - workspaceReadyReceived: false, - workspaceReadyStatus: null, - workspaceErrorMessage: null, - createdAt: Date.now(), - lastStepAt: Date.now(), - provisioningStartedAt: null, - agentReadyStartedAt: null, - workspaceDispatchStartedAt: null, - workspaceDispatchAttempts: 0, - workspaceDispatchLastAttemptAt: null, - workspaceDispatchLastError: null, - workspaceDispatchAckedAt: null, - lastD1Step: null, - completed: false, - } as unknown as TaskRunnerState; - const database = createSqliteD1(sqlite); - const rc = { - env: { - DATABASE: database, - MAX_NODES_PER_USER: '10', - COMPUTE_QUOTA_ENFORCEMENT_ENABLED: 'false', - }, - ctx: { - storage: { put: vi.fn(async () => undefined), setAlarm: vi.fn(async () => undefined) }, - }, - assertRecoveryAuthority: vi.fn(async () => undefined), - advanceToStep: vi.fn(async () => undefined), - getProvisionPollIntervalMs: () => 1000, - getProvisionTimeoutMs: () => 600_000, - updateD1ExecutionStep: vi.fn(async () => undefined), - } as unknown as TaskRunnerContext; - const provisionSpy = vi.spyOn(nodesService, 'provisionNode'); + retryCount: 0, + workspaceReadyReceived: false, + workspaceReadyStatus: null, + workspaceErrorMessage: null, + createdAt: Date.now(), + lastStepAt: Date.now(), + provisioningStartedAt: null, + agentReadyStartedAt: null, + workspaceDispatchStartedAt: null, + workspaceDispatchAttempts: 0, + workspaceDispatchLastAttemptAt: null, + workspaceDispatchLastError: null, + workspaceDispatchAckedAt: null, + lastD1Step: null, + completed: false, + } as unknown as TaskRunnerState; + const database = createSqliteD1(sqlite); + const rc = { + env: { + DATABASE: database, + MAX_NODES_PER_USER: '10', + COMPUTE_QUOTA_ENFORCEMENT_ENABLED: 'false', + }, + ctx: { + storage: { put: vi.fn(async () => undefined), setAlarm: vi.fn(async () => undefined) }, + }, + assertRecoveryAuthority: vi.fn(async () => undefined), + advanceToStep: vi.fn(async () => undefined), + getProvisionPollIntervalMs: () => 1000, + getProvisionTimeoutMs: () => 600_000, + updateD1ExecutionStep: vi.fn(async () => undefined), + } as unknown as TaskRunnerContext; + const provisionSpy = vi.spyOn(nodesService, 'provisionNode'); + + if (afterFallback) { + sqlite.exec( + "UPDATE nodes SET runtime = 'vm' WHERE id = 'existing-node'; UPDATE tasks SET auto_provisioned_node_id = 'existing-node' WHERE id = 'task-1'" + ); + state.stepResults.nodeId = 'existing-node'; + state.stepResults.autoProvisioned = true; + state.rejectedAutoProvisionedNodeId = 'existing-node'; + expect(await resumeWorkspacePlacementFallback(state, rc)).toBe(true); + expect(state.stepResults.nodeId).toBeNull(); + expect( + sqlite.prepare("SELECT task_provisioned FROM nodes WHERE id = 'existing-node'").get() + ).toEqual({ task_provisioned: 1 }); + } - await expect(handleNodeProvisioning(state, rc)).rejects.toMatchObject({ - message: 'Capacity pool node limit (2) reached and no node can fit the request.', - permanent: true, - }); + await expect(handleNodeProvisioning(state, rc)).rejects.toMatchObject({ + message: 'Capacity pool node limit (2) reached and no node can fit the request.', + permanent: true, + }); - expect(provisionSpy).not.toHaveBeenCalled(); - expect(sqlite.prepare(`SELECT COUNT(*) AS count FROM nodes`).get()).toEqual({ count: 1 }); - }); + expect(provisionSpy).not.toHaveBeenCalled(); + expect(sqlite.prepare(`SELECT COUNT(*) AS count FROM nodes`).get()).toEqual({ count: 1 }); + } + ); }); diff --git a/apps/api/tests/integration/provisioned-node-fallback-admission.test.ts b/apps/api/tests/integration/provisioned-node-fallback-admission.test.ts new file mode 100644 index 0000000000..e489ef7068 --- /dev/null +++ b/apps/api/tests/integration/provisioned-node-fallback-admission.test.ts @@ -0,0 +1,269 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { buildAdmissionIdentity } from '../../src/durable-objects/task-runner/node-provisioning-admission'; +import { handleNodeProvisioning } from '../../src/durable-objects/task-runner/node-steps'; +import type { TaskRunnerState } from '../../src/durable-objects/task-runner/types'; +import { resumeWorkspacePlacementFallback } from '../../src/durable-objects/task-runner/workspace-placement-fallback'; +import * as nodesService from '../../src/services/nodes'; +import { tryAcquireVmProvisioningLease } from '../../src/services/vm-admission-control'; +import { createIncompatibleCapacityFixture } from '../helpers/incompatible-agent-capacity-fixture'; + +// Real fallback, provisioning handlers, credential resolution, lease SQL and pool trigger. +// SQLite replaces D1; storage/alarm scheduling and provider HTTP are the boundaries simulated. +let fixture: ReturnType; + +beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-10-05T12:00:00.000Z')); + fixture = createIncompatibleCapacityFixture(); +}); + +afterEach(() => { + fixture?.sqlite.close(); + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +async function fallback(state = fixture.state, nodeId = 'existing-node') { + fixture.sqlite + .prepare('UPDATE tasks SET auto_provisioned_node_id = ? WHERE id = ?') + .run(nodeId, state.taskId); + state.stepResults.nodeId = nodeId; + state.stepResults.autoProvisioned = true; + state.rejectedAutoProvisionedNodeId = nodeId; + expect(await resumeWorkspacePlacementFallback(state, fixture.rc)).toBe(true); + expect(state.stepResults.nodeId).toBeNull(); + expect(state.admissionScopeKey).toBeNull(); + expect(state.admissionLeaseToken).toBeNull(); + expect( + fixture.sqlite + .prepare('SELECT auto_provisioned_node_id FROM tasks WHERE id = ?') + .get(state.taskId) + ).toEqual({ auto_provisioned_node_id: null }); +} + +function admission(taskId = fixture.state.taskId) { + return fixture.sqlite + .prepare( + 'SELECT state, reason, wait_deadline_at, next_retry_at FROM vm_task_admissions WHERE task_id = ?' + ) + .get(taskId) as { + state: string; + reason: string; + wait_deadline_at: string; + next_retry_at: string | null; + }; +} + +describe('normal admission after provisioned-node fallback', () => { + it.each(['capacity_pool_node_limit', 'user_node_limit'] as const)( + 'keeps the original %s queue deadline through retries, then expires without allocation', + async (reason) => { + const { sqlite, state, rc } = fixture; + const provision = vi.spyOn(nodesService, 'provisionNode'); + rc.env.VM_ADMISSION_WAIT_TIMEOUT_MS = '5000'; + if (reason === 'user_node_limit') { + state.config.capacityPoolSelection!.maxNodes = 2; + sqlite.exec('UPDATE capacity_pools SET max_nodes = 2'); + rc.env.MAX_NODES_PER_USER = '1'; + } + // Start with the owner's real fenced lease; fallback must relinquish it before queueing. + const identity = await buildAdmissionIdentity(state, rc); + expect(identity).not.toBeNull(); + if (!identity) throw new Error('Missing fixture admission identity'); + const grant = await tryAcquireVmProvisioningLease(rc.env, identity); + expect(grant.kind).toBe('granted'); + if (grant.kind !== 'granted') throw new Error('Expected initial lease'); + state.admissionScopeKey = grant.scopeKey; + state.admissionLeaseToken = grant.fencingToken; + await fallback(); + expect(sqlite.prepare('SELECT COUNT(*) AS count FROM vm_provisioning_leases').get()).toEqual({ + count: 0, + }); + + await handleNodeProvisioning(state, rc); + const first = admission(); + expect(first).toMatchObject({ state: 'waiting', reason }); + expect(first.wait_deadline_at).toBe(new Date(Date.now() + 5000).toISOString()); + expect(rc.ctx.storage.setAlarm).toHaveBeenLastCalledWith(Date.now() + 1000); + for (let retry = 0; retry < 4; retry++) { + vi.advanceTimersByTime(1000); + await handleNodeProvisioning(state, rc); + expect(admission()).toMatchObject({ + state: 'waiting', + reason, + wait_deadline_at: first.wait_deadline_at, + }); + } + vi.advanceTimersByTime(1000); + await expect(handleNodeProvisioning(state, rc)).rejects.toMatchObject({ permanent: true }); + expect(admission()).toMatchObject({ + state: 'expired', + reason: 'wait_deadline_expired', + next_retry_at: null, + }); + expect( + sqlite + .prepare('SELECT admission_state, admission_reason FROM tasks WHERE id = ?') + .get(state.taskId) + ).toEqual({ admission_state: 'expired', admission_reason: 'wait_deadline_expired' }); + expect(sqlite.prepare('SELECT COUNT(*) AS count FROM nodes').get()).toEqual({ count: 1 }); + expect(sqlite.prepare('SELECT status FROM nodes WHERE id = ?').get('existing-node')).toEqual({ + status: 'running', + }); + expect( + sqlite.prepare('SELECT status FROM workspaces WHERE id = ?').get('old-workspace') + ).toEqual({ status: 'running' }); + expect(provision).not.toHaveBeenCalled(); + } + ); + + it('serializes two fallback owners through one real provisioning lease before provider allocation', async () => { + const { sqlite, state, rc } = fixture; + sqlite.exec(` + UPDATE capacity_pools SET max_nodes = 4; + INSERT INTO nodes (id, user_id, name, status, capacity_pool_id, runtime, node_role, node_class) + VALUES ('second-rejected-node', 'user-1', 'Second occupied host', 'running', 'pool-1', 'vm', 'workspace', 'managed'); + INSERT INTO tasks (id, project_id, user_id, status) + VALUES ('task-2', 'project-1', 'user-1', 'queued'); + INSERT INTO workspaces (id, user_id, node_id, project_id, status, resolved_reservation_json) + SELECT 'second-occupied-workspace', user_id, 'second-rejected-node', project_id, status, resolved_reservation_json + FROM workspaces WHERE id = 'old-workspace'; + `); + // Leave room for both requests: the lease, rather than the pool trigger, must serialize + // provider allocation. The separate limit tests exercise a pool with no free slot. + state.config.capacityPoolSelection!.maxNodes = 4; + const second = structuredClone(state); + second.taskId = 'task-2'; + await fallback(state); + await fallback(second, 'second-rejected-node'); + + let announceProvider!: () => void; + let announceDuplicate!: () => void; + let finishProvider!: () => void; + const providerStarted = new Promise((resolve) => { + announceProvider = resolve; + }); + const duplicateProviderStarted = new Promise((resolve) => { + announceDuplicate = resolve; + }); + const providerReleased = new Promise((resolve) => { + finishProvider = resolve; + }); + let providerCalls = 0; + const provision = vi.spyOn(nodesService, 'provisionNode').mockImplementation(async (nodeId) => { + if (++providerCalls > 1) announceDuplicate(); + announceProvider(); + await providerReleased; + sqlite + .prepare( + "UPDATE nodes SET status = 'running', agent_version = 'current-agent' WHERE id = ?" + ) + .run(nodeId); + }); + const runs = [handleNodeProvisioning(state, rc), handleNodeProvisioning(second, rc)]; + // Stop exactly at provider HTTP: the winner has recorded its inflight node, while the + // loser must finish by entering the shared queue rather than issuing another request. + try { + await providerStarted; + const loser = await Promise.race([ + ...runs.map((run, index) => run.then(() => index)), + duplicateProviderStarted.then(() => -1), + ]); + // A removed lease fence reports the extra provider call directly, without waiting for + // a timeout on two provider requests that are both deliberately paused. + expect(provision).toHaveBeenCalledTimes(1); + const losingState: TaskRunnerState = loser === 0 ? state : second; + expect(admission(losingState.taskId)).toMatchObject({ + state: 'waiting', + reason: 'compatible_node_provisioning', + }); + expect(sqlite.prepare('SELECT COUNT(*) AS count FROM vm_provisioning_leases').get()).toEqual({ + count: 1, + }); + expect( + sqlite.prepare("SELECT COUNT(*) AS count FROM nodes WHERE status = 'creating'").get() + ).toEqual({ count: 1 }); + } finally { + finishProvider(); + await Promise.allSettled(runs); + } + await Promise.all(runs); + expect(provision).toHaveBeenCalledTimes(1); + expect(sqlite.prepare('SELECT COUNT(*) AS count FROM nodes').get()).toEqual({ count: 3 }); + expect( + sqlite.prepare("SELECT COUNT(*) AS count FROM workspaces WHERE status = 'running'").get() + ).toEqual({ count: 2 }); + }); +}); + +// Security review (2026-11-19): the fallback stamps node-local provenance and releases the task +// pointer. Each attack below must stamp nothing, release nothing and refuse the handoff, while the +// owner path above (`fallback()`) proves the same fixture does stamp and release. +describe('provisioned-node fallback ownership scoping', () => { + function stamped(nodeId = 'existing-node') { + const row = fixture.sqlite + .prepare('SELECT task_provisioned FROM nodes WHERE id = ?') + .get(nodeId) as { task_provisioned: number | null }; + return row.task_provisioned === 1; + } + function pointer() { + return fixture.sqlite + .prepare('SELECT auto_provisioned_node_id FROM tasks WHERE id = ?') + .get(fixture.state.taskId); + } + function arm(state: TaskRunnerState, nodeId = 'existing-node') { + fixture.sqlite + .prepare('UPDATE tasks SET auto_provisioned_node_id = ? WHERE id = ?') + .run(nodeId, fixture.state.taskId); + state.stepResults.nodeId = nodeId; + state.stepResults.autoProvisioned = true; + state.rejectedAutoProvisionedNodeId = nodeId; + } + + it('owner control: stamps the owned node and releases the pointer', async () => { + await fallback(); + expect(stamped()).toBe(true); + }); + + it("refuses a pointer to another user's node", async () => { + fixture.sqlite.exec(` + INSERT INTO nodes (id, user_id, name, status, capacity_pool_id, runtime, node_role, node_class) + VALUES ('foreign-node', 'user-2', 'Foreign host', 'running', 'pool-1', 'vm', 'workspace', 'managed'); + `); + arm(fixture.state, 'foreign-node'); + await expect(resumeWorkspacePlacementFallback(fixture.state, fixture.rc)).rejects.toThrow(); + expect(stamped('foreign-node')).toBe(false); + expect(pointer()).toEqual({ auto_provisioned_node_id: 'foreign-node' }); + }); + + it('refuses a task row owned by another user', async () => { + arm(fixture.state); + fixture.sqlite + .prepare("UPDATE tasks SET user_id = 'user-2' WHERE id = ?") + .run(fixture.state.taskId); + await expect(resumeWorkspacePlacementFallback(fixture.state, fixture.rc)).rejects.toThrow(); + expect(stamped()).toBe(false); + expect(pointer()).toEqual({ auto_provisioned_node_id: 'existing-node' }); + }); + + it('refuses when both the task and the node belong to another user than the runner', async () => { + arm(fixture.state); + fixture.sqlite.exec("UPDATE nodes SET user_id = 'user-2' WHERE id = 'existing-node'"); + fixture.sqlite + .prepare("UPDATE tasks SET user_id = 'user-2' WHERE id = ?") + .run(fixture.state.taskId); + await expect(resumeWorkspacePlacementFallback(fixture.state, fixture.rc)).rejects.toThrow(); + expect(stamped()).toBe(false); + expect(pointer()).toEqual({ auto_provisioned_node_id: 'existing-node' }); + }); + + it("refuses when the runner's project does not own the task", async () => { + const foreignProject = structuredClone(fixture.state); + foreignProject.projectId = 'project-2'; + arm(foreignProject); + await expect(resumeWorkspacePlacementFallback(foreignProject, fixture.rc)).rejects.toThrow(); + expect(stamped()).toBe(false); + expect(pointer()).toEqual({ auto_provisioned_node_id: 'existing-node' }); + }); +}); diff --git a/apps/api/tests/unit/services/provisioned-node-history.test.ts b/apps/api/tests/unit/services/provisioned-node-history.test.ts new file mode 100644 index 0000000000..bb6a52c6c2 --- /dev/null +++ b/apps/api/tests/unit/services/provisioned-node-history.test.ts @@ -0,0 +1,52 @@ +import Database from 'better-sqlite3'; +import { afterEach, describe, expect, it } from 'vitest'; + +import * as schema from '../../../src/db/schema'; +import { isNodePastLifetimeAdmissionCutoff } from '../../../src/services/node-lifetime-admission'; +import { cleanupNodeProvenanceSql } from '../../../src/services/node-teardown-provenance'; +import { buildProvisionedNodeHoldSqlPredicate } from '../../../src/services/provisioned-node-ownership'; +import { + createAllSchemaTables, + createDeclaredIndexes, + createSqliteD1, +} from '../../helpers/sqlite-d1'; + +describe('released provisioned-node history', () => { + let sqlite: Database.Database; + afterEach(() => sqlite?.close()); + + it('retains indexed cleanup and lifetime provenance without retaining a placement hold', async () => { + sqlite = new Database(':memory:'); + createAllSchemaTables(sqlite, schema); + createDeclaredIndexes(sqlite, [schema.tasks]); + sqlite.exec(` + INSERT INTO nodes(id, user_id, node_class, runtime, node_role, status, created_at) + VALUES ('rejected', 'user-1', 'managed', 'vm', 'workspace', 'running', '2000-01-01T00:00:00.000Z'); + UPDATE nodes SET task_provisioned = 1 WHERE id = 'rejected'; + WITH RECURSIVE history(i) AS (VALUES(1) UNION ALL SELECT i + 1 FROM history WHERE i < 100000) + INSERT INTO tasks(id, status) SELECT 'old-' || i, 'completed' FROM history; + INSERT INTO tasks(id, user_id, project_id, status, auto_provisioned_node_id) + VALUES ('owner', 'user-1', 'project-1', 'queued', NULL); + `); + const database = createSqliteD1(sqlite); + const hold = buildProvisionedNodeHoldSqlPredicate('n', 'contender'); + const cleanupSql = `SELECT n.id FROM nodes n WHERE ${cleanupNodeProvenanceSql('n', true)}`; + expect(sqlite.prepare(cleanupSql).all()).toEqual([{ id: 'rejected' }]); + expect( + sqlite.prepare(`SELECT n.id FROM nodes n WHERE 1=1 ${hold.sql}`).all(...hold.binds) + ).toEqual([{ id: 'rejected' }]); + expect(await isNodePastLifetimeAdmissionCutoff(database, 'rejected', 1000)).toBe(true); + const plan = sqlite.prepare(`EXPLAIN QUERY PLAN ${cleanupSql}`).all() as { detail: string }[]; + + expect(plan.map((row) => row.detail).join('\n')).not.toMatch(/SCAN auto_task/); + const holdPlan = sqlite + .prepare(`EXPLAIN QUERY PLAN SELECT n.id FROM nodes n WHERE 1=1 ${hold.sql}`) + .all(...hold.binds) as { detail: string }[]; + expect(holdPlan.map((row) => row.detail).join('\n')).toContain( + 'idx_tasks_auto_provisioned_node' + ); + sqlite.exec("UPDATE nodes SET task_provisioned = 0 WHERE id = 'rejected'"); + expect(sqlite.prepare(cleanupSql).all()).toEqual([]); + expect(await isNodePastLifetimeAdmissionCutoff(database, 'rejected', 1000)).toBe(false); + }); +}); diff --git a/apps/api/tests/unit/services/workspace-placement.test.ts b/apps/api/tests/unit/services/workspace-placement.test.ts index 6e74c6475a..3b9fb48440 100644 --- a/apps/api/tests/unit/services/workspace-placement.test.ts +++ b/apps/api/tests/unit/services/workspace-placement.test.ts @@ -8,18 +8,19 @@ import type { ResolvedResourceReservation, } from '@simple-agent-manager/shared'; import Database from 'better-sqlite3'; -import { afterEach, describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import * as schema from '../../../src/db/schema'; +import type { TaskRunnerContext, TaskRunnerState } from '../../../src/durable-objects/task-runner/types'; +import { tryClaimWarmNode } from '../../../src/durable-objects/task-runner/warm-node-claim'; import { isNodePastLifetimeAdmissionCutoff } from '../../../src/services/node-lifetime-admission'; +import { filterReusableNodesByCurrentAuthority } from '../../../src/services/reusable-node-authority'; import { attachPrecreatedWorkspacePlacement, reserveWorkspacePlacement, reserveWorkspaceRestart, } from '../../../src/services/workspace-placement'; -import { - loadActiveWorkspaceReservationUsage, -} from '../../../src/services/workspace-reservation-usage'; +import { loadActiveWorkspaceReservationUsage } from '../../../src/services/workspace-reservation-usage'; import { createAllSchemaTables, createSqliteD1, @@ -1861,3 +1862,219 @@ describe('lifetime admission cutoff at every new-placement atomic admission (pol ).toBe(true); }); }); + +describe('auto-provisioned node owner hold', () => { + function seedOwner(status = 'queued', workspaceId: string | null = null) { + sqlite + ?.prepare( + `INSERT INTO tasks + (id, project_id, user_id, title, status, auto_provisioned_node_id, workspace_id, created_at, updated_at) + VALUES ('owner', 'project-1', 'user-1', 'Owner', ?, 'node-1', ?, ?, ?)` + ) + .run(status, workspaceId, AUTHORITY_TIMESTAMP, AUTHORITY_TIMESTAMP); + } + + function select(database: ReturnType, requestingTaskId?: string) { + return filterReusableNodesByCurrentAuthority(database, { + userId: 'user-1', + projectId: 'project-1', + requestingTaskId, + selections: [{ nodeId: 'node-1', capacityPlacementSnapshot: capacitySnapshot() }], + }); + } + + it.each(['owner', 'contender'])('revalidates warm discovery at the claim boundary (%s)', async (requester) => { + const database = createDb(); + seedNode({ capacity_pool_id: null, capacity_pool_scope: null, capacity_pool_revision: null, + capacity_source_id: null, capacity_pool_candidate_id: null, capacity_pool_project_id: null, + warm_since: new Date().toISOString() }); + sqlite?.exec('DELETE FROM capacity_pools'); + sqlite?.prepare('INSERT INTO tasks(id, user_id, project_id, status) VALUES (?, ?, ?, ?)') + .run(requester, 'user-1', 'project-1', 'queued'); + let authorityReads = 0; + const prepare = database.prepare.bind(database); + vi.spyOn(database, 'prepare').mockImplementation((query) => { + const statement = prepare(query); + if (!query.includes('SELECT n.id FROM nodes n')) return statement; + const bind = statement.bind.bind(statement); + statement.bind = (...values) => { + const bound = bind(...values); + const all = bound.all.bind(bound); + Object.defineProperty(bound, 'all', { value: async () => { + const result = await all(); + if (++authorityReads === 1) { + if (requester === 'owner') sqlite?.exec("DELETE FROM tasks WHERE id = 'owner'"); + seedOwner(); // Owner claim arrives AFTER discovery, BEFORE the final warm claim. + } + return result; + }}); + return bound; + }; + return statement; + }); + const tryClaim = vi.fn(async () => { + await database.prepare('UPDATE tasks SET claimed_warm_node_id = ? WHERE id = ?').bind('node-1', requester).run(); + return { claimed: true }; + }); + const state = { taskId: requester, userId: 'user-1', projectId: 'project-1', stepResults: {}, + config: { vmSize: 'large', vmLocation: 'fsn1', resolvedReservation: reservation(), projectScaling: {} } + } as unknown as TaskRunnerState; + const rc = { env: { DATABASE: database, NODE_LIFECYCLE: { idFromName: (id: string) => id, get: () => ({ tryClaim }) } }, + ctx: { storage: { put: async () => undefined } }, assertRecoveryAuthority: async () => undefined + } as unknown as TaskRunnerContext; + const result = await tryClaimWarmNode(state, rc); + expect(authorityReads).toBe(2); + expect(tryClaim).toHaveBeenCalledTimes(requester === 'owner' ? 1 : 0); + if (requester === 'owner') expect(result?.nodeId).toBe('node-1'); + else expect(result).toBeNull(); + expect(sqlite?.prepare('SELECT claimed_warm_node_id AS nodeId FROM tasks WHERE id = ?').get(requester)) + .toEqual({ nodeId: requester === 'owner' ? 'node-1' : null }); + }); + + it.each(['queued', 'delegated', 'in_progress'])( + 'holds an unplaced %s owner node in selection and atomic admission', + async (status) => { + const database = createDb(); + seedNode(); + seedOwner(status); + expect(await select(database)).toEqual(new Set()); + expect( + await reserveWorkspacePlacement( + database, + reserveInput(capacitySnapshot()), + admissionPolicy() + ) + ).toBe(false); + expect(sqlite?.prepare('SELECT id FROM workspaces').all()).toEqual([]); + } + ); + + it('admits the owner onto its held node', async () => { + const database = createDb(); + seedNode(); + seedOwner(); + expect(await select(database, 'owner')).toEqual(new Set(['node-1'])); + expect( + await reserveWorkspacePlacement( + database, + { + ...reserveInput(capacitySnapshot()), + taskLifecycleGuard: { + taskId: 'owner', + projectId: 'project-1', + userId: 'user-1', + chatSessionId: null, + }, + }, + admissionPolicy() + ) + ).toBe(true); + }); + + it.each(['failed', 'cancelled', 'completed', 'placed', 'unowned'])( + 'reuses a node after its owner is %s', + async (state) => { + const database = createDb(); + seedNode(); + if (state !== 'unowned') + seedOwner( + state === 'placed' ? 'in_progress' : state, + state === 'placed' ? 'owner-workspace' : null + ); + expect(await select(database)).toEqual(new Set(['node-1'])); + expect( + await reserveWorkspacePlacement( + database, + reserveInput(capacitySnapshot()), + admissionPolicy() + ) + ).toBe(true); + } + ); + + it.each(['insert', 'attach', 'restart'] as const)( + 'rechecks a hold acquired after %s selection at the final atomic mutation', + async (path) => { + const database = createDb(); + seedNode(); + expect(await select(database)).toEqual(new Set(['node-1'])); + if (path === 'attach') seedPlaceholderWorkspace('workspace-1'); + if (path === 'restart') { + seedActiveWorkspace('workspace-1', JSON.stringify(reservation())); + sqlite?.exec("UPDATE workspaces SET status = 'stopped' WHERE id = 'workspace-1'"); + } + seedOwner(); + const admit = () => + path === 'insert' + ? reserveWorkspacePlacement( + database, + reserveInput(capacitySnapshot()), + admissionPolicy() + ) + : path === 'attach' + ? attachPrecreatedWorkspacePlacement( + database, + reserveInput(capacitySnapshot()), + admissionPolicy() + ) + : reserveWorkspaceRestart( + database, + { + ...reserveInput(capacitySnapshot()), + resolvedReservation: reservation(), + chatSessionId: null, + evictionGeneration: 'new-generation', + expectedEvictionGeneration: null, + expectedStatus: 'stopped', + }, + admissionPolicy() + ); + expect(await admit()).toBe(false); + expect( + sqlite + ?.prepare("SELECT id FROM workspaces WHERE node_id = 'node-1' AND status = 'creating'") + .all() + ).toEqual([]); + sqlite?.exec("UPDATE tasks SET status = 'failed' WHERE id = 'owner'"); + expect(await admit()).toBe(true); + } + ); + + it('keeps owner admission and large reusable selection within the D1 bind limit', async () => { + createDb(); + if (!sqlite) throw new Error('SQLite fixture was not initialized'); + const database = createSqliteD1WithBindLimit(sqlite, 100); + seedNode({ created_at: new Date().toISOString() }); + seedOwner(); + const selections = Array.from({ length: 125 }, (_, i) => { + const nodeId = `extra-${i}`; + insertNodeRow({ id: nodeId }); + return { nodeId, capacityPlacementSnapshot: capacitySnapshot() }; + }); + expect( + ( + await filterReusableNodesByCurrentAuthority(database, { + userId: 'user-1', + projectId: 'project-1', + requestingTaskId: 'owner', + selections, + }) + ).size + ).toBe(125); + expect( + await reserveWorkspacePlacement( + database, + { + ...reserveInput(capacitySnapshot()), + taskLifecycleGuard: { + taskId: 'owner', + projectId: 'project-1', + userId: 'user-1', + chatSessionId: null, + }, + }, + admissionPolicy({ lifetimeAdmissionCutoffAgeMs: 0.9 * 24 * 60 * 60 * 1000 }) + ) + ).toBe(true); + }); +}); diff --git a/apps/api/tests/workers/provisioned-node-placement-admission.test.ts b/apps/api/tests/workers/provisioned-node-placement-admission.test.ts index f9c4b26249..239d0c2ee6 100644 --- a/apps/api/tests/workers/provisioned-node-placement-admission.test.ts +++ b/apps/api/tests/workers/provisioned-node-placement-admission.test.ts @@ -1,6 +1,6 @@ /** * A node auto-provisioned for a task must admit that task, and a node that cannot must - * fail the task fast instead of spinning in a replan loop. + * get one bounded fallback to normal placement instead of spinning in a replan loop. * * 2026-11-05 staging: a 3.5 GB task provisioned a cx23 (4096 MB); admission charged the * node's measured host use (459 MB) on top of the 512 MB host reserve and refused it. The @@ -32,6 +32,7 @@ import { } from '../../src/durable-objects/task-runner/workspace-placement-rejection'; import type { Env } from '../../src/env'; import { invalidateAdminSettings } from '../../src/services/admin-settings-resolution'; +import { isNodePastLifetimeAdmissionCutoff } from '../../src/services/node-lifetime-admission'; import { seedInstallation, seedNode, @@ -68,7 +69,7 @@ beforeAll(async () => { async function seedProvisionedCx23( nodeId: string, taskId: string, - metrics: { memoryPercent: number; creatingWorkspaces?: number } + metrics: { memoryPercent: number; creatingWorkspaces?: number; memoryMb?: number } ): Promise { const now = new Date().toISOString(); await seedNode(nodeId, USER_ID, { vmSize: 'small', lastHeartbeatAt: now }); @@ -85,8 +86,8 @@ async function seedProvisionedCx23( ) .bind( `server-${nodeId}`, - CX23_MEMORY_MB, - CX23_MEMORY_MB, + metrics.memoryMb ?? CX23_MEMORY_MB, + metrics.memoryMb ?? CX23_MEMORY_MB, now, JSON.stringify({ version: 1, @@ -165,6 +166,16 @@ function taskRunner(taskId: string): DurableObjectStub { return env.TASK_RUNNER.get(env.TASK_RUNNER.idFromName(taskId)) as DurableObjectStub; } +/** Keep immediate production alarms from racing this test's explicitly stepped alarms. */ +async function withPausedAlarms( + taskId: string, + fn: (instance: TaskRunner) => Promise +): Promise { + return runInDurableObject(taskRunner(taskId), (instance) => + instance.ctx.blockConcurrencyWhile(() => fn(instance)) + ); +} + /** Start the runner as if node_provisioning had just handed it the node it created. */ async function startAtWorkspaceCreation( taskId: string, @@ -172,6 +183,7 @@ async function startAtWorkspaceCreation( memoryMb: number, options: { priorRejections?: number; + priorFallback?: boolean; preferred?: boolean; /** Share the node with other workspaces: a small, non-exclusive reservation. */ shared?: boolean; @@ -180,7 +192,7 @@ async function startAtWorkspaceCreation( } = {} ): Promise { const preferred = options.preferred === true; - await runInDurableObject(taskRunner(taskId), async (instance) => { + await withPausedAlarms(taskId, async (instance) => { await instance.start(taskRunnerInput(taskId, memoryMb, preferred ? nodeId : null)); await instance.ctx.storage.deleteAlarm(); const state = await instance.ctx.storage.get('state'); @@ -191,6 +203,7 @@ async function startAtWorkspaceCreation( state.stepResults.autoProvisioned = !preferred; state.provisioningStartedAt = Date.now(); state.workspacePlacementRejections = options.priorRejections ?? 0; + if (options.priorFallback) state.rejectedAutoProvisionedNodeId = 'earlier-rejected-node'; if (options.shared && state.config.resolvedReservation) { state.config.resolvedReservation = { ...state.config.resolvedReservation, @@ -206,7 +219,7 @@ async function startAtWorkspaceCreation( /** Fire the runner's alarm once; returns the step it ran and the state it left. */ async function fireAlarm(taskId: string): Promise<{ ran: string; state: TaskRunnerState }> { - return runInDurableObject(taskRunner(taskId), async (instance) => { + return withPausedAlarms(taskId, async (instance) => { const before = await instance.ctx.storage.get('state'); await instance.alarm(); await instance.ctx.storage.deleteAlarm(); @@ -296,6 +309,13 @@ function placementNotes(placement: string | null): string[] { describe('a node provisioned for a task admits that task', () => { afterEach(async () => { await setMaxRejections(null); + // This workerd pool shares D1 within a file. Completed fixtures must not become + // alternative capacity for a later test's explicitly controlled placement episode. + await env.DATABASE.batch([ + env.DATABASE.prepare('DELETE FROM workspaces WHERE user_id = ?').bind(USER_ID), + env.DATABASE.prepare('DELETE FROM tasks WHERE user_id = ?').bind(USER_ID), + env.DATABASE.prepare('DELETE FROM nodes WHERE user_id = ?').bind(USER_ID), + ]); }); it('resolves the shared defaults through the real resolver', () => { @@ -338,6 +358,121 @@ describe('a node provisioned for a task admits that task', () => { expect(await activeWorkspacesOn(nodeId)).toBe(1); }); + it.each([ + ['ranked', false], + ['ranked', true], + ['pinned', false], + ['pinned', true], + ['warm', false], + ['warm', true], + ] as const)('holds A’s 8 GB booting node from B (%s, exclusive: %s)', async (path, exclusive) => { + const nodeId = `node-booting-owner-a-${path}-${exclusive}`; + const ownerId = `task-booting-owner-a-${path}-${exclusive}`; + const contenderId = `task-booting-contender-b-${path}-${exclusive}`; + await seedProvisionedCx23(nodeId, ownerId, { memoryPercent: 10, memoryMb: 8192 }); + await env.DATABASE.prepare("UPDATE nodes SET status = 'creating' WHERE id = ?") + .bind(nodeId) + .run(); + await seedTask(contenderId, PROJECT_ID, USER_ID, { status: 'queued', taskMode: 'task' }); + await startAtWorkspaceCreation(ownerId, nodeId, 4096, { shared: !exclusive }); + await withPausedAlarms(contenderId, async (instance) => { + const input = taskRunnerInput(contenderId, 4096, path === 'pinned' ? nodeId : null); + if (input.config.resolvedReservation) + input.config.resolvedReservation.exclusiveNode = exclusive; + await instance.start(input); + await instance.ctx.storage.deleteAlarm(); + const state = await instance.ctx.storage.get('state'); + if (!state) throw new Error('Missing contender state'); + state.currentStep = 'node_selection'; + await instance.ctx.storage.put('state', state); + }); + // N becomes ready before B selects capacity, as in the production incident. + await env.DATABASE.prepare("UPDATE nodes SET status = 'running' WHERE id = ?") + .bind(nodeId) + .run(); + if (path === 'warm') + await env.DATABASE.prepare('UPDATE nodes SET warm_since = ? WHERE id = ?') + .bind(new Date().toISOString(), nodeId) + .run(); + const contender = (await fireAlarm(contenderId)).state; + expect(contender.stepResults.nodeId).not.toBe(nodeId); + if (path === 'pinned') expect(contender.completed).toBe(true); + else expect(contender.currentStep).toBe('node_provisioning'); + expect(await activeWorkspacesOn(nodeId)).toBe(0); + const owner = (await fireAlarm(ownerId)).state; + expect(owner.currentStep).toBe('workspace_dispatch'); + expect(owner.stepResults.nodeId).toBe(nodeId); + expect(await activeWorkspacesOn(nodeId)).toBe(1); + }); + + it.each(['normal', 'intent', 'released'] as const)( + 'falls back from a full provisioned node (resuming interrupted fallback: %s)', + async (resuming) => { + const nodeId = `node-full-owned-${resuming}`; + const taskId = `task-full-owned-${resuming}`; + const alternativeId = `node-idle-alternative-${resuming}`; + await seedProvisionedCx23(nodeId, taskId, { memoryPercent: 14 }); + await seedWorkspace(`ws-full-owned-sibling-${resuming}`, nodeId, USER_ID, { + projectId: PROJECT_ID, + status: 'running', + resolvedReservationJson: JSON.stringify({ ...SIBLING_RESERVATION, memoryMb: 2048 }), + }); + await startAtWorkspaceCreation(taskId, nodeId, DOCUMENTED_CAP_MEMORY_MB, { + priorRejections: DEFAULT_WORKSPACE_PLACEMENT_MAX_REJECTIONS - 1, + }); + if (resuming !== 'normal') { + await withPausedAlarms(taskId, async (instance) => { + const state = await instance.ctx.storage.get('state'); + if (!state) throw new Error('Missing state'); + state.rejectedAutoProvisionedNodeId = nodeId; + await instance.ctx.storage.put('state', state); + }); + } + if (resuming === 'released') { + await env.DATABASE.prepare('UPDATE nodes SET task_provisioned = 1 WHERE id = ?') + .bind(nodeId) + .run(); + await env.DATABASE.prepare('UPDATE tasks SET auto_provisioned_node_id = NULL WHERE id = ?') + .bind(taskId) + .run(); + } + await seedProvisionedCx23(alternativeId, `task-alternative-finished-${resuming}`, { + memoryPercent: 14, + }); + await env.DATABASE.prepare("UPDATE tasks SET status = 'failed' WHERE id = ?") + .bind(`task-alternative-finished-${resuming}`) + .run(); + let state: TaskRunnerState | undefined; + for (let i = 0; i < 40; i++) { + state = (await fireAlarm(taskId)).state; + if (state.completed || state.currentStep === 'workspace_dispatch') break; + } + expect(state?.completed).toBe(false); + expect(state?.currentStep).toBe('workspace_dispatch'); + expect(state?.stepResults.nodeId).toBe(alternativeId); + expect((await taskRow(taskId))?.status).toBe('delegated'); + expect(await activeWorkspacesOn(nodeId)).toBe(1); + expect(await warmSince(nodeId)).toBeNull(); + expect( + await env.DATABASE.prepare('SELECT status FROM nodes WHERE id = ?') + .bind(nodeId) + .first('status') + ).toBe('running'); + expect(await activeWorkspacesOn(alternativeId)).toBe(1); + const owner = await env.DATABASE.prepare( + 'SELECT auto_provisioned_node_id AS nodeId FROM tasks WHERE id = ?' + ) + .bind(taskId) + .first<{ nodeId: string | null }>(); + expect(owner?.nodeId).toBeNull(); + expect( + await env.DATABASE.prepare('SELECT task_provisioned FROM nodes WHERE id = ?') + .bind(nodeId) + .first('task_provisioned') + ).toBe(1); + } + ); + it('fails a specified node on its first refusal and leaves that node alone', async () => { const nodeId = 'node-specified-overrun'; const taskId = 'task-specified-overrun'; @@ -361,13 +496,124 @@ describe('a node provisioned for a task admits that task', () => { expect(await warmSince(nodeId)).toBeNull(); }); - it('still refuses measured use above the reserve, then fails fast after the cap and hands the node off', async () => { + it.each([1, 5])( + 'spends one real fallback then exhausts the replacement budget (%i)', + async (limit) => { + await setMaxRejections(limit); + const nodeId = `node-first-fallback-${limit}`; + const replacementId = `node-second-fallback-${limit}`; + const taskId = `task-real-fallback-budget-${limit}`; + await seedProvisionedCx23(nodeId, taskId, { memoryPercent: 60 }); + await startAtWorkspaceCreation(taskId, nodeId, DOCUMENTED_CAP_MEMORY_MB); + let state: TaskRunnerState | undefined; + for (let i = 0; i < 40; i++) { + state = (await fireAlarm(taskId)).state; + if (state.rejectedAutoProvisionedNodeId || state.completed) break; + } + expect(state?.completed).toBe(false); + expect(state?.rejectedAutoProvisionedNodeId).toBe(nodeId); + expect(state?.workspacePlacementRejections).toBe(0); + // Simulate the provider/readiness boundary for the normally admitted replacement; no + // paid provider is involved. Its measured pressure still cannot admit the owner. + await seedProvisionedCx23(replacementId, `finished-replacement-owner-${limit}`, { + memoryPercent: 60, + }); + await env.DATABASE.prepare("UPDATE tasks SET status = 'failed' WHERE id = ?") + .bind(`finished-replacement-owner-${limit}`) + .run(); + await env.DATABASE.prepare('UPDATE tasks SET auto_provisioned_node_id = ? WHERE id = ?') + .bind(replacementId, taskId) + .run(); + await withPausedAlarms(taskId, async (instance) => { + const persisted = (await instance.ctx.storage.get('state'))!; + expect(persisted.rejectedAutoProvisionedNodeId).toBe(nodeId); + persisted.stepResults.nodeId = replacementId; + persisted.stepResults.autoProvisioned = true; + persisted.currentStep = 'workspace_creation'; + await instance.ctx.storage.put('state', persisted); + }); + const result = await runToCompletion(taskId); + expect(result.state.completed).toBe(true); + expect(result.state.rejectedAutoProvisionedNodeId).toBe(nodeId); + expect(result.ran.filter((step) => step === 'workspace_creation')).toHaveLength(limit); + expect((await taskRow(taskId))?.errorMessage).toContain(`refused ${limit} times in a row`); + expect( + await env.DATABASE.prepare('SELECT COUNT(*) FROM nodes WHERE user_id = ?') + .bind(USER_ID) + .first('COUNT(*)') + ).toBe(2); + } + ); + + it.each([false, true])( + 'does not re-adopt a rejected node from a stale D1 pointer (rejected: %s)', + async (rejected) => { + const nodeId = `node-crash-readoption-${rejected}`; + const taskId = `task-crash-readoption-${rejected}`; + await seedProvisionedCx23(nodeId, taskId, { memoryPercent: 14 }); + await startAtWorkspaceCreation(taskId, nodeId, DOCUMENTED_CAP_MEMORY_MB); + await withPausedAlarms(taskId, async (instance) => { + const persisted = (await instance.ctx.storage.get('state'))!; + persisted.currentStep = 'node_provisioning'; + persisted.stepResults.nodeId = null; + persisted.stepResults.autoProvisioned = false; + if (rejected) persisted.rejectedAutoProvisionedNodeId = nodeId; + await instance.ctx.storage.put('state', persisted); + }); + const { state } = await fireAlarm(taskId); + if (rejected) { + expect(state.stepResults.nodeId).toBeNull(); + expect(state.completed).toBe(true); // No alternative or cloud credential in this fixture. + } else { + expect(state.stepResults.nodeId).toBe(nodeId); + expect(state.completed).toBe(false); + } + } + ); + + it('hands an empty rejected host to warm retention and keeps lifetime/cleanup provenance after replacement', async () => { + const nodeId = 'node-empty-rejected'; + const taskId = 'task-empty-rejected'; + await seedProvisionedCx23(nodeId, taskId, { memoryPercent: 60 }); + await startAtWorkspaceCreation(taskId, nodeId, DOCUMENTED_CAP_MEMORY_MB, { + priorRejections: DEFAULT_WORKSPACE_PLACEMENT_MAX_REJECTIONS - 1, + }); + const { state } = await fireAlarm(taskId); + expect(state.currentStep).toBe('node_selection'); + expect(state.rejectedAutoProvisionedNodeId).toBe(nodeId); + // Legacy unpooled fixture has no other teardown provenance: this requires retained history. + expect(await warmSince(nodeId)).toBeTruthy(); + await env.DATABASE.prepare( + "UPDATE nodes SET created_at = '2000-01-01T00:00:00.000Z' WHERE id = ?" + ) + .bind(nodeId) + .run(); + expect(await isNodePastLifetimeAdmissionCutoff(env.DATABASE, nodeId, 1000)).toBe(true); + await seedNode('node-replacement-provenance', USER_ID); + await env.DATABASE.prepare('UPDATE tasks SET auto_provisioned_node_id = ? WHERE id = ?') + .bind('node-replacement-provenance', taskId) + .run(); + expect(await isNodePastLifetimeAdmissionCutoff(env.DATABASE, nodeId, 1000)).toBe(true); + // Full migration chain: node deletion nulls history without deleting the task or resetting + // the DO's consumed fallback budget. + await env.DATABASE.prepare('DELETE FROM nodes WHERE id = ?').bind(nodeId).run(); + expect(await taskRow(taskId)).not.toBeNull(); + await withPausedAlarms(taskId, async (instance) => { + expect( + (await instance.ctx.storage.get('state'))?.rejectedAutoProvisionedNodeId + ).toBe(nodeId); + }); + }); + + it('bounds fallback by failing at the cap after a prior provisioned-node fallback', async () => { const nodeId = 'node-provisioned-overrun'; const taskId = 'task-provisioned-overrun'; // 60% = 2458 MB that no workspace observation explains (a leak or an orphaned container). // Declared accounting fits (1024 + 3072 = 4096); only the measured overrun refuses it. await seedProvisionedCx23(nodeId, taskId, { memoryPercent: 60 }); - await startAtWorkspaceCreation(taskId, nodeId, DOCUMENTED_CAP_MEMORY_MB); + await startAtWorkspaceCreation(taskId, nodeId, DOCUMENTED_CAP_MEMORY_MB, { + priorFallback: true, + }); const ran: string[] = []; let state: TaskRunnerState | null = null; @@ -528,7 +774,9 @@ describe('a node provisioned for a task admits that task', () => { const taskId = `task-provisioned-limit-${limit}`; await seedProvisionedCx23(nodeId, taskId, { memoryPercent: 60 }); await setMaxRejections(limit); - await startAtWorkspaceCreation(taskId, nodeId, DOCUMENTED_CAP_MEMORY_MB); + await startAtWorkspaceCreation(taskId, nodeId, DOCUMENTED_CAP_MEMORY_MB, { + priorFallback: true, + }); const { ran, state } = await runToCompletion(taskId); diff --git a/apps/api/tests/workers/task-runner-do.test.ts b/apps/api/tests/workers/task-runner-do.test.ts index 99260849b1..e59a6a0796 100644 --- a/apps/api/tests/workers/task-runner-do.test.ts +++ b/apps/api/tests/workers/task-runner-do.test.ts @@ -743,18 +743,26 @@ describe('stable TaskRunner reactivation', () => { const old = (await instance.ctx.storage.get('state'))!; old.completed = true; old.currentStep = 'running'; + old.rejectedAutoProvisionedNodeId = 'old-rejected-node'; + old.workspacePlacementRejections = 3; + old.startupBacklogConflicts = 3; await instance.ctx.storage.put('state', old); await instance.ctx.storage.deleteAlarm(); expect(await instance.ensureStarted('wake-1')).toBe(false); await instance.reactivate(input); expect(await instance.ensureStarted('wake-1')).toBe(true); const waking = (await instance.ctx.storage.get('state'))!; + expect(waking.rejectedAutoProvisionedNodeId).toBeUndefined(); + expect(waking.workspacePlacementRejections).toBe(0); + expect(waking.startupBacklogConflicts).toBe(0); waking.currentStep = 'workspace_creation'; waking.stepResults.nodeId = 'already-selected'; + waking.rejectedAutoProvisionedNodeId = 'this-attempt-rejected-node'; await instance.ctx.storage.put('state', waking); await instance.reactivate(input); expect(await instance.getStatus()).toMatchObject({ currentStep: 'workspace_creation', + rejectedAutoProvisionedNodeId: 'this-attempt-rejected-node', stepResults: { nodeId: 'already-selected' }, }); await instance.ctx.storage.deleteAlarm(); diff --git a/apps/www/src/content/docs/docs/architecture/durable-objects.md b/apps/www/src/content/docs/docs/architecture/durable-objects.md index 585bf1c7fa..2e3c295968 100644 --- a/apps/www/src/content/docs/docs/architecture/durable-objects.md +++ b/apps/www/src/content/docs/docs/architecture/durable-objects.md @@ -286,8 +286,9 @@ workspace lifecycle credit usage already represented in the host sample; unobser keeps its full reservation outstanding. The final atomic claim repeats both checks. When that claim refuses the node a task selected, the TaskRunner replans through node selection; after `operations.workspacePlacementMaxRejections` -consecutive refusals (3 by default) it fails the task with the refusal reasons and hands a node it -provisioned to the warm pool (`handleWorkspacePlacementRefused()` in +consecutive refusals (3 by default), an owned provisioned node gets one fallback to normal placement. +The rejected host retains cleanup/lifetime provenance; an empty host enters warm retention and an +occupied host stays active. Exhausting the refusal budget again fails the run with the refusal reasons (`handleWorkspacePlacementRefused()` in `durable-objects/task-runner/workspace-placement-rejection.ts`). Disk pressure remains a live overload veto. CPU saturation is one only for a node that already holds a workspace reservation: an empty node, warm ones included, is admitted on declared reservations alone, because bootstrap work can saturate a fresh host's CPU before any workspace exists. Exclusive requests require an empty node, and an active exclusive workspace prevents any additional placement. Legacy workspace-count and co-tenant settings remain compatible audit data but do not block placement. diff --git a/apps/www/src/content/docs/docs/guides/admin-settings.md b/apps/www/src/content/docs/docs/guides/admin-settings.md index c13e190d9a..7848393ba3 100644 --- a/apps/www/src/content/docs/docs/guides/admin-settings.md +++ b/apps/www/src/content/docs/docs/guides/admin-settings.md @@ -1080,7 +1080,7 @@ Nodes created before this change still boot from the flavor's local disk and kee | Setting | Default | Allowed range | Applies to | | ----------------------------------------------------- | ------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | `operations.provisioningAttemptsPerProviderTier` | 8 | 1–50 | Most offerings one task tries from one provider source under `fallback-chain` before moving to the pool's next-ranked provider | -| `operations.workspacePlacementMaxRejections` | 3 | 1–20 | Consecutive times the node a task selected may refuse its final workspace reservation before the task fails | +| `operations.workspacePlacementMaxRejections` | 3 | 1–20 | Consecutive times the node a task selected may refuse its final workspace reservation per episode; an owned provisioned node gets one fallback before final failure | | `operations.workspacePlacementBacklogConflictRetries` | 3 | 1–20 | Times a task may pick again because its chosen node gained a queued workspace setup before the reservation, counted until one succeeds | | `operations.workspaceBuildQueueTimeoutMinutes` | 60 | 5–1440 | Minutes a workspace may wait for its node's single build slot before it times out | @@ -1089,9 +1089,11 @@ to the provider, so this bounds the work one task does before it reaches the nex A refused workspace reservation sends the task back through node selection, about 6 seconds per cycle, so `operations.workspacePlacementMaxRejections` bounds a node that can never admit the -request to roughly 18 seconds at the default (about 2 minutes at the maximum). The failure names -the refusal reasons, which are also recorded in the task's placement diagnostics, and a node the -task provisioned goes to the warm pool. The count resets when a reservation succeeds. +request to roughly 18 seconds per episode at the default (about 2 minutes at the maximum). An +owned provisioned node gets one fallback to normal placement, for at most twice the configured +refusal budget, plus ordinary provisioning and queue time. Empty rejected nodes enter warm +retention; occupied nodes stay active. The final failure names the refusal reasons, also recorded +in placement diagnostics. Success or a genuinely new wake resets the episode. A node busy setting up another workspace does not refuse a reservation; the new workspace waits in that node's setup queue. When a task chose a node over another one with a longer queue and that diff --git a/apps/www/src/content/docs/docs/guides/compute-pools.md b/apps/www/src/content/docs/docs/guides/compute-pools.md index 5eba8691fa..b4d100a8c5 100644 --- a/apps/www/src/content/docs/docs/guides/compute-pools.md +++ b/apps/www/src/content/docs/docs/guides/compute-pools.md @@ -502,6 +502,18 @@ Cancelling queued work revokes its admission authority. A later free slot cannot task or provision a machine for it. If cancellation races a new allocation, SAM retires only that newly allocated empty machine, preserving occupied hosts and other placement claims. +A VM provisioned for an active task is held until that task places its workspace, fails, or is +cancelled. Other tasks skip it during selection, and atomic workspace admission also enforces +the hold, including direct workspace creation, attachment, and restart +(`services/provisioned-node-ownership.ts:buildProvisionedNodeHoldSqlPredicate`). + +If the owner's VM still cannot admit it after `operations.workspacePlacementMaxRejections`, +TaskRunner releases the claim once and returns to normal placement. It can reuse another VM, +provision within the existing limits, or wait under the pool's exhaustion policy. The rejected +VM retains its normal cleanup and lifetime guards; occupied VMs are preserved. A second +exhausted refusal budget fails the run instead of starting an endless replacement chain +(`task-runner/workspace-placement-fallback.ts:resumeWorkspacePlacementFallback`). + ## Exhaustion policy: what happens when nothing is available Providers run out of capacity, regions sell out, and accounts hit server limits. **Exhaustion diff --git a/packages/scheduler-core/src/provisioning-attempt-limits.ts b/packages/scheduler-core/src/provisioning-attempt-limits.ts index 60ae098c9e..97de5728cd 100644 --- a/packages/scheduler-core/src/provisioning-attempt-limits.ts +++ b/packages/scheduler-core/src/provisioning-attempt-limits.ts @@ -9,11 +9,13 @@ export const DEFAULT_PROVISIONING_ATTEMPTS_PER_PROVIDER_TIER = 8; /** * Default for `operations.workspacePlacementMaxRejections`: consecutive times a task's final - * workspace reservation may be refused by the node it selected before the task fails. A refusal + * workspace reservation may be refused in a placement episode. An unplaced provisioning owner + * gets one fallback to normal placement at the cap; another exhausted episode fails. A refusal * sends the task back through node selection, provisioning recovery and agent readiness, about * 6 s per cycle on staging, so 3 bounds a node that can never admit the request to about 18 s - * (the configurable maximum of 20 to about 2 minutes). Before the cap the loop ran until the - * 15-minute provisioning timeout. The count resets when a reservation succeeds. + * (the configurable maximum of 20 to about 2 minutes per episode). At most two episodes permit + * 2 × the configured cap in capacity refusals per execution, with ordinary queue/provisioning + * deadlines still enforced. The count resets on success or that single fallback. */ export const DEFAULT_WORKSPACE_PLACEMENT_MAX_REJECTIONS = 3; diff --git a/packages/worker-core/src/schema.ts b/packages/worker-core/src/schema.ts index c0b9a0fbdb..1c3bebf4cf 100644 --- a/packages/worker-core/src/schema.ts +++ b/packages/worker-core/src/schema.ts @@ -2064,6 +2064,8 @@ export const nodes = sqliteTable( * enrolled machine). Drives lifecycle guards, billing, quota, and UI. Orthogonal to `runtime`. */ nodeClass: text('node_class').notNull().default('managed'), + /** Server-written task provisioning provenance retained after a placement fallback releases ownership. */ + taskProvisioned: integer('task_provisioned', { mode: 'boolean' }).notNull().default(false), /** Reachability transport: 'vm-public-dns' | 'cloudflare-tunnel'. Null for implicit transport. */ transport: text('transport'), /** Cloudflare Tunnel UUID for tunnel-transport nodes (user-owned or managed). Null otherwise. */ diff --git a/scripts/quality/check-migration-ordering.ts b/scripts/quality/check-migration-ordering.ts index e57f18ebe2..13cab83e17 100644 --- a/scripts/quality/check-migration-ordering.ts +++ b/scripts/quality/check-migration-ordering.ts @@ -141,6 +141,14 @@ const LEGACY_ALLOWED_DUPLICATE_FILES = new Map>> '0231', new Set(['0231_node_tunnel_pending_creates.sql', '0231_publish_job_context_shadow.sql']), ], + // PR #2855's provisioned-node ownership column was applied to staging2 on + // 2026-11-17 as d1_migrations id 276, after main's 0257 recovery-scan index + // (id 275) had claimed the prefix. Renumbering would replay ALTER TABLE nodes + // ADD COLUMN task_provisioned against staging2 and abort its migration run. + [ + '0257', + new Set(['0257_node_task_provisioned.sql', '0257_provider_limit_recovery_scan_index.sql']), + ], ]), ], ]); diff --git a/tasks/archive/2026-11-17-provisioned-node-ownership.md b/tasks/archive/2026-11-17-provisioned-node-ownership.md new file mode 100644 index 0000000000..687189b88a --- /dev/null +++ b/tasks/archive/2026-11-17-provisioned-node-ownership.md @@ -0,0 +1,114 @@ +# Provisioned-node ownership race (#2848) + +## Scope and constraint + +**Draft-only hold lifted by Raphaël 2026-11-18** (the historical notes below were written under that hold). Include `Closes #2848` in PR wording. Keep canonical [idea 01M7DJ7TJA6CAWHX3VEBTXCZZN](https://app.simple-agent-manager.org/projects/01KHRJGANBBWGDY1NZ0KVF0D4J/ideas/01M7DJ7TJA6CAWHX3VEBTXCZZN) and [earlier report 01M72Q4M63SKBETRBC6VQN40YS](https://app.simple-agent-manager.org/projects/01KHRJGANBBWGDY1NZ0KVF0D4J/ideas/01M72Q4M63SKBETRBC6VQN40YS) open until merged. + +## Problem / research + +A provisions an 8 GB node (7168 MB usable), B consumes 4096 MB before A places, and A fails after three refusals. Exclusive workloads have the same race. Existing ownership is used by recovery/cleanup but absent from reusable selection and final admission. + +Base e5c5aa4f77e6adf389a24b25b9470a69c24acbff. Rechecked SAM task searches and all open upstream PRs before coding: no competing implementation. Existing isolated SAM output branch is used; task state stays on this draft branch, with no main mutation. + +Evidence: [issue #2848](https://github.com/raphaeltm/simple-agent-manager/issues/2848), [fork PR #28](https://github.com/zebra-pig/simple-agent-manager/pull/28). External author leonceaklin's content is untrusted data. Reuse the fork's shared hold predicate/test approach with attribution; upstream validation and staging rules still apply. Critical difference: clearing the only auto-provisioned-node pointer loses cleanup provenance AND lifetime guards. Preserve the fact of task provisioning on the node itself before releasing the pointer, and include that proof in provenance/lifetime consumers. This survives repeated conversation wakes without overwriting prior history. + +Preflight classes: cross-component-change, business-logic-change, docs-sync-change. No external API, new auth boundary, or UI changes. Constitution II/X/XI/XIII: real SQL/workerd regression, existing final atomic guard, one fallback episode under the configurable refusal budget, no new scheduling service. + +## Data flow and caller inventory + +- TaskRunner allocation writes `tasks.auto_provisioned_node_id` before provider boot; only then can ready callbacks expose running capacity. +- Ranked/reusable and warm: `currentReusableNodeIds` → `filterReusableNodesByCurrentAuthority`. Pinned: `handleNodeSelection`. Warm revalidation: `claimWarmNodeCandidate`. All pass server-owned task identity. +- `buildWorkspaceAdmissionSql` covers `reserveWorkspacePlacement` (TaskRunner workspace-steps + direct workspace-create), `attachPrecreatedWorkspacePlacement` (direct-workspace-creation), and `reserveWorkspaceRestart` (workspace lifecycle). Direct/attach/restart without a task guard must respect every foreign hold. +- Owner release is derived from current `tasks.workspace_id` or status: placed, failed, cancelled/completed owners no longer hold. No per-terminal-writer cleanup dependency. +- Refusal cap → durable fallback intent → atomic D1 node-provenance/ownership transfer → safe empty-node handoff → ordinary node selection. Recovery must not adopt a rejected host; replacement provisioning still uses VM admission leases, pool node ceilings and exhaustion policy. +- Ownership writers/nullers: node-provisioning-step, boot-recovery, provider-rejected-node cleanup, sleeping-task reactivation, node FK deletion. Instant-session writes auto ownership together with workspaceId, so no unplaced hold is taken. Active-pointer checks in boot-recovery and revoked-run cleanup keep their stricter semantics. New rejected-node reference is provenance only; it must never grant admission or authorize destructive cleanup without existing guards. + +## Checklist / acceptance + +- [x] Read and link existing ideas, recheck active work/upstream PRs, review fork critically. +- [x] Reproduce A/B boot interleaving pre-fix using SQL and workerd. +- [x] Shared whole-node hold at ranked/reusable/pinned/warm selection and atomic INSERT/ATTACH/restart; owner still admissible subject to all safety guards. +- [x] Release on placement/failure/cancellation and stale selection refusal; exclusive/nonexclusive controls. +- [x] One crash-safe fallback episode with no rejected-host re-adoption, normal queue/pool limits, bounded exhaustion, and no occupied-node teardown. +- [x] Preserve teardown provenance/lifetime guards for abandoned provisioned nodes. +- [x] Full relevant validation, local specialist reviews and task-completion validation. +- [x] Verify corrected-account A/B placement, actual replies, rendered chats and guard-preserving cleanup (latest evidence below). +- [x] Clear installation-wide browser/noise release gates: the 503s are `AUTH_UNAVAILABLE` from shared auth middleware and pre-date this PR (staging2 first 2026-11-16 20:36 UTC, before this PR's first staging2 deploy; primary staging, which never ran it, had 109 since 2026-10-30). Pre-existing noise waived per Raphaël 2026-11-18. +- [x] Draft PR with attribution, `Closes #2848`, CI/evidence and preserved constraint; ideas stay open. + +## Validation / post-mortem + +Draft [PR #2855](https://github.com/raphaeltm/simple-agent-manager/pull/2855) opened at cc7fb3fb9 with attribution. Both ideas linked to it and remain open. SAM associate_pull_request timed out after 300s; PR exists and is draft. + +- Final controlled harness against upstream base e5c5aa4f: SQL **7 failed /98 passed /105 total** (active owner selection, warm discovery-to-claim race, stale INSERT/ATTACH/restart); workerd **9 failed /16 skipped /25 total** (ranked/pinned/warm × exclusive/nonexclusive boot interleaving plus normal/intent/released fallback). Only final tests and additive test schema column copied into detached base worktree; base runtime unchanged. +- Fixed SQL **108 passed** across 3 files including a 100k-task indexed query plan, 125-host bind chunking and post-fallback real pool trigger. Fixed workerd **89 passed** across 4 files including real TaskRunner lifecycle, new-wake reset, VM admission and capacity races. Recovery-retry **36 passed** after the NULL fixture compatibility correction. +- Final lint (22 tasks), typecheck (36 tasks) and build (18 tasks) passed. Full local API: **16,600 passed / 4 skipped / 0 failed** across 1,090 files; other 20 packages: **10,030 passed**. Combined: **26,630 passed / 4 skipped**. Migration safety (247 FKs, zero violations), migration ordering and diff checks passed. +- Cloudflare final runtime review PASS: exact-owner atomic release/proof, guarded replay, per-attempt budget reset and occupied-host safety. Test-engineer, task-completion-validator, constitution-validator and doc-sync-validator final reviews also PASS; no remaining implementation findings. New fallback-admission 3/3 tests retain original pool/user queue deadlines and serialize two fallback owners through one provider request; isolated guard removals failed exactly the queue/deadline assertions. +- [Staging2 deployment 44087824862](https://github.com/raphaeltm/simple-agent-manager/actions/runs/44087824862) passed, including smoke tests, at source `3bd7ca45070d59b15591c5e6b6a0212d027d0894`. Both installation queues were coordinated; the primary reservation was released before the secondary turn. D1 confirms `0257_node_task_provisioned.sql` and `nodes.task_provisioned INTEGER NOT NULL DEFAULT 0`. No new Durable Object migration tag. +- Real A/B boot observation: A `01M7MVAB1429A1B6QM62XHJXEG` owned allocated 8 GB node `01M7MVBSDXTDNW0V5YGH6BN4JF` while unplaced; B `01M7MVC3XPQ4XCFF7QMVZ9JEYG` queued instead of taking it. A subsequently placed workspace `01M7MVHRDSEABRA3YB111WF8C2` on its owned node. B allocated a separate 8 GB host after normal provider-capacity retries but did not finish readiness within the bounded window. This is partial evidence, not a full live pass. +- Full agent/chat verification is blocked: A's actual assistant reply was `API Error: 402 AI inference failed (402). Please try again.` The existing Anthropic proxy passes through the AI Gateway's upstream status. Platform cloud and agent credentials were enabled; this is not a missing-personal-cloud-credential diagnosis. No account funding, credential replacement or guard bypass was attempted. +- Browser baseline initially passed dashboard/project/settings/health with zero console/page errors. Later runs saw `AUTH_UNAVAILABLE` 503 responses and a settings-load timeout; cause unresolved. The unchanged 24-hour noise gate exited 1 both before and after: baseline Operations 240 / Hetzner 32; after Operations 225 / Hetzner 34 / auth unavailable 13. Telemetry subcheck unavailable (403). Historical and new errors are distinguished, with evidence appended to existing [noise idea 01M7KE1VAKJTKGV21CAAK6MQMG](https://app.simple-agent-manager.org/projects/01KHRJGANBBWGDY1NZ0KVF0D4J/ideas/01M7KE1VAKJTKGV21CAAK6MQMG). +- Cleanup: all four test tasks cancelled; temporary profile removed; the only created workspace and both allocated VM node rows removed after strict DELETE returned 200. Final D1 proof at 13:45 UTC confirms those resources absent. Two actual 8 GB VMs were used, within the bounded cost estimate; no further paid retries. +- One pre-create, providerless node `01M7MTMV89F5ZV23VSF0ZVPJPS` remains quarantined in `destroying`, with no provider ID, IP, workspace or termination proof. Normal DELETE refuses 409. The existing [providerless cleanup idea 01M7GVRC956Q8JMGCRP1PQ4R5B](https://app.simple-agent-manager.org/projects/01KHRJGANBBWGDY1NZ0KVF0D4J/ideas/01M7GVRC956Q8JMGCRP1PQ4R5B) was read and updated; no duplicate idea/issue or manual D1 cleanup. Preserve this guard until an operator-supported fix establishes allocation finality. +- Lease release [run 44096040800](https://github.com/raphaeltm/simple-agent-manager/actions/runs/44096040800) passed. Fresh staging2 status at 13:56:14 UTC confirms holder=null and the next queued task has its protected turn; early handoff notification queued under the /do staging workflow (acceptance does not prove it was read). Live staging remains blocked and is not waived. This task and both ownership ideas remain open; PR remains **DRAFT ONLY**. +- CodeRabbit requested once via trusted main workflow [run44059649679](https://github.com/raphaeltm/simple-agent-manager/actions/runs/44059649679), retaining draft status. CodeRabbit returned review rate limited; no review arrived and no retrigger is planned. Full manual [CI run 44060519223](https://github.com/raphaeltm/simple-agent-manager/actions/runs/44060519223) passed at source head `3bd7ca45070d59b15591c5e6b6a0212d027d0894`, including all three API and seven workerd shards. Draft status remains set. + +No live reproduction on the external installation. The corrected-account result and remaining broader staging gates are recorded in the latest section below. Draft status, no merge and no production deployment remain explicit constraints. + +Class: state-interaction race; advisory and atomic admission omitted durable provisioning ownership. Existing tests covered workspace reservations without a second TaskRunner selecting during the boot window. Process fix is discriminating SQL/workerd tests through production selection/admission, plus crash-boundary controls; existing rules 44/62/69 already require this coverage. + +## Corrected-account follow-up (15:55 UTC; live rerun pending) + +Raphaël clarified that verification must sign in as `test-user@simple-agent-manager.org` (`staging2-test-user`) and use that user's attached Anthropic account. Metadata confirms its active Claude Code OAuth credential and user attachment, GCP credential, and Artifacts `test-project` (`01M7M62YQ2XRZ6HYT1VYJ3WDS2`). The prepared harness explicitly selects OAuth configuration `cc-cfg-01M7M62R81N29Q65EC6PMFF4K8`. The previous bootstrap-user/API-key 402 does not establish a failure of this account. + +Exact-user workload login, session verification, project read and sign-out passed at 14:55 after the installation-specific trust was applied by PR #2841's staging deployment. No further human configuration was needed for the earlier target-allowlist 403. No new VM has been created for the corrected-account rerun. + +Our branch's old staging workflow still contains the credential-copy path prohibited by project policy 795e72a6. Wait for upstream [PR #2841](https://github.com/raphaeltm/simple-agent-manager/pull/2841) to merge, update this branch from main, review the merge and run appropriate checks before redeploying. At 15:52 it remains open, with no failures and its final CI run 44114588924 progressing. This task does not authorize merging that other PR. + +Staging2 reservation 44104898905 succeeded. The preceding branch released early; authoritative 15:51:54 status shows our protected turn through 16:23:58 UTC, holder=null. The handoff event was read and acknowledged. Do not deploy an unsafe workflow or bypass another branch's lease if the queue changes. + +A nonsecret, ephemeral verification harness and checkpoint are saved in the Project Library at `/engineering/issue-2848/handoff-2848.tgz`, file ID `01M7N3G4ZEV5FT93QAWF3RHG3E` (download with `download_library_file`). Local ignored files were omitted when SAM replaced the workspace, so this artifact prevents repeated reconstruction. It contains no cookie or credential values. The harness requires our exact candidate lease, uses at most two allocated 8 GB GCP VMs for a 12-minute overall trial, verifies B was accepted while A remained unplaced, checks actual assistant replies and chat DOM, and preserves strict ownership/occupancy cleanup guards. Syntax and browser tooling checks passed; the paid `race` mode remains **UNRUN**. Conservative incremental allowance: USD 1, with regional/disk/IP margin; [published Compute Engine pricing](https://cloud.google.com/products/compute/pricing/general-purpose). + +PR #2855 stays **DRAFT ONLY**. Full runtime CI passed at `3bd7ca450`; later evidence-only checks pass except PR Evidence, which fails because the explicit `needs-human-review` label is retained while live verification is incomplete. Do not describe that label gate as green or remove it to bypass review. + +## Safe upstream update and renewed queue wait (16:28 UTC) + +PR #2841 merged at 16:18:26 UTC (`0c672ddbf698cd59cc4e5f6b4894cf9a4ea8d67f`). Merged main into this branch as `4280e504a8dc08ec67ce99236e0f5895d83e1d94`; the only conflict was the TaskRunner documentation moved upstream from overview.md to durable-objects.md. Kept upstream's move and applied the fallback paragraph on the new page. No Wrangler or Durable Object migration-tag difference remains against main. The secret-readback check passes (zero findings, one tracked masked legacy read), API dependency build and typecheck pass, focused SQL/history/fallback tests pass 109/109, ownership/TaskRunner workerd tests pass 46/46, and the docs build passes (297 pages). The first focused run in the fresh workspace could not resolve unbuilt package exports; rebuilding dependencies fixed it. Two incorrectly named follow-up filters found no tests; they are excluded from all pass counts. + +Full manual CI [44125052305](https://github.com/raphaeltm/simple-agent-manager/actions/runs/44125052305) is queued for the merged candidate. GitHub runners never started acquire [44124844403](https://github.com/raphaeltm/simple-agent-manager/actions/runs/44124844403) or safe deploy [44125035061](https://github.com/raphaeltm/simple-agent-manager/actions/runs/44125035061) before our protected turn ended at 16:23:58. Both were cancelled before any job ran; no lease or deployment occurred. New reserve-only [44125513591](https://github.com/raphaeltm/simple-agent-manager/actions/runs/44125513591) is queued normally. At 16:24 the next task had its protected turn; a coordination message was accepted on the shared agent channel (not proof of receipt). No queue bypass, no corrected-account VM allocations. + +The unchanged 24-hour observability baseline at 16:26 still exits 1: Operations project configuration 192 occurrences, guarded stale handoff cleanup 16, session verification unavailable 13; telemetry unavailable (403). Preserve those known failures and the existing noise idea; no threshold changes or waiver. The corrected-user paid trial is still **UNRUN** and staging is not waived. Same-chat completion subscription `9040bb75-9a21-4057-bba9-894584820e14` covers the merged head; immediate replay was empty. Independent fallback schedule `524181ba-32a5-492b-a334-4d1470fe9a71` is accepted for 17:00 UTC. PR #2855 stays **DRAFT ONLY**; do not mark ready, merge or deploy to production. Both ownership ideas remain open. + +## Merged-runtime full CI success (18:08 UTC; draft-only staging wait) + +[Full manual CI 44125052305](https://github.com/raphaeltm/simple-agent-manager/actions/runs/44125052305) is **SUCCESS** for merged runtime `4280e504a8dc08ec67ce99236e0f5895d83e1d94`: all three API shards, all seven workerd shards, other packages, CLI, quality surfaces, lint, code quality, secret scan, build/typecheck and the full-suite aggregate gate passed. This supersedes the earlier pending-CI status. The current task-report-only head has identical runtime. The 219 focused post-merge checks also passed. No repeated full suite is required for this report-only update. + +[Quick draft CI 44126512475](https://github.com/raphaeltm/simple-agent-manager/actions/runs/44126512475) completed with all executed quality/build checks passing; its sole failure is PR Evidence because `needs-human-review` remains while live verification is incomplete. Its failed-job log explicitly requires a human to remove that label before any future merge. Keep the gate intact. This task authorizes neither readiness nor merge. + +Fresh staging2 status at 18:06:51 shows task `01M7MZBZGD2KWWFWJVZ03FP6EQ` holding the installation until 18:42:46.721. Our reservation 44125513591 is now fifth, with estimated turn **19:22:46.721–19:32:46.721 UTC**, expiring 00:30:59.118 the next day. Rescheduled existing turn wake `fa18ea6f-42ef-4614-ae14-1c4bf6d2e33e` to 19:22:46.721 (version 2); this follows a changed authoritative queue deadline. CI event batch `4163b1b2-7743-4344-8b3e-32a429508225` was read, verified and acknowledged; the completed-CI subscription was cancelled. No corrected-account VM has been created; paid trial remains **UNRUN**. Use `test-user@simple-agent-manager.org` and its attached Anthropic OAuth configuration on the actual leased candidate. Both ownership ideas remain open and the task stays active. **DRAFT PR ONLY — never mark ready, merge or deploy to production.** + +## Corrected-account final validation (22:05 UTC) + +**The draft fix is functionally verified. Broader staging is not clean: retain `needs-human-review`, keep this PR draft, and do not mark ready, merge or deploy to production.** Both ownership ideas remain open and this task file stays active while the PR is unmerged. + +- [Staging2 deployment 44178337481](https://github.com/raphaeltm/simple-agent-manager/actions/runs/44178337481) **SUCCESS** at `7092a9b793b5ab2907caec3ff9ff83a8126bfdd1`, including completed container rollout and smoke tests. This head differs from fully tested runtime `4280e504a8dc08ec67ce99236e0f5895d83e1d94` only in task-report notes. Migration `0257_node_task_provisioned.sql` is present. The exact candidate lease was acquired 21:19:36.552, expiring 22:19:36.552. The 21:40 fallback actually resumed this chat; later completion events were read, independently verified and acknowledged; the completed subscription was cancelled. +- Signed in as the requested `test-user@simple-agent-manager.org` (`staging2-test-user`) and explicitly selected attached Anthropic OAuth configuration `cc-cfg-01M7M62R81N29Q65EC6PMFF4K8`. Initial VM count was zero. One bounded trial used two allocated 8 GB GCP VMs, without pool/queue changes or another paid rerun. +- A `01M7NQS8W4TQ5TPWHAWKDPE4J0` owned 8 GB node `01M7NQSJMD667K4MEQ9RGAJ66G` while unplaced. B `01M7NQTDTDX9CDY5TP02Z62QK7` was accepted during that window and queued for capacity. A then placed workspace `01M7NR01HJ21JCD0SPTWFFAA9S` on its original host. B allocated a separate 8 GB node `01M7NR06BNE26Q2W9DYNNDBFE1`, then placed workspace `01M7NR7N0PEWXNRACYW0WR7M6P`. Both workspaces ran. +- Both actual assistant replies exactly matched their unique `PONG-2848-...-A/B` prompts, and both exact replies rendered in Playwright. I reviewed both screenshots. The first verifier incorrectly required a full reply in one message row; each reply was streamed in two rows. Its bounded wait therefore timed out. Supplemental checks concatenated the assistant chunks and verified the **same sessions** and chat DOM; no new VM or inference run was started. The original harness is not reported as passing. +- Projects, project overview and Settings loaded, but the supplemental browser's clean-error gate **FAILED**: **15 HTTP 503 responses, 15 console errors, zero page errors**. Affected metadata/session/inbox endpoints repeat the earlier authentication-read-deadline symptom. B's sidebar showed no chats while its actual reply was visible. Root cause is not established here. This is not a clean existing-workflow pass. +- Unchanged 24-hour / 10-occurrence noise gate remains **exit 1**. Before: Operations configuration 133, guarded stale cleanup 54, telemetry unavailable 403. After: Operations 125, guarded cleanup 60, session verification unavailable 24, telemetry 403. Evidence appended to [existing staging2 noise idea](https://app.simple-agent-manager.org/projects/01KHRJGANBBWGDY1NZ0KVF0D4J/ideas/01M7KE1VAKJTKGV21CAAK6MQMG). No threshold changes or waiver. +- Cleanup completed at **22:05:07 UTC**: both tasks cancelled (200), both workspaces deleted (200), and both allocated VMs deleted through normal guarded APIs (200). Initial 30-second client delete timeouts left `destroying` rows; normal retries with a longer client timeout completed. Final D1 queries returned **zero test nodes and zero test workspaces**; sign-out passed. The older bootstrap-user providerless quarantine remains untouched. +- A timeout's local error detail included an already-signed-out session cookie. It was scrubbed immediately; no raw report was uploaded, and scratch error capture now omits request-header call logs. The original execution-status tool returned `-32603` after completion; local terminal evidence and a separate successful strict-cleanup job establish the outcomes. No secret values are in committed or uploaded evidence. +- Reviewed screenshots and sanitized evidence are in Project Library `/engineering/issue-2848/`: A image `01M7NRVHY3Y9VN5MSY0RCWPVGF`, B image `01M7NRVKNN66T027MENR79X4Q6`, JSON `01M7NRVNGBSXKQG4M7X6SMQF3S`. The source/recovery archive remains `01M7N3G4ZEV5FT93QAWF3RHG3E`. +- [Lease release 44186778769](https://github.com/raphaeltm/simple-agent-manager/actions/runs/44186778769) **SUCCESS**. Fresh 22:13:54 UTC status confirms holder=null and next task `01M7MPMNXSC5RBS7JNA8V6A11G` has its protected turn through 22:29:36.552. A durable early handoff was sent under `/do`; acceptance does not prove it was read. No further live staging mutations are planned. + +### Final task-completion validation + +Verdict **WARN** for handoff: A (research/checklist), B (checklist/diff), E (owner/competitor discrimination) and F (vertical slice) pass; D is N/A (no UI input changes). C covers every scoped fix criterion through SQL/workerd and the corrected-account live trial, but the broader browser/noise release gate remains red and explicitly tracked. No unexplained implementation omissions or new critical/high findings were identified. Runtime is unchanged since the fully tested merged candidate; the final change only records evidence. Keep `needs-human-review`, this active task file, both open ideas and draft-only hold. + +## Resume and release (2026-11-19, task 01M7RN3SX99N1J3PBP8H2NBDXN) + +- [x] Merged current `origin/main`. Main owns prefix 0257 too; staging2 applied `0257_node_task_provisioned.sql` (d1_migrations id 276, read back 2026-11-19), so the file keeps its name and `scripts/quality/check-migration-ordering.ts` allowlists the duplicate prefix. Production applies it as a pending migration. +- [x] Security-auditor (PASS, no CRITICAL/HIGH): added four real-SQL attack cases in `apps/api/tests/integration/provisioned-node-fallback-admission.test.ts` (foreign node, foreign task owner, both foreign to the runner, foreign project) beside the owner control; each guard in `resumeWorkspacePlacementFallback` was neutralized once and exactly its case went red. +- [x] 503 provenance established (above); `needs-human-review` removed with Raphaël's authorization. +- [x] task-completion-validator re-run: PASS.