Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions apps/api/src/db/migrations/0257_node_task_provisioned.sql
Original file line number Diff line number Diff line change
@@ -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));
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions apps/api/src/durable-objects/task-runner/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,10 @@ export class TaskRunner extends DurableObject<Env> {
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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
} from '../../services/capacity-pools';
import type { TaskRunnerContext, TaskRunnerState } from './types';

export async function adoptProvisionedNodeAfterCrash(

Check failure on line 16 in apps/api/src/durable-objects/task-runner/node-provisioning-recovery.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 16 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=raphaeltm_simple-agent-manager&issues=AaHo6WET_GfhQBClBsgL&open=AaHo6WET_GfhQBClBsgL&pullRequest=2855
state: TaskRunnerState,
rc: TaskRunnerContext
): Promise<void> {
Expand All @@ -31,7 +31,7 @@
.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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand All @@ -110,6 +107,7 @@ export async function currentReusableNodeIds(
nodes: readonly NodePlacementFields[]
): Promise<Set<string>> {
return filterReusableNodesByCurrentAuthority(rc.env.DATABASE, {
requestingTaskId: state.taskId,
userId: state.userId,
projectId: state.projectId,
selections: nodes.flatMap((node) => {
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/durable-objects/task-runner/node-steps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }],
Expand Down
5 changes: 4 additions & 1 deletion apps/api/src/durable-objects/task-runner/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 4 additions & 9 deletions apps/api/src/durable-objects/task-runner/warm-node-claim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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,
Expand Down Expand Up @@ -105,6 +99,7 @@ async function claimWarmNodeCandidate(
): Promise<boolean> {
const nodeId = selection.nodeId;
const eligible = await filterReusableNodesByCurrentAuthority(rc.env.DATABASE, {
requestingTaskId: state.taskId,
userId: state.userId,
projectId: state.projectId,
selections: [selection],
Expand Down
Original file line number Diff line number Diff line change
@@ -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<boolean> {
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;
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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';
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions apps/api/src/durable-objects/task-runner/workspace-steps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -44,6 +45,7 @@ export async function handleWorkspaceCreation(
state: TaskRunnerState,
rc: TaskRunnerContext
): Promise<void> {
if (await resumeWorkspacePlacementFallback(state, rc)) return;
await rc.updateD1ExecutionStep(state.taskId, 'workspace_creation');

if (!state.stepResults.nodeId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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')}
Expand Down
16 changes: 4 additions & 12 deletions apps/api/src/scheduled/node-cleanup/node-phases.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion apps/api/src/services/admin-settings-core-definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
9 changes: 4 additions & 5 deletions apps/api/src/services/node-lifetime-admission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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).
Expand Down Expand Up @@ -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 < ?
)`;
}
Expand Down
Loading
Loading