diff --git a/.github/workflows/deploy-reusable.yml b/.github/workflows/deploy-reusable.yml index 4b0c699ce5..45719423d9 100644 --- a/.github/workflows/deploy-reusable.yml +++ b/.github/workflows/deploy-reusable.yml @@ -1068,6 +1068,8 @@ jobs: VM_AGENT_TUNNEL_RESTART_SECONDS: ${{ vars.VM_AGENT_TUNNEL_RESTART_SECONDS }} SANDBOX_CONTAINER_MAX_INSTANCES: ${{ vars.SANDBOX_CONTAINER_MAX_INSTANCES }} VM_AGENT_CONTAINER_MAX_INSTANCES: ${{ vars.VM_AGENT_CONTAINER_MAX_INSTANCES }} + DEPLOY_BUILDER_MAX_INSTANCES: ${{ vars.DEPLOY_BUILDER_MAX_INSTANCES }} + DEPLOY_BUILDER_INSTANCE_TYPE: ${{ vars.DEPLOY_BUILDER_INSTANCE_TYPE }} SANDBOX_ENABLED: ${{ vars.SANDBOX_ENABLED }} MAX_CONCURRENT_SETUP_SESSIONS: ${{ vars.MAX_CONCURRENT_SETUP_SESSIONS }} SETUP_SESSION_TTL_MS: ${{ vars.SETUP_SESSION_TTL_MS }} @@ -1937,6 +1939,8 @@ jobs: VM_AGENT_TUNNEL_RESTART_SECONDS: ${{ vars.VM_AGENT_TUNNEL_RESTART_SECONDS }} SANDBOX_CONTAINER_MAX_INSTANCES: ${{ vars.SANDBOX_CONTAINER_MAX_INSTANCES }} VM_AGENT_CONTAINER_MAX_INSTANCES: ${{ vars.VM_AGENT_CONTAINER_MAX_INSTANCES }} + DEPLOY_BUILDER_MAX_INSTANCES: ${{ vars.DEPLOY_BUILDER_MAX_INSTANCES }} + DEPLOY_BUILDER_INSTANCE_TYPE: ${{ vars.DEPLOY_BUILDER_INSTANCE_TYPE }} SANDBOX_ENABLED: ${{ vars.SANDBOX_ENABLED }} MAX_CONCURRENT_SETUP_SESSIONS: ${{ vars.MAX_CONCURRENT_SETUP_SESSIONS }} SETUP_SESSION_TTL_MS: ${{ vars.SETUP_SESSION_TTL_MS }} diff --git a/apps/api/Dockerfile.compose-builder b/apps/api/Dockerfile.compose-builder new file mode 100644 index 0000000000..5cd6bc3276 --- /dev/null +++ b/apps/api/Dockerfile.compose-builder @@ -0,0 +1,11 @@ +# Phase-0 measured Docker29.9.3 / Compose5.7.0 / Buildx0.38.2. +# Keep the reviewed digest: root DinD with overlayfs, not rootless or vfs. +# Rootful DinD is required by the measured recipe. The isolated, one-job +# Cloudflare microVM is the trust boundary; no broad credential is delivered. +FROM docker.io/library/docker@sha256:08a98015fce594af7c382883bea080ea206de74402a95da9dc52b6428c8cd121 +COPY container-artifacts/sam-builder-linux-amd64 /usr/local/bin/sam-builder +COPY container-entrypoints/compose-builder.sh /usr/local/bin/compose-builder +RUN chmod 0755 /usr/local/bin/sam-builder /usr/local/bin/compose-builder +EXPOSE 8080 +# docker-init reaps orphaned children and forwards termination to the Go supervisor. +ENTRYPOINT ["docker-init", "--", "/usr/local/bin/compose-builder"] diff --git a/apps/api/container-entrypoints/compose-builder.sh b/apps/api/container-entrypoints/compose-builder.sh new file mode 100644 index 0000000000..4eeff2c46c --- /dev/null +++ b/apps/api/container-entrypoints/compose-builder.sh @@ -0,0 +1,7 @@ +#!/bin/sh +set -eu +# Required by the measured Cloudflare DinD startup recipe. +mountpoint -q /tmp || mount -t tmpfs none /tmp +# Never copy a token, Worker secret or launch payload into the guest environment +# or filesystem. Direct Internet access uses the image's normal trust store. +exec /usr/local/bin/sam-builder diff --git a/apps/api/src/app-deployment-ports/cloudflare-builder.ts b/apps/api/src/app-deployment-ports/cloudflare-builder.ts new file mode 100644 index 0000000000..3fb2449cfd --- /dev/null +++ b/apps/api/src/app-deployment-ports/cloudflare-builder.ts @@ -0,0 +1,41 @@ +import { + type CloudflareBuildPorts, + DEFAULT_DEPLOY_BUILDER_MAX_CONCURRENT, + isCloudflareBuildCapacityError, +} from '@simple-agent-manager/app-deployment'; + +import type { Env } from '../env'; +import { parsePositiveInt } from '../lib/route-helpers'; +import { resolveAdminSetting } from '../services/admin-settings'; +import { recordDeploymentPublishJobLifecycleEventBestEffort } from '../services/project-lifecycle-events'; + +export function createCloudflareBuildPorts(env: Env): CloudflareBuildPorts { + const stub = (jobId: string) => env.COMPOSE_BUILDER.get(env.COMPOSE_BUILDER.idFromName(jobId)); + return { + classMax: parsePositiveInt( + env.DEPLOY_BUILDER_CLASS_MAX_INSTANCES, + DEFAULT_DEPLOY_BUILDER_MAX_CONCURRENT + ), + settings: { resolveSetting: (name) => resolveAdminSetting(env, name) }, + lifecycle: { + recordPublishJobLifecycleEventBestEffort: (event) => + recordDeploymentPublishJobLifecycleEventBestEffort(env, event), + }, + builder: { + start: async (job) => { + try { + await stub(job.id).startJob(job.id, job.attempt, job.executorNotBefore); + return 'started'; + } catch (error) { + // Only platform capacity is retryable queue pressure. Never interpret + // authentication, image/startup errors or a lost RPC as capacity. + if (isCloudflareBuildCapacityError(error)) return 'capacity'; + throw error; + } + }, + stop: async (job, capacity) => { + await stub(job.id).stopJob(capacity); + }, + }, + }; +} diff --git a/apps/api/src/app-deployment-ports/publish-jobs.ts b/apps/api/src/app-deployment-ports/publish-jobs.ts index fc1d9b083a..e5b5a1085b 100644 --- a/apps/api/src/app-deployment-ports/publish-jobs.ts +++ b/apps/api/src/app-deployment-ports/publish-jobs.ts @@ -5,6 +5,7 @@ import type { Env } from '../env'; import { cancelBuildPublishJobOnVm } from '../routes/mcp/workspace-tools'; import { resolveAdminSetting } from '../services/admin-settings'; import { recordDeploymentPublishJobLifecycleEventBestEffort } from '../services/project-lifecycle-events'; +import { createCloudflareBuildPorts } from './cloudflare-builder'; export function createDeploymentPublishJobPorts(env: Env): DeploymentPublishJobPorts { return { @@ -13,6 +14,7 @@ export function createDeploymentPublishJobPorts(env: Env): DeploymentPublishJobP cancelPublishJob: (workspaceId, userId, nodeId, publishJobId, timeoutMs) => cancelBuildPublishJobOnVm(env, workspaceId, userId, nodeId, publishJobId, timeoutMs), }, + builder: createCloudflareBuildPorts(env).builder, lifecycle: { recordPublishJobLifecycleEventBestEffort: (event) => recordDeploymentPublishJobLifecycleEventBestEffort(env, event), diff --git a/apps/api/src/db/migrations/0242_cloudflare_build_executor.sql b/apps/api/src/db/migrations/0242_cloudflare_build_executor.sql new file mode 100644 index 0000000000..e7adb67878 --- /dev/null +++ b/apps/api/src/db/migrations/0242_cloudflare_build_executor.sql @@ -0,0 +1,5 @@ +ALTER TABLE deployment_publish_jobs ADD COLUMN executor_instance_id TEXT; +ALTER TABLE deployment_publish_jobs ADD COLUMN executor_deadline_at TEXT; +ALTER TABLE deployment_publish_jobs ADD COLUMN executor_not_before TEXT; +CREATE INDEX idx_publish_job_executor_reservation ON deployment_publish_jobs(executor, executor_instance_id, project_id); +ALTER TABLE deployment_publish_jobs ADD COLUMN context_project_name TEXT; diff --git a/apps/api/src/db/migrations/0244_cloudflare_build_reservation_deletion_guard.sql b/apps/api/src/db/migrations/0244_cloudflare_build_reservation_deletion_guard.sql new file mode 100644 index 0000000000..768e5a8397 --- /dev/null +++ b/apps/api/src/db/migrations/0244_cloudflare_build_reservation_deletion_guard.sql @@ -0,0 +1,7 @@ +-- D1 is the capacity ledger. Keep even terminal jobs until the microVM stop +-- has been confirmed and its reservation released. Also fences FK cascades. +CREATE TRIGGER cloudflare_build_reservation_no_delete +BEFORE DELETE ON deployment_publish_jobs +WHEN OLD.executor = 'cloudflare' AND OLD.context_shadow = 0 + AND OLD.executor_instance_id IS NOT NULL +BEGIN SELECT RAISE(ABORT, 'cloudflare_build_reservation_held'); END; diff --git a/apps/api/src/durable-objects/compose-builder-container.ts b/apps/api/src/durable-objects/compose-builder-container.ts new file mode 100644 index 0000000000..64a1ed7961 --- /dev/null +++ b/apps/api/src/durable-objects/compose-builder-container.ts @@ -0,0 +1,535 @@ +import { Container } from '@cloudflare/containers'; +import { + appendDeploymentPublishJobEvent, + type CloudflareBuildStopGuard, + isCloudflareBuildCapacityError, + PUBLISH_JOB_TERMINAL_STATUSES, + recoverReservedCloudflareBuild, + releaseCloudflareBuildReservation, + startReservedCloudflareBuild, +} from '@simple-agent-manager/app-deployment'; +import { log } from '@simple-agent-manager/worker-core'; +import { and, eq } from 'drizzle-orm'; +import { drizzle } from 'drizzle-orm/d1'; + +import { createCloudflareBuildPorts } from '../app-deployment-ports/cloudflare-builder'; +import * as schema from '../db/schema'; +import type { Env } from '../env'; +import { errors } from '../middleware/error'; +import { resolveAdminSetting } from '../services/admin-settings'; +import { recordDeploymentPublishJobLifecycleEventBestEffort } from '../services/project-lifecycle-events'; +import { signPublishJobToken } from '../services/publish-job-token'; + +const PORT = 8080; +const STATE_KEY = 'buildJob'; +interface BuildState { + jobId: string; + attempt: number; + deadline?: number; + stopRetryMs: number; + stopRequested?: boolean; + version?: string; + accepted?: boolean; + reservationEpoch?: string | null; + quiescent?: boolean; +} + +/** One DinD microVM per publishJobId, never reused across jobs/projects. + * Guest code cannot extend the persisted deadline or access Worker bindings. */ +export class ComposeBuilderContainer extends Container { + defaultPort = PORT; + sleepAfter: string | number = '20m'; // Upper safety bound; set from each admitted job below. + // Deployment builds have the same unrestricted Internet access as VM workspaces. + // Keep transfers direct: no SDK outbound proxy or HTTPS interception. The + // one-job microVM and scoped callback token, not an egress filter, are the boundary. + enableInternet = true; + private operation: Promise = Promise.resolve(); + private startAbort?: AbortController; + private startupInProgress = false; + private kickoff: Promise = Promise.resolve(); + // The SDK invokes these hooks from its constructor. Read durable state rather + // than subclass fields, whose initializers have not run at that point. + override renewActivityTimeout() { + if (this.ctx.storage.kv.get(STATE_KEY)?.quiescent) return; + super.renewActivityTimeout(); + } + override async scheduleNextAlarm(ms?: number) { + if (!this.ctx.storage.kv.get(STATE_KEY)?.quiescent) + await super.scheduleNextAlarm(ms); + // A stop may have completed while the SDK awaited storage.sync(). + if (this.ctx.storage.kv.get(STATE_KEY)?.quiescent) + await this.ctx.storage.deleteAlarm(); + } + override async alarm(info?: AlarmInvocationInfo) { + if (this.ctx.storage.kv.get(STATE_KEY)?.quiescent) { + await this.ctx.storage.deleteAlarm(); + return; + } + try { + await super.alarm(info); + } finally { + // The base alarm snapshots schedules before delivering onStop, then can + // rearm that stale snapshot after our terminal cleanup has removed them. + if (this.ctx.storage.kv.get(STATE_KEY)?.quiescent) + await this.ctx.storage.deleteAlarm(); + } + } + private async quiesce(state: BuildState | undefined) { + if (state) { + const stopped = { ...state, quiescent: true }; + delete stopped.deadline; + // Keep the marker and schedule removal in one synchronous turn so an + // admitted retry cannot install fresh timers between these operations. + this.ctx.storage.kv.put(STATE_KEY, stopped); + } + this.deleteSchedules('launchBuilder'); + this.deleteSchedules('enforceDeadline'); + await this.ctx.storage.deleteAlarm(); + } + private serialized(fn: () => Promise): Promise { + const result = this.operation.then(fn, fn); + this.operation = result.catch(() => undefined); + return result; + } + private fetchBootstrap(url: string, init: RequestInit & { signal: AbortSignal }) { + init.signal.throwIfAborted(); + const container = this.ctx.container; + if (!container?.running) throw new Error('Builder stopped before acceptance'); + // Raw workerd port transport never invokes the SDK's implicit restart path. + return container.getTcpPort(PORT).fetch(url, init); + } + private async loadJob(jobId: string, attempt: number) { + const db = drizzle(this.env.DATABASE, { schema }); + const [job] = await db + .select() + .from(schema.deploymentPublishJobs) + .where( + and( + eq(schema.deploymentPublishJobs.id, jobId), + eq(schema.deploymentPublishJobs.attempt, attempt), + eq(schema.deploymentPublishJobs.executor, 'cloudflare'), + eq(schema.deploymentPublishJobs.contextShadow, false) + ) + ) + .limit(1); + return { db, job }; + } + /** Acknowledge persisted kickoff promptly; cold startup is owned by a DO + * alarm, not the source HTTP waitUntil's 30-second lifetime. */ + async startJob(jobId: string, attempt: number, expectedEpoch: string | null = null) { + return this.serialized(async () => { + let { job } = await this.loadJob(jobId, attempt); + if ((job?.executorNotBefore ?? null) !== expectedEpoch) + throw errors.conflict('Builder reservation changed'); + if (job?.status === 'context_ready' && job.executorInstanceId === job.id) { + await recoverReservedCloudflareBuild( + drizzle(this.env.DATABASE, { schema }), + jobId, + attempt + ); + // A competing terminal/progress update may have won the repair CAS. + // Inspect it before either the accepted short-circuit or new kickoff. + ({ job } = await this.loadJob(jobId, attempt)); + } + if ( + !job || + job.executorInstanceId !== jobId || + !job.executorDeadlineAt || + PUBLISH_JOB_TERMINAL_STATUSES.has(job.status) + ) + throw errors.conflict('Builder reservation is no longer current'); + const deadline = Date.parse(job.executorDeadlineAt); + if (!Number.isFinite(deadline) || deadline <= Date.now()) + throw errors.conflict('Builder deadline elapsed'); + let previous = await this.ctx.storage.get(STATE_KEY); + if (previous && (previous.jobId !== jobId || previous.attempt !== attempt)) + throw errors.conflict('Builder identity cannot be reused'); + if ((previous?.reservationEpoch ?? null) !== expectedEpoch) previous = undefined; + if (previous?.accepted) return { accepted: true, version: previous.version }; + const stopRetryMs = + previous?.stopRetryMs ?? + Number(await resolveAdminSetting(this.env, 'deployments.builderCapacityBackoffMs')); + await this.ctx.storage.put(STATE_KEY, { + ...previous, + jobId, + attempt, + deadline, + stopRetryMs, + reservationEpoch: expectedEpoch, + quiescent: false, + stopRequested: false, + }); + await this.schedule(new Date(deadline), 'enforceDeadline'); + await this.schedule(new Date(), 'launchBuilder', { + jobId, + attempt, + notBefore: expectedEpoch, + }); + return { accepted: true }; + }); + } + launchBuilder(identity: { jobId: string; attempt: number; notBefore?: string | null }) { + // SDK alarms await callbacks sequentially. Do not hold the hard deadline + // behind a stalled D1 read or other kickoff work. + this.ctx.waitUntil( + this.runBuilder(identity).catch(() => { + log.warn('cloudflare_builder.kickoff_pending', { publishJobId: identity.jobId }); + }) + ); + } + async runBuilder(identity: { jobId: string; attempt: number; notBefore?: string | null }) { + // Alarm delivery and cron recovery may overlap. Coalesce the full operation, + // including stop/requeue, so stale deliveries cannot defeat capacity backoff. + const run = this.kickoff.then(async () => { + let { job } = await this.loadJob(identity.jobId, identity.attempt); + if ((job?.executorNotBefore ?? null) !== (identity.notBefore ?? null)) return; + if (job?.status === 'context_ready' && job.executorInstanceId === job.id) { + job = + (await recoverReservedCloudflareBuild( + drizzle(this.env.DATABASE, { schema }), + identity.jobId, + identity.attempt + )) ?? undefined; + } + if (!job || job.status !== 'starting' || job.executorInstanceId !== job.id) return; + const ports = createCloudflareBuildPorts(this.env); + await startReservedCloudflareBuild( + this.env.DATABASE, + { + ...ports, + builder: { + start: async () => { + try { + await this.launchNow(identity.jobId, identity.attempt, identity.notBefore ?? null); + return 'started'; + } catch (error) { + if (isCloudflareBuildCapacityError(error)) return 'capacity'; + throw error; + } + }, + stop: async (_job, capacity) => { + await this.stopJob(capacity); + }, + }, + }, + job + ); + }); + this.kickoff = run.catch(() => undefined); + return run; + } + private async launchNow(jobId: string, attempt: number, expectedEpoch: string | null) { + return this.serialized(async () => { + const { job } = await this.loadJob(jobId, attempt); + if ( + !job || + (job.executorNotBefore ?? null) !== expectedEpoch || + job.executorInstanceId !== jobId || + !job.executorDeadlineAt || + !job.agentProfileId || + PUBLISH_JOB_TERMINAL_STATUSES.has(job.status) + ) + throw errors.conflict('Builder reservation is no longer current'); + let previous = await this.ctx.storage.get(STATE_KEY); + if (previous && (previous.jobId !== jobId || previous.attempt !== attempt)) + throw errors.conflict('Builder identity cannot be reused'); + if ((previous?.reservationEpoch ?? null) !== expectedEpoch) previous = undefined; + // RUN can bind the former bootstrap port after the controller closes it. + // Never contact that port again after acceptance; status is callback-only. + if (previous?.accepted) return { version: previous.version }; + const deadline = Date.parse(job.executorDeadlineAt); + if (!Number.isFinite(deadline) || deadline <= Date.now()) + throw errors.conflict('Builder deadline elapsed'); + const state: BuildState = { + jobId, + attempt, + deadline, + stopRetryMs: + previous?.stopRetryMs ?? + Number(await resolveAdminSetting(this.env, 'deployments.builderCapacityBackoffMs')), + stopRequested: previous?.stopRequested, + reservationEpoch: expectedEpoch, + }; + await this.ctx.storage.put(STATE_KEY, state); + // Schedule before startup; Container's scheduler owns the underlying alarm. + await this.schedule(new Date(deadline), 'enforceDeadline'); + const { startTimeoutMs, callbackTimeoutMs, callbackAttempts, callbackRetryDelayMs } = + await Promise.all([ + resolveAdminSetting(this.env, 'deployments.builderDaemonReadyTimeoutMs'), + resolveAdminSetting(this.env, 'deployments.builderCallbackTimeoutMs'), + resolveAdminSetting(this.env, 'deployments.builderCallbackAttempts'), + resolveAdminSetting(this.env, 'deployments.builderCallbackRetryDelayMs'), + ]).then(([start, timeout, attempts, delay]) => ({ + startTimeoutMs: Number(start), + callbackTimeoutMs: Number(timeout), + callbackAttempts: Number(attempts), + callbackRetryDelayMs: Number(delay), + })); + this.sleepAfter = Math.max(1, Math.ceil((deadline - Date.now()) / 1000)); + // Only non-secret control budgets enter the process environment. + this.envVars = { + SAM_BUILDER_BOOTSTRAP_TIMEOUT_MS: String(startTimeoutMs), + SAM_BUILDER_CONTROL_TIMEOUT_MS: String(callbackTimeoutMs), + }; + this.startAbort = new AbortController(); + const signal = AbortSignal.any([ + this.startAbort.signal, + AbortSignal.timeout(Math.min(startTimeoutMs, deadline - Date.now())), + ]); + this.startupInProgress = true; + try { + await this.startAndWaitForPorts({ + ports: [PORT], + cancellationOptions: { + abort: signal, + instanceGetTimeoutMS: startTimeoutMs, + portReadyTimeoutMS: startTimeoutMs, + }, + }); + } finally { + this.startupInProgress = false; + if (signal.aborted) { + // The SDK can start after awaiting internal work even if the signal + // was already aborted. Reconcile locally before any D1 failure write. + await this.stopContainer(state); + // Startup has settled, but its deadline verdict still needs delivery. + await this.ctx.storage.put(STATE_KEY, { + ...state, + stopRequested: true, + quiescent: false, + }); + await this.schedule(new Date(), 'enforceDeadline'); + } + } + signal.throwIfAborted(); + // Private SDK transport to this microVM's port; this is not an Internet HTTP endpoint. + const health = await this.fetchBootstrap('http://builder/health', { signal }); // NOSONAR S5332: private workerd getTcpPort transport to this DO's guest, never public HTTP. + const version: unknown = await health.json(); + if ( + !health.ok || + !version || + typeof version !== 'object' || + !('version' in version) || + typeof version.version !== 'string' + ) + throw new Error('Builder version unavailable'); + if ( + this.env.VM_AGENT_REQUIRED_VERSION && + version.version !== this.env.VM_AGENT_REQUIRED_VERSION + ) + throw new Error('Builder version does not match deployed agent release'); + await this.ctx.storage.put(STATE_KEY, { + ...state, + version: version.version, + stopRequested: false, + }); + // Cancellation can commit while startup/health await network I/O. + const { job: current } = await this.loadJob(jobId, attempt); + if (!current || PUBLISH_JOB_TERMINAL_STATUSES.has(current.status)) + throw errors.conflict('Builder job revoked during startup'); + const token = await signPublishJobToken( + this.env, + { + jobId, + attempt, + projectId: job.projectId, + environmentId: job.environmentId, + agentProfileId: job.agentProfileId, + }, + deadline + ); + // Launch never traverses public HTTP; Container SDK routes inside its private port transport. + const startUrl = 'http://builder/start'; // NOSONAR S5332: private workerd getTcpPort transport to this DO's guest, never public HTTP. + const response = await this.fetchBootstrap(startUrl, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + signal, + body: JSON.stringify({ + jobId, + attempt, + projectId: job.projectId, + deadlineAt: job.executorDeadlineAt, + controlPlaneUrl: `https://api.${this.env.BASE_DOMAIN}`, + token, + callbackTimeoutMs, + callbackAttempts, + callbackRetryDelayMs, + }), + }); + if (response.status !== 202) throw new Error('Builder rejected launch'); + await this.ctx.storage.put(STATE_KEY, { + ...state, + version: version.version, + accepted: true, + stopRequested: false, + }); + this.ctx.waitUntil( + appendDeploymentPublishJobEvent(drizzle(this.env.DATABASE, { schema }), { + publishJobId: jobId, + expectedAttempt: attempt, + projectId: job.projectId, + environmentId: job.environmentId, + workspaceId: job.workspaceId, + nodeId: job.nodeId, + eventType: 'publish.builder.accepted', + message: 'Cloudflare builder accepted job', + detail: { version: version.version }, + }).catch(() => { + log.warn('cloudflare_builder.accepted_event_pending', { publishJobId: jobId }); + }) + ); + return { version: version.version }; + }); + } + private async stopContainer(state: BuildState | undefined) { + if (state) await this.ctx.storage.put(STATE_KEY, { ...state, stopRequested: true }); + // Calling destroy on an inactive guest can activate platform compute. Read + // workerd's synchronous running flag, never a fetch/start/state SDK path. + if (this.ctx.container?.running) await this.destroy(); + if (this.startupInProgress && state) { + this.deleteSchedules('launchBuilder'); + this.deleteSchedules('enforceDeadline'); + await this.schedule(new Date(Date.now() + state.stopRetryMs), 'enforceDeadline'); + } else { + await this.quiesce(state); + } + } + async stopJob(capacity?: CloudflareBuildStopGuard) { + if (!capacity) this.startAbort?.abort(); + return this.serialized(async () => { + const state = await this.ctx.storage.get(STATE_KEY); + const db = drizzle(this.env.DATABASE, { schema }); + if (capacity) { + const { job } = await this.loadJob(capacity.jobId, capacity.attempt); + if ( + !job || + job.executorInstanceId !== job.id || + (job.executorNotBefore ?? null) !== capacity.notBefore || + (job.status !== 'starting' && !PUBLISH_JOB_TERMINAL_STATUSES.has(job.status)) || + (state?.accepted && + (state.reservationEpoch ?? null) === capacity.notBefore && + !PUBLISH_JOB_TERMINAL_STATUSES.has(job.status)) + ) + return; + // A rejected old epoch must not even abort a newer startup. + this.startAbort?.abort(); + } + await this.stopContainer(state); + if (capacity) { + await releaseCloudflareBuildReservation( + db, + capacity.jobId, + capacity.attempt, + capacity.retryAt, + capacity.notBefore + ); + } else if (state) { + await releaseCloudflareBuildReservation(db, state.jobId, state.attempt); + } + }); + } + async enforceDeadline() { + const state = await this.ctx.storage.get(STATE_KEY); + // Destruction must not wait for D1 or lifecycle publication. A database + // outage may delay the verdict, but cannot extend arbitrary RUN execution. + this.startAbort?.abort(); + try { + // Bypass the startup queue: database reads in that queue may be stalled. + // The execution deadline owns destruction independently of D1 health. + await this.stopContainer(state); + } catch (error) { + // Container SDK consumes one-shot schedules even when a callback throws. + // Re-arm explicitly; preserve the original deadline rather than extending it. + if (state) await this.schedule(new Date(Date.now() + state.stopRetryMs), 'enforceDeadline'); + throw error; + } + if (!state || this.startupInProgress) return; + const { db, job } = await this.loadJob(state.jobId, state.attempt); + if (job && !PUBLISH_JOB_TERMINAL_STATUSES.has(job.status)) { + const changed = await appendDeploymentPublishJobEvent(db, { + publishJobId: job.id, + expectedAttempt: state.attempt, + projectId: job.projectId, + environmentId: job.environmentId, + workspaceId: job.workspaceId, + nodeId: job.nodeId, + status: 'failed', + terminal: true, + eventType: 'publish.builder.deadline', + currentStep: 'deadline', + message: 'Cloudflare build hard deadline exceeded', + errorCode: 'deadline_exceeded', + }); + await releaseCloudflareBuildReservation(db, state.jobId, state.attempt); + if (changed) + await recordDeploymentPublishJobLifecycleEventBestEffort(this.env, { + projectId: job.projectId, + publishJobId: job.id, + environmentId: job.environmentId, + status: 'failed', + terminal: true, + currentStep: 'deadline', + source: 'cloudflare_builder.deadline', + occurredAt: Date.now(), + }); + } else if (job) { + await releaseCloudflareBuildReservation(db, state.jobId, state.attempt); + } + } + override async onStop() { + // SDK startup synchronizes a previous guest's pending stop event before it + // starts the next guest. The current startup owns its failure verdict and + // deadline; that older notification cannot revoke either. + if (this.startupInProgress || this.ctx.container?.running) return; + const state = this.ctx.storage.kv.get(STATE_KEY); + // Local cleanup cannot depend on D1 being available or on lifecycle writes. + await this.quiesce(state); + if (!state) return; + const { db, job } = await this.loadJob(state.jobId, state.attempt); + const current = this.ctx.storage.kv.get(STATE_KEY); + if ( + !current?.quiescent || + current.jobId !== state.jobId || + current.attempt !== state.attempt || + (current.reservationEpoch ?? null) !== (state.reservationEpoch ?? null) || + (job?.executorNotBefore ?? null) !== (state.reservationEpoch ?? null) + ) + return; + if (job && !state.stopRequested && !PUBLISH_JOB_TERMINAL_STATUSES.has(job.status)) { + const changed = await appendDeploymentPublishJobEvent(db, { + publishJobId: job.id, + expectedAttempt: state.attempt, + projectId: job.projectId, + environmentId: job.environmentId, + workspaceId: job.workspaceId, + nodeId: job.nodeId, + status: 'failed', + terminal: true, + eventType: 'publish.builder.exited', + expectedReservationEpoch: state.reservationEpoch ?? null, + expectedExecutorInstanceId: state.jobId, + currentStep: 'builder_exit', + message: 'Cloudflare builder exited before completing the job', + errorCode: 'builder_exited', + }); + if (changed) + await recordDeploymentPublishJobLifecycleEventBestEffort(this.env, { + projectId: job.projectId, + publishJobId: job.id, + environmentId: job.environmentId, + status: 'failed', + terminal: true, + currentStep: 'builder_exit', + source: 'cloudflare_builder.exit', + occurredAt: Date.now(), + }); + } + await releaseCloudflareBuildReservation( + db, + state.jobId, + state.attempt, + undefined, + state.reservationEpoch ?? null + ); + } +} diff --git a/apps/api/src/env.ts b/apps/api/src/env.ts index 22a18f1a73..c04d9b785c 100644 --- a/apps/api/src/env.ts +++ b/apps/api/src/env.ts @@ -8,6 +8,7 @@ import type { ProjectDataEnv } from '@simple-agent-manager/project-data'; import type { ArtifactsBinding, RepoHostingEnv } from '@simple-agent-manager/repo-hosting'; import type { WorkspaceAdmissionEnv } from '@simple-agent-manager/scheduler-core'; +import type { ComposeBuilderContainer } from './durable-objects/compose-builder-container'; import type { VmAgentContainer } from './durable-objects/vm-agent-container'; import type { TaskRecoveryEnv } from './task-recovery-env'; import type { WebhookTriggerEnv } from './webhook-trigger-env'; @@ -25,6 +26,8 @@ export interface Env OperationsEnv, RepoHostingEnv, AiProxyEnv { + COMPOSE_BUILDER: DurableObjectNamespace; + DEPLOY_BUILDER_CLASS_MAX_INSTANCES?: string; CLI_RECEIPT_REQUEST_MAX_BYTES?: string; // default 262144 CLI_RECEIPT_RESPONSE_MAX_BYTES?: string; // default 65536 // D1 Database. diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 93ab7fbd38..25a339dfea 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -3,6 +3,9 @@ import './repo-hosting-wiring'; export { McpRateCounter } from './durable-objects/mcp-rate-counter'; export { WorkspaceBootLog } from './durable-objects/workspace-boot-log'; +// SDK 0.3.7 requires this helper when reconstructing a running Container. +// Builders register no outbound interceptors, so their network traffic stays direct. +export { ContainerProxy } from '@cloudflare/containers'; import { adminAgentEmailRoutes } from './routes/admin-agent-email'; import { cliOperationReceiptRoutes } from './routes/cli-operation-receipts'; import { cliProjectMetadataRoutes } from './routes/cli-project-metadata'; @@ -546,3 +549,5 @@ export default { await handleInboundAgentEmail(message, env); }, }; + +export { ComposeBuilderContainer } from './durable-objects/compose-builder-container'; diff --git a/apps/api/src/middleware/app-error-handler.ts b/apps/api/src/middleware/app-error-handler.ts index 013bfae152..8dd34c87e8 100644 --- a/apps/api/src/middleware/app-error-handler.ts +++ b/apps/api/src/middleware/app-error-handler.ts @@ -1,3 +1,7 @@ +import { + CLOUDFLARE_BUILD_DELETION_CONFLICT, + isCloudflareBuildDeletionConflict, +} from '@simple-agent-manager/app-deployment'; import type { Context } from 'hono'; import type { ContentfulStatusCode } from 'hono/utils/http-status'; @@ -121,7 +125,10 @@ export function handleAppError(err: Error, c: AppContext): Response { let status: number; let body: Record; - if (err instanceof AppError) { + if (isCloudflareBuildDeletionConflict(err)) { + status = 409; + body = { error: 'CONFLICT', message: CLOUDFLARE_BUILD_DELETION_CONFLICT }; + } else if (err instanceof AppError) { status = err.statusCode; body = { ...err.toJSON() }; } else if (err instanceof GcpApiError) { diff --git a/apps/api/src/routes/deployment-environments.ts b/apps/api/src/routes/deployment-environments.ts index dc4d8275c3..13093f19d4 100644 --- a/apps/api/src/routes/deployment-environments.ts +++ b/apps/api/src/routes/deployment-environments.ts @@ -1,10 +1,10 @@ +import { assertNoReservedCloudflareBuilds } from '@simple-agent-manager/app-deployment'; /** * Deployment environment routes. * * Scoped under /api/projects/:projectId/environments. * Auth: session cookie + active project membership/capabilities. */ - import { and, eq } from 'drizzle-orm'; import { drizzle } from 'drizzle-orm/d1'; import { Hono } from 'hono'; @@ -362,6 +362,7 @@ deploymentEnvironmentRoutes.delete( if (!environment) { throw errors.notFound('Deployment environment'); } + await assertNoReservedCloudflareBuilds(db, { environmentId: envId }); // Reconstruct app-route hostnames from each release's manifest before the // cascade delete removes the rows. diff --git a/apps/api/src/routes/mcp/compose-publish-tools.ts b/apps/api/src/routes/mcp/compose-publish-tools.ts index 6cb0542ecf..8b4c21929e 100644 --- a/apps/api/src/routes/mcp/compose-publish-tools.ts +++ b/apps/api/src/routes/mcp/compose-publish-tools.ts @@ -15,6 +15,8 @@ import { createDeploymentPublishJobPorts } from '../../app-deployment-ports/publ import * as schema from '../../db/schema'; import type { Env } from '../../env'; import { parsePositiveInt } from '../../lib/route-helpers'; +import { resolveAdminSetting } from '../../services/admin-settings'; +import { collectBuildContextOnSource } from '../../services/build-context-collection'; import { scheduleBuildContextShadow } from '../../services/build-context-shadow'; import { assertAgentDeploymentAllowed } from '../../services/deployment-control'; import { loadDeploymentBuildInterpolationEnv } from '../../services/deployment-environment-config'; @@ -111,32 +113,36 @@ export async function handleBuildAndPublish( .from(schema.nodes) .where(eq(schema.nodes.id, workspace.nodeId)) .limit(1); - scheduleBuildContextShadow( - env, - { - projectId, - environmentId: policyResult.environmentId, - workspaceId: tokenData.workspaceId, - nodeId: workspace.nodeId, - taskId: tokenData.taskId || null, - agentProfileId: policyResult.taskAgentProfileId || null, - requestedBy: tokenData.userId, - environmentName: environment, - reference, - workingDir: workingDir ?? null, - }, - { buildInterpolationEnv: buildEnv.values, secretInterpolationKeys: buildEnv.secretKeys }, - execCtx - ); - // Temporary until phase 3 of idea 01KZ6V37D1QGDR3WN12PSDB0QD adds the Cloudflare builder. - if (node?.runtime === 'cf-container') { + const executor = + node?.runtime === 'cf-container' + ? 'cloudflare' + : await resolveAdminSetting(env, 'deployments.buildExecutor'); + if (executor === 'cloudflare' && !policyResult.taskAgentProfileId) return jsonRpcError( requestId, INVALID_PARAMS, - "Deploying from Instant sessions isn't available yet; use a VM session." + 'Cloudflare publishing requires a task agent profile.' + ); + if (executor === 'node') + scheduleBuildContextShadow( + env, + { + projectId, + environmentId: policyResult.environmentId, + workspaceId: tokenData.workspaceId, + nodeId: workspace.nodeId, + taskId: tokenData.taskId || null, + agentProfileId: policyResult.taskAgentProfileId || null, + requestedBy: tokenData.userId, + environmentName: environment, + reference, + workingDir: workingDir ?? null, + }, + { buildInterpolationEnv: buildEnv.values, secretInterpolationKeys: buildEnv.secretKeys }, + execCtx ); - } const job = await createDeploymentPublishJob(db, { + executor: executor === 'cloudflare' ? 'cloudflare' : 'node', projectId, environmentId: policyResult.environmentId, workspaceId: tokenData.workspaceId, @@ -191,6 +197,31 @@ export async function handleBuildAndPublish( if (workingDir) proxyBody.workingDir = workingDir; try { + if (executor === 'cloudflare') { + const result = await collectBuildContextOnSource(env, job, { + buildInterpolationEnv: buildEnv.values, + secretInterpolationKeys: buildEnv.secretKeys, + }); + if (!result.supported) throw new Error(result.message); + return jsonRpcSuccess(requestId, { + content: [ + { + type: 'text', + text: JSON.stringify({ + publishJobId: job.id, + executor: 'cloudflare', + status: 'queued', + environment, + environmentId: job.environmentId, + instructions: + 'The source is collecting the build context. Keep it awake until deployment.publish_job.context_ready or later. After context_ready the independent Cloudflare builder owns the job and the source can sleep. Wait for deployment.publish_job events; do not submit a duplicate job.', + pollTool: 'deployments_read', + pollMethod: 'publish_status', + }), + }, + ], + }); + } await startBuildPublishJobOnVm( env, tokenData.workspaceId, @@ -278,6 +309,7 @@ export async function handleBuildAndPublish( status: 'failed', currentStep: 'start', level: 'error', + sourceCollector: executor === 'cloudflare', eventType: 'publish.job.start_failed', message, errorMessage: message, @@ -285,6 +317,32 @@ export async function handleBuildAndPublish( terminal: true, retryable: true, }); + if (!changed && executor === 'cloudflare') { + const [current] = await db + .select() + .from(schema.deploymentPublishJobs) + .where(eq(schema.deploymentPublishJobs.id, job.id)) + .limit(1); + if (current) + return jsonRpcSuccess(requestId, { + content: [ + { + type: 'text', + text: JSON.stringify({ + publishJobId: job.id, + executor, + status: current.status, + environment, + environmentId: current.environmentId, + pollTool: 'deployments_read', + pollMethod: 'publish_status', + instructions: + 'The job has already advanced. Follow this job to completion; do not submit a duplicate.', + }), + }, + ], + }); + } if (changed) await recordDeploymentPublishJobLifecycleEventBestEffort(env, { projectId, diff --git a/apps/api/src/routes/mcp/deployment-guide-tools.ts b/apps/api/src/routes/mcp/deployment-guide-tools.ts index f75bfcf142..ec4fa8aad1 100644 --- a/apps/api/src/routes/mcp/deployment-guide-tools.ts +++ b/apps/api/src/routes/mcp/deployment-guide-tools.ts @@ -29,7 +29,7 @@ SAM app deployment is **agent-first** and **never goes through CI**. This is the - A user creates a **deployment environment** (for example \`staging\` or \`production\`) and enables agent deployment for it. - If the user asks for a new non-production environment, you may create it with \`deployments_write\` method \`create_environment\`; SAM restricts it to your creator profile by default and the project owner can later change or disable the policy. - You, the agent, author a **Docker Compose stack** in the workspace and call one tool — \`deployments_write\` method \`publish\` — targeting that environment. -- SAM builds the Compose stack **server-side on the SAM VM**, pushes the built service images to the project-scoped registry **using SAM-owned credentials**, and records the release. +- SAM builds the Compose stack on the selected executor (Cloudflare for Instant; the source node by default for VM sessions), uploads the service images, and records the release. - SAM's deployment nodes then pull the recorded release and run it. What this means for you: @@ -133,9 +133,9 @@ Call \`deployments_write { method: 'publish', environment, reference?, workingDi - \`reference\` — optional release tag/identifier (defaults to "latest"). - \`workingDir\` — optional absolute path under \`/workspaces\` if the Compose file is not at the workspace root. -SAM returns a \`publishJobId\` quickly after the VM accepts the job. The actual Docker Compose build, image export, artifact upload, and release recording continue in the background. You do not run any docker or registry commands. +SAM returns a \`publishJobId\` quickly after the source accepts the job. The actual Docker Compose build, image export, artifact upload, and release recording continue in the background. You do not run any docker or registry commands. -Publishing requires a VM session; Instant sessions cannot publish yet. Jobs fail with retryable \`stalled\` when a heartbeat-capable executor stops heartbeating (older agents are deadline-only) or \`deadline_exceeded\` after the overall deadline. To cancel, use \`deployments_write { method: 'cancel_publish', publishJobId }\` (also callable as \`cancel_publish\`). +Both Instant and VM sessions can publish. Instant always builds in a dedicated Cloudflare Container. VM sessions default to building on their node; an administrator can select the Cloudflare executor. For Cloudflare builds, the source collects and uploads a verified portable context first. Wait until \`publish_status\` reports \`context_ready\` or subsequent builder progress before sleeping the source; the remote build can then continue independently. Deployment targets remain VMs. Jobs fail with retryable \`stalled\` when a heartbeat-capable executor stops heartbeating (older agents are deadline-only) or \`deadline_exceeded\` after the overall deadline. To cancel, use \`deployments_write { method: 'cancel_publish', publishJobId }\` (also callable as \`cancel_publish\`). After \`deployments_write\` method \`publish\` returns, call \`deployments_read { method: 'publish_status', publishJobId }\` every 10-20 seconds until the status is terminal: diff --git a/apps/api/src/routes/nodes/delete.ts b/apps/api/src/routes/nodes/delete.ts index a7bac4d66d..a59fd397db 100644 --- a/apps/api/src/routes/nodes/delete.ts +++ b/apps/api/src/routes/nodes/delete.ts @@ -1,3 +1,4 @@ +import { assertNoReservedCloudflareBuilds } from '@simple-agent-manager/app-deployment'; import { isUserOwnedNodeClass } from '@simple-agent-manager/shared'; import { and, eq, sql } from 'drizzle-orm'; import { drizzle } from 'drizzle-orm/d1'; @@ -172,6 +173,7 @@ export async function deleteOwnedNode( userId: string ): Promise { const nodeId = node.id; + await assertNoReservedCloudflareBuilds(db, { nodeId }); const strandedTasks = await listStrandedNodeTasks(env, nodeId); const cleanup = await deleteNodeResources(nodeId, userId, env); @@ -243,6 +245,7 @@ export async function completeOwnerNodeRemoval(input: { }): Promise { const { env, db, node, userId, cleanup } = input; const nodeId = node.id; + await assertNoReservedCloudflareBuilds(db, { nodeId }); // Deprovision app-route DNS records for any deployment environments hosted on // this node. The environment rows survive (nodeId is set null by the FK), but // their grey-cloud A records would otherwise point at the now-freed VM IP. diff --git a/apps/api/src/routes/nodes/diagnostics.ts b/apps/api/src/routes/nodes/diagnostics.ts index 9289b3b8c3..47c9d4e705 100644 --- a/apps/api/src/routes/nodes/diagnostics.ts +++ b/apps/api/src/routes/nodes/diagnostics.ts @@ -50,6 +50,7 @@ nodeDiagnosticsRoutes.get('/:id/events', async (c) => { * Only available when the node is running. */ nodeDiagnosticsRoutes.get('/:id/system-info', async (c) => { + c.header('Cache-Control', 'no-store'); const nodeId = c.req.param('id'); const node = await ownedNode(c, nodeId); const outcome = await runNodeDiagnostic(node, ownerNodeAccess(getUserId(c)), (id, userId) => diff --git a/apps/api/src/routes/nodes/manual-deletion.ts b/apps/api/src/routes/nodes/manual-deletion.ts index f97313369a..8b17ccd316 100644 --- a/apps/api/src/routes/nodes/manual-deletion.ts +++ b/apps/api/src/routes/nodes/manual-deletion.ts @@ -1,3 +1,4 @@ +import { assertNoReservedCloudflareBuilds } from '@simple-agent-manager/app-deployment'; import { drizzle } from 'drizzle-orm/d1'; import type { Context } from 'hono'; @@ -25,6 +26,7 @@ export async function confirmManualNodeDeletionRoute(c: Context<{ Bindings: Env const owned = await requireNodeOwnership(c, nodeId); if (!owned) throw errors.notFound('Node'); + await assertNoReservedCloudflareBuilds(db, { nodeId }); const strandedTasks = await listStrandedNodeTasks(c.env, nodeId); const { node, runtimeTerminationConfirmedAt } = await recordManualNodeDeletion( db, diff --git a/apps/api/src/routes/projects/_publish-callback-auth.ts b/apps/api/src/routes/projects/_publish-callback-auth.ts new file mode 100644 index 0000000000..b782931bfe --- /dev/null +++ b/apps/api/src/routes/projects/_publish-callback-auth.ts @@ -0,0 +1,95 @@ +import type { Context } from 'hono'; +import { decodeJwt } from 'jose'; + +import type { Env } from '../../env'; +import { extractBearerToken } from '../../lib/auth-helpers'; +import { readRequestJsonRecord, RequestBodyTooLargeError } from '../../lib/runtime-validation'; +import { AppError, errors } from '../../middleware/error'; +import { resolveAdminSetting } from '../../services/admin-settings-resolution'; +import { verifyPublishJobToken } from '../../services/publish-job-token'; +import type { WorkspaceDeletionCallbackKind } from '../../services/workspace-deletion-callback-signal'; +import { verifyWorkspacePublishCallback } from './_callback-auth'; + +async function readPublishBody(c: Context<{ Bindings: Env }>, context: string) { + try { + return await readRequestJsonRecord( + c.req.raw, + context, + Number(await resolveAdminSetting(c.env, 'deployments.publishCallbackMaxBodyBytes')) + ); + } catch (error) { + if (error instanceof RequestBodyTooLargeError) + throw new AppError( + 413, + 'PAYLOAD_TOO_LARGE', + 'Publish callback body exceeds the configured byte limit' + ); + throw errors.badRequest('Publish callback JSON object required'); + } +} + +/** Only the existing events, artifact, and release sinks opt in. Context upload + * and registry credentials remain source-workspace-only. The unverified scope + * is routing information; both branches perform full signature verification. */ +export async function verifyPublishCallback( + c: Context<{ Bindings: Env }>, + logPrefix: WorkspaceDeletionCallbackKind, + scopeErrorMessage: string +) { + const authorization = c.req.header('Authorization'); + let jobScope = false; + try { + jobScope = decodeJwt(extractBearerToken(authorization)).scope === 'publish-job'; + } catch { + /* verifier returns 401 */ + } + if (!jobScope) { + const verified = await verifyWorkspacePublishCallback(c, logPrefix, scopeErrorMessage); + return { ...verified, job: null, body: await readPublishBody(c, logPrefix) }; + } + const token = extractBearerToken(authorization); + const { db, job } = await verifyPublishJobToken(c.env, token); + if ( + job.projectId !== c.req.param('id') || + (c.req.param('jobId') && job.id !== c.req.param('jobId')) + ) + throw errors.forbidden('Publish job identity does not match route'); + const fields = await readPublishBody(c, logPrefix); + if (logPrefix !== 'deployment_publish_job_event') { + if (fields.environmentId !== job.environmentId || fields.environment !== job.environmentName) + throw errors.forbidden('Publish job environment does not match'); + const submittedBy = fields.submittedBy as Record | undefined; + if (logPrefix === 'compose_publish_release') { + if ( + fields.publishJobId !== job.id || + fields.attempt !== job.attempt || + submittedBy?.agentProfileId !== job.agentProfileId || + (submittedBy?.taskId ?? null) !== job.taskId + ) + throw errors.forbidden('Release must match the authenticated job and attempt'); + } else if (fields.agentProfileId !== job.agentProfileId) { + throw errors.forbidden('Publish job agent profile does not match'); + } + const artifacts = logPrefix === 'compose_publish_release' ? fields.services : fields.artifacts; + if (Array.isArray(artifacts)) { + const prefix = `compose-image-artifacts/${job.projectId}/${job.environmentId}/${job.workspaceId}/${job.id}-${job.attempt}/`; + for (const artifact of artifacts) { + if (!artifact || typeof artifact.r2Key !== 'string' || !artifact.r2Key.startsWith(prefix)) + throw errors.forbidden('Artifact must belong to this job and attempt'); + } + } + } + return { + projectId: job.projectId, + workspaceId: job.workspaceId, + userId: job.requestedBy, + db, + job, + body: fields, + // A successful release links its release before provisioning. Its job stays + // nonterminal until the builder's final event; no workspace read is involved. + assertCurrent: async () => { + await verifyPublishJobToken(c.env, token); + }, + }; +} diff --git a/apps/api/src/routes/projects/build-context-callback.ts b/apps/api/src/routes/projects/build-context-callback.ts index e9ead713ed..192517c8a5 100644 --- a/apps/api/src/routes/projects/build-context-callback.ts +++ b/apps/api/src/routes/projects/build-context-callback.ts @@ -11,6 +11,7 @@ import { createBuildContextUpload, verifyBuildContextObject, } from '../../services/build-context-upload'; +import { dispatchCloudflareBuild } from '../../services/cloudflare-build-executor'; import { assertAgentDeploymentAllowedForProfile } from '../../services/deployment-control'; import { recordDeploymentPublishJobLifecycleEventBestEffort } from '../../services/project-lifecycle-events'; import { verifyWorkspacePublishCallback } from './_callback-auth'; @@ -19,6 +20,7 @@ const requestSchema = v.object({ attempt: v.pipe(v.number(), v.integer(), v.minValue(1)), sizeBytes: v.pipe(v.number(), v.integer(), v.minValue(1)), sha256: v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/)), + projectName: v.optional(v.pipe(v.string(), v.maxLength(255), v.regex(/^[a-z0-9][a-z0-9_-]*$/))), durationMs: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0))), }); const buildContextCallbackRoute = new Hono<{ Bindings: Env }>(); @@ -51,6 +53,10 @@ for (const operation of ['init', 'complete'] as const) { ) .limit(1); if (!job) throw errors.notFound('Publish job'); + if (!job.contextShadow && !body.projectName) + throw errors.badRequest( + 'Source agent is missing Compose project identity; restart the workspace to upgrade before using the Cloudflare executor' + ); const policy = await assertAgentDeploymentAllowedForProfile( verified.db, verified.projectId, @@ -114,6 +120,8 @@ for (const operation of ['init', 'complete'] as const) { }) ); await verified.assertCurrent(); + if (operation === 'complete' && !job.contextShadow) + c.executionCtx.waitUntil(dispatchCloudflareBuild(c.env, job.id)); return c.json({ ok: true, status: result.status, ...upload }); } ); diff --git a/apps/api/src/routes/projects/compose-image-artifacts-callback.ts b/apps/api/src/routes/projects/compose-image-artifacts-callback.ts index 13c7c50f32..317d66a0b4 100644 --- a/apps/api/src/routes/projects/compose-image-artifacts-callback.ts +++ b/apps/api/src/routes/projects/compose-image-artifacts-callback.ts @@ -5,7 +5,7 @@ import * as v from 'valibot'; import type { Env } from '../../env'; import { log } from '../../lib/logger'; -import { parseWithSchema, readRequestJsonRecord } from '../../lib/runtime-validation'; +import { parseWithSchema } from '../../lib/runtime-validation'; import { ulid } from '../../lib/ulid'; import { AppError, errors } from '../../middleware/error'; import { @@ -17,7 +17,7 @@ import { } from '../../services/compose-image-artifacts'; import { assertAgentDeploymentAllowedForProfile } from '../../services/deployment-control'; import type { WorkspaceDeletionCallbackKind } from '../../services/workspace-deletion-callback-signal'; -import { verifyWorkspacePublishCallback } from './_callback-auth'; +import { verifyPublishCallback } from './_publish-callback-auth'; const composeImageArtifactsCallbackRoute = new Hono<{ Bindings: Env }>(); @@ -80,18 +80,13 @@ async function verifyArtifactPolicy( c: Context<{ Bindings: Env }>, logPrefix: WorkspaceDeletionCallbackKind ) { - const verified = await verifyWorkspacePublishCallback( + const verified = await verifyPublishCallback( c, logPrefix, 'Invalid token scope for compose image artifact upload' ); - let requestBody: Record; - try { - requestBody = await readRequestJsonRecord(c.req.raw, `${logPrefix}.body`); - } catch { - throw errors.badRequest('Artifact request body is required'); - } + const requestBody = verified.body; let policyFields: InferOutput; try { @@ -151,7 +146,7 @@ composeImageArtifactsCallbackRoute.post('/:id/compose-image-artifacts/init', asy if (services.length === 0) { throw errors.badRequest('Artifact upload init requires at least one service'); } - const uploadId = ulid(); + const uploadId = verified.job ? `${verified.job.id}-${verified.job.attempt}` : ulid(); await verified.assertCurrent(); const uploads = await createComposeImageArtifactUploads(c.env, { diff --git a/apps/api/src/routes/projects/compose-publish-release-callback.ts b/apps/api/src/routes/projects/compose-publish-release-callback.ts index b3871ac32d..e9c9cabb17 100644 --- a/apps/api/src/routes/projects/compose-publish-release-callback.ts +++ b/apps/api/src/routes/projects/compose-publish-release-callback.ts @@ -18,7 +18,7 @@ import * as schema from '../../db/schema'; import type { Env } from '../../env'; import { log, serializeError } from '../../lib/logger'; import { parsePositiveInt } from '../../lib/route-helpers'; -import { parseWithSchema, readRequestJsonRecord } from '../../lib/runtime-validation'; +import { parseWithSchema } from '../../lib/runtime-validation'; import { ulid } from '../../lib/ulid'; import { AppError, errors } from '../../middleware/error'; import { @@ -45,7 +45,7 @@ import { placeReleaseOnDeploymentNode, updateDeploymentEnvironmentForLatestRelease, } from '../deployment-release-submission'; -import { verifyWorkspacePublishCallback } from './_callback-auth'; +import { verifyPublishCallback } from './_publish-callback-auth'; /** * Compose-publish release ingestion callback — mounted BEFORE projectsRoutes in @@ -211,19 +211,18 @@ function resolveComposePublishReservation( } composePublishReleaseCallbackRoute.post('/:id/compose-publish-release', async (c) => { - const { projectId, workspaceId, userId, db, assertCurrent } = - await verifyWorkspacePublishCallback( - c, - 'compose_publish_release', - 'Invalid token scope for compose-publish release' - ); - - let submissionBody: Record; - try { - submissionBody = await readRequestJsonRecord(c.req.raw, 'compose_publish_release.submission'); - } catch { - throw errors.badRequest('Invalid release submission body'); - } + const { + projectId, + workspaceId, + userId, + db, + assertCurrent, + body: submissionBody, + } = await verifyPublishCallback( + c, + 'compose_publish_release', + 'Invalid token scope for compose-publish release' + ); let submission: InferOutput; try { diff --git a/apps/api/src/routes/projects/crud.ts b/apps/api/src/routes/projects/crud.ts index 336fa54fca..a2495e726c 100644 --- a/apps/api/src/routes/projects/crud.ts +++ b/apps/api/src/routes/projects/crud.ts @@ -1,3 +1,4 @@ +import { assertNoReservedCloudflareBuilds } from '@simple-agent-manager/app-deployment'; import type { ListProjectsResponse } from '@simple-agent-manager/shared'; import { and, count, desc, eq, inArray, lt, sql } from 'drizzle-orm'; import { drizzle } from 'drizzle-orm/d1'; @@ -155,6 +156,7 @@ crudRoutes.delete('/:id', async (c) => { const db = drizzle(c.env.DATABASE, { schema }); const project = await requireProjectCapability(db, projectId, userId, 'project:delete'); + await assertNoReservedCloudflareBuilds(db, { projectId }); // Explicitly delete child records instead of relying on D1 CASCADE. // SQLite ignores REFERENCES constraints added via ALTER TABLE, so diff --git a/apps/api/src/routes/projects/deployment-publish-job-callback.ts b/apps/api/src/routes/projects/deployment-publish-job-callback.ts index 11de41cc31..bc71c945bf 100644 --- a/apps/api/src/routes/projects/deployment-publish-job-callback.ts +++ b/apps/api/src/routes/projects/deployment-publish-job-callback.ts @@ -3,18 +3,22 @@ import { Hono } from 'hono'; import type { InferOutput } from 'valibot'; import * as v from 'valibot'; +import { createCloudflareBuildPorts } from '../../app-deployment-ports/cloudflare-builder'; import * as schema from '../../db/schema'; import type { Env } from '../../env'; -import { parseWithSchema, readRequestJsonRecord } from '../../lib/runtime-validation'; +import { log } from '../../lib/logger'; +import { parseWithSchema } from '../../lib/runtime-validation'; import { errors } from '../../middleware/error'; import { appendDeploymentPublishJobEvent, PUBLISH_JOB_TERMINAL_STATUSES, } from '../../services/deployment-publish-jobs'; import { recordDeploymentPublishJobLifecycleEventBestEffort } from '../../services/project-lifecycle-events'; -import { verifyWorkspacePublishCallback } from './_callback-auth'; +import { verifyPublishCallback } from './_publish-callback-auth'; +import { publishJobSpecRoute } from './publish-job-spec'; const deploymentPublishJobCallbackRoute = new Hono<{ Bindings: Env }>(); +deploymentPublishJobCallbackRoute.route('/', publishJobSpecRoute); function optionalString(value: unknown): string | null { return typeof value === 'string' && value.trim() !== '' ? value.trim() : null; @@ -50,12 +54,19 @@ const publishJobEventSchema = v.object({ }); deploymentPublishJobCallbackRoute.post('/:id/deployment-publish-jobs/:jobId/events', async (c) => { - const { projectId, workspaceId, userId, db, assertCurrent } = - await verifyWorkspacePublishCallback( - c, - 'deployment_publish_job_event', - 'Invalid token scope for deployment publish job event' - ); + const { + projectId, + workspaceId, + userId, + db, + assertCurrent, + job: authenticatedJob, + body: requestBody, + } = await verifyPublishCallback( + c, + 'deployment_publish_job_event', + 'Invalid token scope for deployment publish job event' + ); const publishJobId = c.req.param('jobId'); const [job] = await db .select() @@ -73,13 +84,6 @@ deploymentPublishJobCallbackRoute.post('/:id/deployment-publish-jobs/:jobId/even throw errors.notFound('Publish job'); } - let requestBody: Record; - try { - requestBody = await readRequestJsonRecord(c.req.raw, 'deployment_publish_job_event.body'); - } catch { - throw errors.badRequest('Invalid publish job event body'); - } - let event: InferOutput; try { event = parseWithSchema( @@ -97,7 +101,17 @@ deploymentPublishJobCallbackRoute.post('/:id/deployment-publish-jobs/:jobId/even throw errors.badRequest('Publish job event requires eventType and message'); } - const status = optionalString(event.status) ?? undefined; + // The verified context callback already handed execution to admission. The + // collector reports this receipt afterwards, possibly after the builder has + // started. Keep its diagnostic history without letting old source agents + // move the job backwards or bypass context verification. Shadow collection + // still owns its terminal completion. + const sourceContextReceipt = + !authenticatedJob && + job.executor === 'cloudflare' && + !job.contextShadow && + eventType === 'publish.context.collected'; + const status = sourceContextReceipt ? undefined : (optionalString(event.status) ?? undefined); if (event.terminal && (!status || !PUBLISH_JOB_TERMINAL_STATUSES.has(status))) { throw errors.badRequest('Terminal publish job event requires a terminal status'); } @@ -107,10 +121,18 @@ deploymentPublishJobCallbackRoute.post('/:id/deployment-publish-jobs/:jobId/even ) { throw errors.badRequest('Release metadata requires releaseId'); } - const currentStep = optionalString(event.currentStep) ?? optionalString(event.step); + if (authenticatedJob && event.releaseId && event.releaseId !== authenticatedJob.releaseId) + throw errors.forbidden('Event release must already be linked to this job'); + const terminal = event.terminal === true || PUBLISH_JOB_TERMINAL_STATUSES.has(status ?? ''); + const currentStep = sourceContextReceipt + ? undefined + : (optionalString(event.currentStep) ?? optionalString(event.step) ?? undefined); await assertCurrent(); const accepted = await appendDeploymentPublishJobEvent(db, { publishJobId, + expectedAttempt: authenticatedJob?.attempt, + sourceCollector: !authenticatedJob, + expectedExecutor: authenticatedJob ? 'cloudflare' : undefined, projectId, environmentId: job.environmentId, nodeId: job.nodeId, @@ -121,7 +143,7 @@ deploymentPublishJobCallbackRoute.post('/:id/deployment-publish-jobs/:jobId/even eventType, message, detail: requestBody.detail, - terminal: event.terminal === true, + terminal, releaseId: optionalString(event.releaseId) ?? undefined, releaseVersion: optionalNumber(event.releaseVersion) ?? undefined, releaseStatus: optionalString(event.releaseStatus) ?? undefined, @@ -132,7 +154,7 @@ deploymentPublishJobCallbackRoute.post('/:id/deployment-publish-jobs/:jobId/even if (accepted === false) throw errors.conflict('Publish job is terminal or release does not match'); - await assertCurrent(); + if (!authenticatedJob) await assertCurrent(); if ( !job.contextShadow && eventType !== 'publish.job.heartbeat' && @@ -151,14 +173,20 @@ deploymentPublishJobCallbackRoute.post('/:id/deployment-publish-jobs/:jobId/even workspaceId, releaseId: optionalString(event.releaseId) ?? undefined, releaseVersion: optionalNumber(event.releaseVersion) ?? undefined, - terminal: event.terminal === true, + terminal, source: 'deployment_publish_job_callback.status', occurredAt: Date.now(), }) ); } - await assertCurrent(); + if (!authenticatedJob) await assertCurrent(); + if (job.executor === 'cloudflare' && job.executorInstanceId && terminal) + c.executionCtx.waitUntil( + createCloudflareBuildPorts(c.env) + .builder.stop(job) + .catch(() => log.warn('cloudflare_builder.stop_pending', { publishJobId: job.id })) + ); return c.json({ ok: true }); }); diff --git a/apps/api/src/routes/projects/publish-job-spec.ts b/apps/api/src/routes/projects/publish-job-spec.ts new file mode 100644 index 0000000000..b883a17f6a --- /dev/null +++ b/apps/api/src/routes/projects/publish-job-spec.ts @@ -0,0 +1,58 @@ +import { createBuildContextDownload } from '@simple-agent-manager/app-deployment'; +import { Hono } from 'hono'; + +import type { Env } from '../../env'; +import { extractBearerToken } from '../../lib/auth-helpers'; +import { errors } from '../../middleware/error'; +import { resolveAdminSetting } from '../../services/admin-settings'; +import { loadDeploymentBuildInterpolationEnv } from '../../services/deployment-environment-config'; +import { verifyPublishJobToken } from '../../services/publish-job-token'; + +/** Mounted with the existing job callback router, before session-cookie auth. */ +export const publishJobSpecRoute = new Hono<{ Bindings: Env }>(); +publishJobSpecRoute.get('/:id/deployment-publish-jobs/:jobId/spec', async (c) => { + const { db, job } = await verifyPublishJobToken( + c.env, + extractBearerToken(c.req.header('Authorization')) + ); + if (job.projectId !== c.req.param('id') || job.id !== c.req.param('jobId')) + throw errors.forbidden('Publish job route identity mismatch'); + if ( + !job.contextR2Key || + !job.contextSha256 || + !job.contextBytes || + !job.executorDeadlineAt || + !job.executorInstanceId + ) + throw errors.conflict('Job has no verified admitted context'); + const interpolation = await loadDeploymentBuildInterpolationEnv(db, job.environmentId); + const expiresIn = Math.min( + Number(await resolveAdminSetting(c.env, 'deployments.buildContextUploadTtlSeconds')), + Math.floor((Date.parse(job.executorDeadlineAt) - Date.now()) / 1000) + ); + if (expiresIn < 1) throw errors.gone('Publish job deadline elapsed'); + const contextUrl = await createBuildContextDownload(c.env, job.contextR2Key, expiresIn); + await verifyPublishJobToken(c.env, extractBearerToken(c.req.header('Authorization'))); + return c.json({ + jobId: job.id, + attempt: job.attempt, + environment: job.environmentName, + environmentId: job.environmentId, + reference: job.reference, + agentProfileId: job.agentProfileId, + taskId: job.taskId ?? '', + contextUrl, + contextBytes: job.contextBytes, + contextSha256: job.contextSha256, + projectName: job.contextProjectName, + maxBytes: Number(await resolveAdminSetting(c.env, 'deployments.buildContextMaxBytes')), + buildInterpolationEnv: interpolation.values, + secretInterpolationKeys: interpolation.secretKeys, + daemonReadyTimeoutMs: Number( + await resolveAdminSetting(c.env, 'deployments.builderDaemonReadyTimeoutMs') + ), + heartbeatIntervalMs: Number( + await resolveAdminSetting(c.env, 'deployments.builderHeartbeatIntervalMs') + ), + }); +}); diff --git a/apps/api/src/scheduled/handler.ts b/apps/api/src/scheduled/handler.ts index 53501fc377..6bb863e67d 100644 --- a/apps/api/src/scheduled/handler.ts +++ b/apps/api/src/scheduled/handler.ts @@ -6,6 +6,7 @@ import type { Env } from '../env'; import { log } from '../lib/logger'; import { runAgentEmailRecovery } from '../services/agent-email/recovery'; import { CAPACITY_POOL_CONTINUATION_CRON } from '../services/capacity-pool-refresh-defaults'; +import { drainCloudflareBuilds } from '../services/cloudflare-build-executor'; import { reconcileDiagnosisRuns } from '../services/diagnosis-runner'; import { reconcileDiagnosticIncidents } from '../services/diagnostic-incident-reconciliation'; import { refreshGcpPriceTableIfDue } from '../services/gcp-price-table'; @@ -154,6 +155,7 @@ export async function scheduled( await sweeps.isolate('deployment_publish_jobs', () => runDeploymentPublishJobSweep(env, createDeploymentPublishJobPorts(env), ctx.waitUntil.bind(ctx)) ); + await sweeps.isolate('cloudflare_build_drain', () => drainCloudflareBuilds(env)); const githubTriggerRecovery = await sweeps.isolate('github_trigger_recovery', () => runGitHubTriggerRecovery(env, ctx.waitUntil.bind(ctx)) ); diff --git a/apps/api/src/scheduled/node-cleanup/shared.ts b/apps/api/src/scheduled/node-cleanup/shared.ts index 92d31a4aa1..9418f88aa2 100644 --- a/apps/api/src/scheduled/node-cleanup/shared.ts +++ b/apps/api/src/scheduled/node-cleanup/shared.ts @@ -363,7 +363,18 @@ async function runStrictCleanup( return 'destroyed'; } catch (error) { - await handleCleanupFailure(env, node, nowIso, options, error); + try { + await handleCleanupFailure(env, node, nowIso, options, error); + } catch (failureError) { + // Failure diagnosis and persistence can fail too. Keep this candidate's + // failure from suppressing teardown of the remaining nodes in the phase. + log.error('node_cleanup.failure_handler_failed', { + nodeId: node.id, + userId: node.user_id, + error: errorMessage(failureError), + originalError: errorMessage(error), + }); + } await recordSweepDecision(env, node, options, 'destroy_failed', errorMessage(error)); return 'failed'; } finally { diff --git a/apps/api/src/services/admin-setting-definitions.ts b/apps/api/src/services/admin-setting-definitions.ts index 3d51292a9b..e94d4b421c 100644 --- a/apps/api/src/services/admin-setting-definitions.ts +++ b/apps/api/src/services/admin-setting-definitions.ts @@ -1,3 +1,5 @@ +import type { DeploymentPublishJobSettingName } from '@simple-agent-manager/app-deployment'; + import type { Env } from '../env'; import { type GcpCatalogSettingName } from './admin-settings-gcp-catalog-definitions'; import type { NodeTunnelSettingName } from './admin-settings-node-tunnel-definitions'; @@ -21,13 +23,11 @@ export type AdminSettingValue = boolean | number | string | readonly string[] | export type AdminSettingType = 'boolean' | 'integer' | 'string' | 'string-list' | 'enum'; export type AdminSettingName = + | DeploymentPublishJobSettingName + | 'deployments.publishCallbackMaxBodyBytes' | 'chat.messageMergingEnabled' | 'chat.messageMergeMaxRowBytes' | 'chat.messageMergeRecentIds' - | 'deployments.buildContextCollectionMode' - | 'deployments.buildContextStartTimeoutMs' - | `deployments.buildContext${'MaxBytes' | 'CollectTimeoutMs' | 'UploadTtlSeconds' | 'RetentionHours' | 'CleanupBudgetMs' | 'CleanupPageSize'}` - | `deployments.publishJob${'StallMs' | 'DeadlineMs' | 'SweepLimit' | 'CancelTimeoutMs'}` | `workflow.${keyof typeof WORKFLOW_DEFAULTS}` | `lifecycleLatency.${LifecycleLatencySettingKey}` | `aiModels.${AgentModelSettingKey}` diff --git a/apps/api/src/services/admin-settings-deployment-publish-definitions.ts b/apps/api/src/services/admin-settings-deployment-publish-definitions.ts index 4c7794f2c4..e639110191 100644 --- a/apps/api/src/services/admin-settings-deployment-publish-definitions.ts +++ b/apps/api/src/services/admin-settings-deployment-publish-definitions.ts @@ -1,3 +1,5 @@ +import { DEFAULT_DEPLOY_BUILDER_RESERVATION_GRACE_MS } from '@simple-agent-manager/app-deployment'; + import { choiceDefinition, integerDefinition } from './admin-setting-definitions'; import { DEFAULT_BUILD_CONTEXT_CLEANUP_BUDGET_MS, @@ -18,6 +20,98 @@ import { } from './deployment-publish-job-defaults'; export const DEPLOYMENT_PUBLISH_SETTINGS = [ + integerDefinition( + 'deployments.publishCallbackMaxBodyBytes', + 1024 * 1024, + 'Operations', + 'Maximum actual JSON bytes for authenticated publish event, image artifact and release callbacks, for source and builder tokens.', + { min: 1024, max: 16 * 1024 * 1024 } + ), + integerDefinition( + 'deployments.builderCallbackTimeoutMs', + 30000, + 'Operations', + 'Builder control-plane HTTP timeout and bootstrap HTTP shutdown budget.', + { min: 1000, max: 120000 } + ), + integerDefinition( + 'deployments.builderCallbackAttempts', + 3, + 'Operations', + 'Maximum attempts for retryable builder callbacks.', + { min: 1, max: 10 } + ), + integerDefinition( + 'deployments.builderCallbackRetryDelayMs', + 5000, + 'Operations', + 'Delay between retryable builder callbacks.', + { min: 100, max: 30000 } + ), + integerDefinition( + 'deployments.builderDeadlineMs', + 20 * 60_000, + 'Operations', + 'Absolute builder deadline after first admission, also capped by the overall publish-job deadline.', + { min: 10000, max: 1200000 } + ), + integerDefinition( + 'deployments.builderReservationGraceMs', + DEFAULT_DEPLOY_BUILDER_RESERVATION_GRACE_MS, + 'Operations', + 'Grace after the immutable builder deadline before cron force-releases an unconfirmed reservation with an alert. Running jobs become unknown; physical stop may remain unconfirmed.', + { min: 1000, max: 3600000 } + ), + // Keep VM builds on node until staging proof in SAM idea 01M7H8GCR5FFDEXA70DNMEF8BW is complete. + choiceDefinition( + 'deployments.buildExecutor', + 'node', + ['node', 'cloudflare'], + 'Operations', + 'Build executor for VM sessions. Instant always uses Cloudflare; explicit Cloudflare selection never silently falls back to the source node.' + ), + integerDefinition( + 'deployments.builderMaxConcurrent', + 6, + 'Operations', + 'Platform Cloudflare build reservations, clamped to the deployed container class maximum.', + { min: 1, max: 6 } + ), + integerDefinition( + 'deployments.builderProjectMaxConcurrent', + 2, + 'Operations', + 'Concurrent Cloudflare builds per project.', + { min: 1, max: 2 } + ), + integerDefinition( + 'deployments.builderCapacityBackoffMs', + 30000, + 'Operations', + 'Minimum delay before retrying Cloudflare platform capacity errors.', + { min: 1000, max: 300000 } + ), + integerDefinition( + 'deployments.builderDrainLimit', + 6, + 'Operations', + 'Maximum queued builds considered per cron tick.', + { min: 1, max: 100 } + ), + integerDefinition( + 'deployments.builderDaemonReadyTimeoutMs', + 60000, + 'Operations', + 'DinD daemon readiness deadline.', + { min: 1000, max: 120000 } + ), + integerDefinition( + 'deployments.builderHeartbeatIntervalMs', + 15000, + 'Operations', + 'Cloudflare builder heartbeat interval.', + { min: 1000, max: 30000 } + ), choiceDefinition( 'deployments.buildContextCollectionMode', DEFAULT_BUILD_CONTEXT_COLLECTION_MODE, diff --git a/apps/api/src/services/build-context-upload.ts b/apps/api/src/services/build-context-upload.ts index 43606a319d..95c25805b1 100644 --- a/apps/api/src/services/build-context-upload.ts +++ b/apps/api/src/services/build-context-upload.ts @@ -1,5 +1,6 @@ // Canonical implementation lives in the app-deployment package. export { + createBuildContextDownload, createBuildContextUpload, verifyBuildContextObject, } from '@simple-agent-manager/app-deployment'; diff --git a/apps/api/src/services/cloudflare-build-executor.ts b/apps/api/src/services/cloudflare-build-executor.ts new file mode 100644 index 0000000000..3c63f83a10 --- /dev/null +++ b/apps/api/src/services/cloudflare-build-executor.ts @@ -0,0 +1,11 @@ +import { + dispatchCloudflareBuild as dispatch, + drainCloudflareBuilds as drain, +} from '@simple-agent-manager/app-deployment'; + +import { createCloudflareBuildPorts } from '../app-deployment-ports/cloudflare-builder'; +import type { Env } from '../env'; +export const dispatchCloudflareBuild = (env: Env, jobId: string) => + dispatch(env.DATABASE, createCloudflareBuildPorts(env), jobId); +export const drainCloudflareBuilds = (env: Env) => + drain(env.DATABASE, createCloudflareBuildPorts(env)); diff --git a/apps/api/src/services/jwt.ts b/apps/api/src/services/jwt.ts index 82ed85151a..d7c0ca66de 100644 --- a/apps/api/src/services/jwt.ts +++ b/apps/api/src/services/jwt.ts @@ -395,6 +395,45 @@ export async function verifyCallbackToken( }; } +/** Verify only publish-job claims. Callers must additionally bind these claims to + * the current non-terminal job row and attempt in publish-job-token.ts. Generic + * workspace/node callback sinks continue to reject the publish-job scope. */ +export async function verifyPublishJobClaims(env: Env, token: string) { + const key = await importSPKI(env.JWT_PUBLIC_KEY, 'RS256'); + let payload; + try { + ({ payload } = await jwtVerify(token, key, { + algorithms: ['RS256'], + issuer: `https://api.${env.BASE_DOMAIN}`, + audience: CALLBACK_AUDIENCE, + })); + } catch { + throw new AppError(401, 'UNAUTHORIZED', 'Invalid or expired publish job token'); + } + if ( + payload.scope !== 'publish-job' || + payload.type !== 'callback' || + typeof payload.jobId !== 'string' || + payload.sub !== payload.jobId || + typeof payload.projectId !== 'string' || + typeof payload.environmentId !== 'string' || + typeof payload.agentProfileId !== 'string' || + typeof payload.attempt !== 'number' || + !Number.isSafeInteger(payload.attempt) || + payload.attempt < 1 || + typeof payload.iat !== 'number' || + typeof payload.exp !== 'number' + ) + throw new AppError(401, 'UNAUTHORIZED', 'Invalid publish job claims'); + return { + jobId: payload.jobId, + projectId: payload.projectId, + environmentId: payload.environmentId, + agentProfileId: payload.agentProfileId, + attempt: payload.attempt, + }; +} + /** * Verify a browser-to-workspace terminal token. * diff --git a/apps/api/src/services/publish-job-token.ts b/apps/api/src/services/publish-job-token.ts new file mode 100644 index 0000000000..137ff185a4 --- /dev/null +++ b/apps/api/src/services/publish-job-token.ts @@ -0,0 +1,60 @@ +import { and, eq } from 'drizzle-orm'; +import { drizzle } from 'drizzle-orm/d1'; +import { importPKCS8, SignJWT } from 'jose'; + +import * as schema from '../db/schema'; +import type { Env } from '../env'; +import { errors } from '../middleware/error'; +import { PUBLISH_JOB_TERMINAL_STATUSES } from './deployment-publish-jobs'; +import { verifyPublishJobClaims } from './jwt'; + +const AUDIENCE = 'workspace-callback'; +export interface PublishJobClaims { + jobId: string; + projectId: string; + environmentId: string; + agentProfileId: string; + attempt: number; +} + +/** Deliberately separate from the generic callback verifier: all other callback + * sinks continue rejecting this scope, including credential/renewal routes. */ +export async function signPublishJobToken( + env: Env, + claims: PublishJobClaims, + deadline: number +): Promise { + if (deadline <= Date.now()) throw errors.conflict('Publish job deadline has elapsed'); + return new SignJWT({ ...claims, scope: 'publish-job', type: 'callback' }) + .setProtectedHeader({ alg: 'RS256' }) + .setIssuer(`https://api.${env.BASE_DOMAIN}`) + .setAudience(AUDIENCE) + .setSubject(claims.jobId) + .setIssuedAt() + .setExpirationTime(Math.floor(deadline / 1000)) + .sign(await importPKCS8(env.JWT_PRIVATE_KEY, 'RS256')); +} + +export async function verifyPublishJobToken(env: Env, token: string) { + const payload = await verifyPublishJobClaims(env, token); + const db = drizzle(env.DATABASE, { schema }); + const j = schema.deploymentPublishJobs; + const [job] = await db + .select() + .from(j) + .where( + and( + eq(j.id, payload.jobId), + eq(j.projectId, payload.projectId), + eq(j.environmentId, payload.environmentId), + eq(j.agentProfileId, payload.agentProfileId), + eq(j.attempt, payload.attempt), + eq(j.executor, 'cloudflare'), + eq(j.contextShadow, false) + ) + ) + .limit(1); + if (!job || PUBLISH_JOB_TERMINAL_STATUSES.has(job.status)) + throw errors.gone('Publish job is terminal, missing, or its attempt changed'); + return { db, job }; +} diff --git a/apps/api/tests/mocks/cloudflare-containers.ts b/apps/api/tests/mocks/cloudflare-containers.ts index 1fef825a9d..6e118f1976 100644 --- a/apps/api/tests/mocks/cloudflare-containers.ts +++ b/apps/api/tests/mocks/cloudflare-containers.ts @@ -39,3 +39,6 @@ export class Container { export function switchPort(request: Request): Request { return request; } + +// Worker entrypoint export required by the real SDK during reconstruction. +export class ContainerProxy {} diff --git a/apps/api/tests/unit/durable-objects/compose-builder-container.test.ts b/apps/api/tests/unit/durable-objects/compose-builder-container.test.ts new file mode 100644 index 0000000000..99353152ce --- /dev/null +++ b/apps/api/tests/unit/durable-objects/compose-builder-container.test.ts @@ -0,0 +1,490 @@ +import { + appendDeploymentPublishJobEvent, + failExpiredDeploymentPublishJobs, +} from '@simple-agent-manager/app-deployment'; +import Database from 'better-sqlite3'; +import { drizzle } from 'drizzle-orm/d1'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import * as schema from '../../../src/db/schema'; +import type { Env } from '../../../src/env'; +import { createSchemaTables, createSqliteD1 } from '../../helpers/sqlite-d1'; +const calls = vi.hoisted(() => ({ + schedule: vi.fn(), + deleteSchedules: vi.fn(), + waitUntil: vi.fn(), + running: false, + lifecycle: vi.fn(async () => {}), + destroy: vi.fn(), + start: vi.fn(), + fetch: vi.fn(), +})); +vi.mock('../../../src/services/project-lifecycle-events', () => ({ + recordDeploymentPublishJobLifecycleEventBestEffort: calls.lifecycle, +})); +vi.mock('@cloudflare/containers', () => ({ + Container: class { + ctx: unknown; + env: unknown; + envVars = {}; + constructor(ctx: unknown, env: unknown) { + this.ctx = ctx; + this.env = env; + } + schedule(...args: unknown[]) { + return calls.schedule(...args); + } + async destroy() { + await calls.destroy(); + calls.running = false; + } + deleteSchedules(name: string) { + calls.deleteSchedules(name); + } + async startAndWaitForPorts(...args: unknown[]) { + await calls.start(...args); + calls.running = true; + } + containerFetch(...args: unknown[]) { + return calls.fetch(...args); + } + async getState() { + return { status: 'healthy' }; + } + }, +})); +vi.mock('../../../src/services/admin-settings', () => ({ resolveAdminSetting: async () => 30000 })); +vi.mock('../../../src/services/publish-job-token', () => ({ + signPublishJobToken: vi.fn(async () => 'single-job-token'), +})); +const { ComposeBuilderContainer } = + await import('../../../src/durable-objects/compose-builder-container'); +let sqlite: Database.Database; +let env: Env; +let stored: Map; +let builder: InstanceType; +beforeEach(() => { + vi.clearAllMocks(); + calls.running = false; + sqlite = new Database(':memory:'); + createSchemaTables(sqlite, [schema.deploymentPublishJobs, schema.deploymentPublishJobEvents]); + const deadline = new Date(Date.now() + 60_000).toISOString(); + sqlite + .prepare( + `INSERT INTO deployment_publish_jobs(id,project_id,environment_id,workspace_id,node_id,requested_by,environment_name,status,executor,context_shadow,attempt,agent_profile_id,executor_instance_id,executor_deadline_at) VALUES('job','project','env','ws','node','user','staging','starting','cloudflare',0,1,'profile','job',?)` + ) + .run(deadline); + env = { + DATABASE: createSqliteD1(sqlite), + BASE_DOMAIN: 'example.test', + CF_ACCOUNT_ID: 'account', + VM_AGENT_REQUIRED_VERSION: 'version', + } as Env; + stored = new Map(); + const ctx = { + container: { + getTcpPort: () => ({ fetch: calls.fetch }), + get running() { + return calls.running; + }, + }, + waitUntil: calls.waitUntil, + storage: { + kv: { + get: (key: string) => stored.get(key), + put: (key: string, value: unknown) => stored.set(key, value), + }, + deleteAlarm: vi.fn(async () => {}), + get: async (key: string) => stored.get(key), + put: async (key: string, value: unknown) => { + stored.set(key, value); + }, + }, + }; + builder = new ComposeBuilderContainer(ctx as unknown as DurableObjectState, env); + calls.schedule.mockResolvedValue({}); + calls.destroy.mockResolvedValue(undefined); + calls.start.mockResolvedValue(undefined); + calls.fetch.mockImplementation(async (url: string) => + url.endsWith('/health') + ? Response.json({ version: 'version' }) + : new Response(null, { status: 202 }) + ); +}); +afterEach(() => sqlite.close()); +async function launch() { + await builder.startJob('job', 1); + await builder.runBuilder({ jobId: 'job', attempt: 1 }); +} +describe('per-job builder lifecycle adapter', () => { + it('launches after a controlled late collector callback without undoing admission', async () => { + // The row is already atomically admitted by the fixture. Deliver the old + // source event before the durable kickoff runs, matching the staging race. + expect( + await appendDeploymentPublishJobEvent(drizzle(env.DATABASE, { schema }), { + publishJobId: 'job', + projectId: 'project', + environmentId: 'env', + workspaceId: 'ws', + nodeId: 'node', + eventType: 'publish.context.collected', + message: 'context collected', + status: 'context_ready', + currentStep: 'context_ready', + }) + ).toBe(false); + expect( + sqlite.prepare('SELECT status,current_step FROM deployment_publish_jobs').get() + ).toMatchObject({ status: 'starting' }); + await launch(); + expect(calls.start).toHaveBeenCalledTimes(1); + expect(calls.fetch).toHaveBeenCalledTimes(2); + }); + it('recovers a reserved context_ready row once without repeating an accepted launch', async () => { + sqlite.exec( + "UPDATE deployment_publish_jobs SET status='context_ready',current_step='context_ready'" + ); + await launch(); + await launch(); + expect(calls.start).toHaveBeenCalledTimes(1); + expect( + sqlite.prepare('SELECT status,executor_instance_id FROM deployment_publish_jobs').get() + ).toEqual({ status: 'starting', executor_instance_id: 'job' }); + }); + + it('repairs a regression after acceptance without touching or relaunching the guest', async () => { + await launch(); + const deadline = sqlite + .prepare('SELECT executor_deadline_at FROM deployment_publish_jobs') + .get(); + sqlite.exec( + "UPDATE deployment_publish_jobs SET status='context_ready',current_step='context_ready'" + ); + sqlite.exec("UPDATE deployment_publish_jobs SET last_heartbeat_at='2000-01-01T00:00:00.000Z'"); + await builder.startJob('job', 1); // cron recovery enters through this method + expect( + await failExpiredDeploymentPublishJobs(drizzle(env.DATABASE, { schema }), { + stallMs: 60000, + deadlineMs: 1800000, + sweepLimit: 6, + }) + ).toEqual([]); + expect( + sqlite.prepare('SELECT status,executor_instance_id FROM deployment_publish_jobs').get() + ).toEqual({ status: 'starting', executor_instance_id: 'job' }); + expect( + sqlite.prepare('SELECT executor_deadline_at FROM deployment_publish_jobs').get() + ).toEqual(deadline); + expect(calls.start).toHaveBeenCalledTimes(1); + expect(calls.fetch).toHaveBeenCalledTimes(2); + }); + it('arms the persisted deadline before startup and sends no credentials through env', async () => { + await launch(); + expect(calls.schedule.mock.invocationCallOrder[0]).toBeLessThan( + calls.start.mock.invocationCallOrder[0]! + ); + const envelope = JSON.parse(calls.fetch.mock.calls[1]?.[1].body); + expect(envelope).toMatchObject({ jobId: 'job', attempt: 1, token: 'single-job-token' }); + expect((builder as unknown as { envVars: unknown }).envVars).toEqual({ + SAM_BUILDER_BOOTSTRAP_TIMEOUT_MS: '30000', + SAM_BUILDER_CONTROL_TIMEOUT_MS: '30000', + }); + await launch(); + expect(calls.start).toHaveBeenCalledTimes(1); + }); + it('rejects a stale attempt or version before sending the token', async () => { + await expect(builder.startJob('job', 2)).rejects.toThrow(); + expect(calls.start).not.toHaveBeenCalled(); + calls.fetch.mockResolvedValueOnce(Response.json({ version: 'stale' })); + await launch(); + expect(sqlite.prepare('SELECT status FROM deployment_publish_jobs').get()).toEqual({ + status: 'failed', + }); + expect(calls.fetch).toHaveBeenCalledTimes(1); + }); + it('rechecks durable cancellation after startup awaits', async () => { + calls.start.mockImplementationOnce(async () => { + sqlite.exec("UPDATE deployment_publish_jobs SET status='canceled'"); + }); + await launch(); + expect(sqlite.prepare('SELECT status FROM deployment_publish_jobs').get()).toEqual({ + status: 'canceled', + }); + expect(calls.fetch).toHaveBeenCalledTimes(1); + }); + it('hard deadline stops before publishing its verdict and frees capacity', async () => { + await launch(); + await builder.enforceDeadline(); + expect(calls.destroy).toHaveBeenCalled(); + expect(calls.lifecycle).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + status: 'failed', + terminal: true, + source: 'cloudflare_builder.deadline', + }) + ); + expect( + sqlite + .prepare('SELECT status,error_code,executor_instance_id FROM deployment_publish_jobs') + .get() + ).toEqual({ status: 'failed', error_code: 'deadline_exceeded', executor_instance_id: null }); + }); + it('stops orphan containers when source-node deletion cascades away their job', async () => { + await launch(); + sqlite.exec("DELETE FROM deployment_publish_jobs WHERE id='job'"); + await builder.enforceDeadline(); + expect(calls.destroy).toHaveBeenCalledTimes(1); + }); + it('unexpected process exit produces a durable failure; terminal success survives cleanup', async () => { + await launch(); + calls.running = false; + await builder.onStop(); + expect(sqlite.prepare('SELECT status FROM deployment_publish_jobs').get()).toEqual({ + status: 'failed', + }); + sqlite.exec( + "UPDATE deployment_publish_jobs SET status='succeeded', executor_instance_id='job'" + ); + await builder.onStop(); + expect( + sqlite.prepare('SELECT status,executor_instance_id FROM deployment_publish_jobs').get() + ).toEqual({ status: 'succeeded', executor_instance_id: null }); + }); +}); + +it('persists kickoff before returning without starting a container in the HTTP waiter', async () => { + await builder.startJob('job', 1); + expect(calls.start).not.toHaveBeenCalled(); + expect(calls.schedule).toHaveBeenCalledWith(expect.any(Date), 'launchBuilder', { + jobId: 'job', + attempt: 1, + notBefore: null, + }); + expect(stored.get('buildJob')).toMatchObject({ jobId: 'job', attempt: 1 }); + await builder.runBuilder({ jobId: 'job', attempt: 1 }); + expect(calls.start).toHaveBeenCalledTimes(1); +}); + +it('ignores duplicate and stale capacity alarms without defeating backoff', async () => { + await builder.startJob('job', 1); + calls.start.mockRejectedValueOnce(new Error('Maximum number of running containers')); + await Promise.all([ + builder.runBuilder({ jobId: 'job', attempt: 1 }), + builder.runBuilder({ jobId: 'job', attempt: 1 }), + ]); + await builder.runBuilder({ jobId: 'job', attempt: 1 }); + expect(calls.start).toHaveBeenCalledTimes(1); + expect( + sqlite + .prepare( + 'SELECT status,executor_instance_id,executor_not_before FROM deployment_publish_jobs' + ) + .get() + ).toEqual({ + status: 'context_ready', + executor_instance_id: null, + executor_not_before: expect.any(String), + }); +}); +it('destroys on deadline even when D1 is unavailable', async () => { + await launch(); + env.DATABASE = { + prepare: () => { + throw new Error('D1 unavailable'); + }, + } as unknown as D1Database; + await expect(builder.enforceDeadline()).rejects.toThrow(); + expect(calls.destroy).toHaveBeenCalledTimes(1); +}); + +it('re-arms deadline destruction after a transient container failure', async () => { + await launch(); + calls.destroy.mockRejectedValueOnce(new Error('temporary stop unavailable')); + const before = calls.schedule.mock.calls.length; + await expect(builder.enforceDeadline()).rejects.toThrow('temporary stop unavailable'); + expect(calls.schedule.mock.calls.slice(before)).toEqual([[expect.any(Date), 'enforceDeadline']]); + await builder.enforceDeadline(); + expect(calls.destroy).toHaveBeenCalledTimes(2); + expect( + sqlite.prepare('SELECT status,executor_instance_id FROM deployment_publish_jobs').get() + ).toEqual({ status: 'failed', executor_instance_id: null }); +}); + +it('never contacts the bootstrap port after acceptance, even if RUN binds it', async () => { + await launch(); + expect(calls.fetch).toHaveBeenCalledTimes(2); // version probe, then the single launch + calls.fetch.mockImplementation(() => { + throw new Error('untrusted RUN now owns the former bootstrap port'); + }); + await builder.startJob('job', 1); + await builder.runBuilder({ jobId: 'job', attempt: 1 }); + await builder.enforceDeadline(); + await builder.onStop(); + expect(calls.fetch).toHaveBeenCalledTimes(2); + expect(calls.destroy).toHaveBeenCalled(); +}); + +it.each(['succeeded', 'missing'])( + 'old deadline never touches an inactive %s guest', + async (status) => { + await launch(); + calls.running = false; + if (status === 'missing') sqlite.exec('DELETE FROM deployment_publish_jobs'); + else + sqlite.exec( + "UPDATE deployment_publish_jobs SET status='succeeded',executor_instance_id=NULL" + ); + calls.destroy.mockClear(); + calls.start.mockClear(); + calls.fetch.mockClear(); + await builder.enforceDeadline(); + expect(calls.destroy).not.toHaveBeenCalled(); + expect(calls.start).not.toHaveBeenCalled(); + expect(calls.fetch).not.toHaveBeenCalled(); + expect(calls.deleteSchedules).toHaveBeenCalledWith('enforceDeadline'); + expect(calls.deleteSchedules).toHaveBeenCalledWith('launchBuilder'); + } +); +it('a never-settling acceptance diagnostic cannot block kickoff or deadline destruction', async () => { + const actual = env.DATABASE.batch.bind(env.DATABASE); + let entered!: () => void; + const pending = new Promise((resolve) => { + entered = resolve; + }); + let first = true; + env.DATABASE.batch = (async (statements) => { + if (first) { + first = false; + entered(); + return new Promise(() => {}); + } + return actual(statements); + }) as D1Database['batch']; + const launched = launch(); + await pending; + expect( + await Promise.race([ + launched.then(() => true), + new Promise((resolve) => setTimeout(() => resolve(false), 100)), + ]) + ).toBe(true); + await builder.enforceDeadline(); + expect(calls.destroy).toHaveBeenCalledTimes(1); +}); + +it('legacy persisted kickoff callback releases the sequential SDK alarm immediately', async () => { + const prepare = env.DATABASE.prepare.bind(env.DATABASE); + env.DATABASE.prepare = ((sql) => { + const statement = prepare(sql); + return { + ...statement, + bind: (...args: unknown[]) => ({ + ...statement.bind(...args), + raw: () => new Promise(() => {}), + }), + }; + }) as D1Database['prepare']; + expect(builder.launchBuilder({ jobId: 'job', attempt: 1 })).toBeUndefined(); + expect(calls.waitUntil).toHaveBeenCalledWith(expect.any(Promise)); + expect(calls.start).not.toHaveBeenCalled(); +}); +it('a previous SDK stop notification during retry startup cannot revoke its new deadline or job', async () => { + calls.start.mockImplementationOnce(async () => { + await builder.onStop(); + }); + await launch(); + expect( + sqlite.prepare('SELECT status,executor_instance_id FROM deployment_publish_jobs').get() + ).toEqual({ status: 'starting', executor_instance_id: 'job' }); + expect(calls.fetch).toHaveBeenCalledTimes(2); + expect(calls.deleteSchedules).not.toHaveBeenCalled(); + expect(calls.schedule).toHaveBeenCalledWith(expect.any(Date), 'enforceDeadline'); +}); + +it('destroys SDK startup that resumes after deadline abort without depending on D1', async () => { + let resume!: () => void, entered!: () => void; + const blocked = new Promise((resolve) => { + resume = resolve; + }); + const starting = new Promise((resolve) => { + entered = resolve; + }); + calls.start.mockImplementationOnce(async () => { + entered(); + await blocked; + }); + const launched = launch(); + await starting; + env.DATABASE = { + prepare: () => { + throw new Error('D1 unavailable'); + }, + } as unknown as D1Database; + await expect(builder.enforceDeadline()).resolves.toBeUndefined(); + expect(calls.schedule).toHaveBeenCalledWith(expect.any(Date), 'enforceDeadline'); + resume(); + await launched.catch(() => undefined); + expect(calls.destroy).toHaveBeenCalledTimes(1); + expect(calls.running).toBe(false); + expect(calls.fetch).not.toHaveBeenCalled(); +}); + +it('inactive terminal cleanup releases its reservation without waking compute', async () => { + await launch(); + calls.running = false; + sqlite.exec("UPDATE deployment_publish_jobs SET status='succeeded'"); + calls.destroy.mockClear(); + await builder.enforceDeadline(); + expect(calls.destroy).not.toHaveBeenCalled(); + expect(sqlite.prepare('SELECT executor_instance_id FROM deployment_publish_jobs').get()).toEqual({ + executor_instance_id: null, + }); +}); + +it('stale capacity stop neither aborts nor destroys a readmitted reservation', async () => { + await launch(); + const signal = calls.start.mock.calls[0]![0].cancellationOptions.abort as AbortSignal; + sqlite.exec("UPDATE deployment_publish_jobs SET executor_not_before='2099-01-01T00:00:00.000Z'"); + await builder.stopJob({ jobId: 'job', attempt: 1, notBefore: null, retryAt: Date.now() + 30000 }); + expect(signal.aborted).toBe(false); + expect(calls.destroy).not.toHaveBeenCalled(); + expect( + sqlite + .prepare( + 'SELECT status,executor_instance_id,executor_not_before FROM deployment_publish_jobs' + ) + .get() + ).toEqual({ + status: 'starting', + executor_instance_id: 'job', + executor_not_before: '2099-01-01T00:00:00.000Z', + }); +}); + +it('capacity cleanup and readmission rotate the epoch without reusing acceptance state', async () => { + calls.start.mockImplementationOnce(async () => { + calls.running = true; + throw new Error('Maximum number of running containers'); + }); + await launch(); + expect(calls.destroy).toHaveBeenCalledTimes(1); + const queued = sqlite + .prepare('SELECT executor_not_before,executor_deadline_at FROM deployment_publish_jobs') + .get() as { executor_not_before: string; executor_deadline_at: string }; + expect(queued.executor_not_before).toEqual(expect.any(String)); + sqlite.exec("UPDATE deployment_publish_jobs SET status='starting',executor_instance_id='job'"); + await expect(builder.startJob('job', 1, null)).rejects.toThrow('reservation changed'); + await builder.startJob('job', 1, queued.executor_not_before); + await builder.runBuilder({ jobId: 'job', attempt: 1, notBefore: queued.executor_not_before }); + const signal = calls.start.mock.calls[1]![0].cancellationOptions.abort as AbortSignal; + await builder.stopJob({ jobId: 'job', attempt: 1, notBefore: null, retryAt: Date.now() + 60000 }); + await builder.runBuilder({ jobId: 'job', attempt: 1 }); + expect(signal.aborted).toBe(false); + expect(calls.destroy).toHaveBeenCalledTimes(1); + expect(calls.start).toHaveBeenCalledTimes(2); + expect(calls.fetch).toHaveBeenCalledTimes(2); + expect(sqlite.prepare('SELECT executor_deadline_at FROM deployment_publish_jobs').get()).toEqual({ + executor_deadline_at: queued.executor_deadline_at, + }); +}); diff --git a/apps/api/tests/unit/durable-objects/compose-builder-sdk-alarm.test.ts b/apps/api/tests/unit/durable-objects/compose-builder-sdk-alarm.test.ts new file mode 100644 index 0000000000..c52ba4827f --- /dev/null +++ b/apps/api/tests/unit/durable-objects/compose-builder-sdk-alarm.test.ts @@ -0,0 +1,351 @@ +import { admitCloudflareBuild } from '@simple-agent-manager/app-deployment'; +import Database from 'better-sqlite3'; +import { drizzle } from 'drizzle-orm/d1'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import * as schema from '../../../src/db/schema'; +import type { Env } from '../../../src/env'; +import { createSchemaTables, createSqliteD1 } from '../../helpers/sqlite-d1'; + +// Exercise the installed constructor, SQL scheduler and alarm implementation. +// Only the native workerd container/storage boundaries are simulated. +vi.mock( + '@cloudflare/containers', + async () => import('../../../node_modules/@cloudflare/containers/dist/lib/container.js') +); +vi.mock('../../../src/services/admin-settings', () => ({ + resolveAdminSetting: async () => 30000, +})); +vi.mock('../../../src/services/project-lifecycle-events', () => ({ + recordDeploymentPublishJobLifecycleEventBestEffort: async () => undefined, +})); +const { Container } = await import('@cloudflare/containers'); +const { ComposeBuilderContainer } = + await import('../../../src/durable-objects/compose-builder-container'); + +let sql: Database.Database; +let database: D1Database; +let env: Env; +let values: Map; +let nativeAlarm: number | null; +let running: boolean; +let boot: Promise[]; +let builder: InstanceType; +let ctx: DurableObjectState; +const native = { + start: vi.fn(), + destroy: vi.fn(), + monitor: vi.fn(), + fetch: vi.fn(), + setAlarm: vi.fn(), + deleteAlarm: vi.fn(), +}; + +async function settleConstructor() { + while (boot.length) await Promise.all(boot.splice(0)); +} +function schedules() { + return sql.prepare('SELECT callback FROM container_schedules ORDER BY callback').all(); +} +async function armOriginalDeadline() { + await builder.schedule(new Date(Date.now() + 60000), 'enforceDeadline'); + expect(nativeAlarm).not.toBeNull(); + expect(schedules()).toEqual([{ callback: 'enforceDeadline' }]); +} +function assertNoGuestOperations() { + expect(native.start).not.toHaveBeenCalled(); + expect(native.destroy).not.toHaveBeenCalled(); + expect(native.monitor).not.toHaveBeenCalled(); + expect(native.fetch).not.toHaveBeenCalled(); +} +beforeEach(async () => { + vi.clearAllMocks(); + sql = new Database(':memory:'); + createSchemaTables(sql, [schema.deploymentPublishJobs, schema.deploymentPublishJobEvents]); + const now = new Date().toISOString(); + sql + .prepare( + `INSERT INTO deployment_publish_jobs + (id,project_id,environment_id,workspace_id,node_id,requested_by,environment_name, + executor,context_shadow,status,current_step,attempt,agent_profile_id, + executor_instance_id,executor_deadline_at,context_r2_key,context_sha256,created_at,updated_at) + VALUES ('job','project','env','ws','node','user','staging','cloudflare',0, + 'succeeded','complete',1,'profile',NULL,?,'context','digest',?,?)` + ) + .run(new Date(Date.now() + 60000).toISOString(), now, now); + database = createSqliteD1(sql); + env = { DATABASE: database, BASE_DOMAIN: 'example.test' } as Env; + values = new Map([ + [ + 'buildJob', + { + jobId: 'job', + attempt: 1, + deadline: Date.now() + 60000, + stopRetryMs: 30000, + accepted: true, + reservationEpoch: null, + }, + ], + ['__CF_CONTAINER_STATE', { status: 'stopped', lastChange: Date.now() }], + ]); + nativeAlarm = null; + running = false; + boot = []; + native.setAlarm.mockImplementation(async (at: number | Date) => { + nativeAlarm = Number(at); + }); + native.deleteAlarm.mockImplementation(async () => { + nativeAlarm = null; + }); + native.destroy.mockImplementation(async () => { + running = false; + }); + native.monitor.mockImplementation(() => new Promise(() => {})); + ctx = { + id: { toString: () => 'builder-job' }, + exports: { ContainerProxy: () => ({ fetch: vi.fn() }) }, + blockConcurrencyWhile: (fn: () => Promise) => { + const promise = fn(); + boot.push(promise); + return promise; + }, + waitUntil: () => undefined, + container: { + get running() { + return running; + }, + start: native.start, + destroy: native.destroy, + monitor: native.monitor, + getTcpPort: () => ({ fetch: native.fetch }), + }, + storage: { + get: async (key: string) => values.get(key), + put: async (key: string, value: unknown) => { + values.set(key, value); + }, + kv: { + get: (key: string) => values.get(key), + put: (key: string, value: unknown) => { + values.set(key, value); + }, + }, + sql: { + exec: (query: string, ...bindings: unknown[]) => { + const statement = sql.prepare(query); + return statement.reader ? statement.all(...bindings) : (statement.run(...bindings), []); + }, + }, + setAlarm: native.setAlarm, + getAlarm: async () => nativeAlarm, + deleteAlarm: native.deleteAlarm, + sync: async () => undefined, + }, + } as unknown as DurableObjectState; + builder = new ComposeBuilderContainer(ctx, env); + await settleConstructor(); + await armOriginalDeadline(); + vi.clearAllMocks(); +}); +afterEach(() => { + vi.restoreAllMocks(); + sql.close(); +}); + +describe('installed SDK terminal builder alarm lifecycle', () => { + it('natural terminal stop removes the deadline and native alarm before a D1 outage', async () => { + env.DATABASE = { + prepare: () => { + throw new Error('D1 unavailable'); + }, + } as unknown as D1Database; + await expect(builder.onStop()).rejects.toThrow('D1 unavailable'); + expect(schedules()).toEqual([]); + expect(nativeAlarm).toBeNull(); + assertNoGuestOperations(); + }); + + it('explicit terminal stop clears the native alarm as well as SDK schedules', async () => { + await builder.stopJob(); + expect(schedules()).toEqual([]); + expect(nativeAlarm).toBeNull(); + assertNoGuestOperations(); + }); + + it('reconstruction of a stopped terminal builder neither rearms nor renews activity', async () => { + await builder.onStop(); + vi.clearAllMocks(); + const renew = vi.spyOn(Container.prototype, 'renewActivityTimeout'); + builder = new ComposeBuilderContainer(ctx, env); + await settleConstructor(); + expect(native.setAlarm).not.toHaveBeenCalled(); + expect(renew).not.toHaveBeenCalled(); + expect(nativeAlarm).toBeNull(); + assertNoGuestOperations(); + }); + + it('a delivered terminal alarm returns before entering the installed SDK alarm', async () => { + await builder.onStop(); + vi.clearAllMocks(); + const baseAlarm = vi.spyOn(Container.prototype, 'alarm'); + await builder.alarm(); + expect(baseAlarm).not.toHaveBeenCalled(); + expect(native.setAlarm).not.toHaveBeenCalled(); + expect(nativeAlarm).toBeNull(); + assertNoGuestOperations(); + }); + + it('natural stop inside the SDK alarm cannot rearm its stale pre-stop schedule snapshot', async () => { + // The SDK snapshots future schedules before synchronizing the previous + // process exit. onStop then removes them, but the SDK still holds that + // snapshot and would otherwise rearm the original native deadline. + values.set('__CF_CONTAINER_STATE', { status: 'healthy', lastChange: Date.now() }); + builder = new ComposeBuilderContainer(ctx, env); + await settleConstructor(); + vi.clearAllMocks(); + const baseAlarm = vi.spyOn(Container.prototype, 'alarm'); + await builder.alarm(); + expect(baseAlarm).toHaveBeenCalledTimes(1); + expect(schedules()).toEqual([]); + expect(nativeAlarm).toBeNull(); + assertNoGuestOperations(); + }); + + it('SDK scheduling that finishes storage.sync after quiescence cannot restore a native alarm', async () => { + let resume!: () => void; + let entered!: () => void; + const blocked = new Promise((resolve) => { + resume = resolve; + }); + const syncing = new Promise((resolve) => { + entered = resolve; + }); + vi.spyOn(ctx.storage, 'sync').mockImplementationOnce(async () => { + entered(); + await blocked; + }); + const scheduling = builder.scheduleNextAlarm(); + await syncing; + await builder.onStop(); + expect(await ctx.storage.getAlarm()).toBeNull(); + resume(); + await scheduling; + expect(await ctx.storage.getAlarm()).toBeNull(); + expect(schedules()).toEqual([]); + assertNoGuestOperations(); + }); + + it('a previous stop notification cannot erase or fail a newly admitted reservation epoch', async () => { + sql.exec("UPDATE deployment_publish_jobs SET status='starting',executor_instance_id='job'"); + values.set('buildJob', { + jobId: 'job', + attempt: 1, + deadline: Date.now() + 60000, + stopRetryMs: 30000, + accepted: false, + reservationEpoch: null, + }); + let resume!: () => void; + let entered!: () => void; + const blocked = new Promise((resolve) => { + resume = resolve; + }); + const reading = new Promise((resolve) => { + entered = resolve; + }); + const prepare = database.prepare.bind(database); + vi.spyOn(database, 'prepare').mockImplementationOnce((query) => { + const statement = prepare(query); + return { + ...statement, + bind: (...args: unknown[]) => { + const bound = statement.bind(...args); + return { + ...bound, + raw: async () => { + const captured = await bound.raw(); + entered(); + await blocked; + return captured; + }, + }; + }, + } as D1PreparedStatement; + }); + const oldStop = builder.onStop(); + await reading; + await builder.stopJob({ + jobId: 'job', + attempt: 1, + notBefore: null, + retryAt: Date.now() - 1000, + }); + const admitted = await admitCloudflareBuild(drizzle(database, { schema }), 'job', { + platform: 6, + project: 2, + classMax: 6, + deadlineMs: 1800000, + }); + expect(admitted).toBeTruthy(); + await builder.startJob('job', 1, admitted!.executorNotBefore); + resume(); + await oldStop; + expect(values.get('buildJob')).toMatchObject({ + reservationEpoch: admitted!.executorNotBefore, + quiescent: false, + }); + expect( + sql.prepare('SELECT status,executor_instance_id FROM deployment_publish_jobs').get() + ).toEqual({ status: 'starting', executor_instance_id: 'job' }); + expect(schedules()).toEqual([{ callback: 'enforceDeadline' }, { callback: 'launchBuilder' }]); + expect(await ctx.storage.getAlarm()).not.toBeNull(); + assertNoGuestOperations(); + }); + + it('an active deadline still destroys before an unavailable D1 verdict', async () => { + running = true; + sql.exec("UPDATE deployment_publish_jobs SET status='building',executor_instance_id='job'"); + env.DATABASE = { + prepare: () => { + throw new Error('D1 unavailable'); + }, + } as unknown as D1Database; + await expect(builder.enforceDeadline()).rejects.toThrow('D1 unavailable'); + expect(native.destroy).toHaveBeenCalledTimes(1); + expect(running).toBe(false); + expect(nativeAlarm).toBeNull(); + expect(native.start).not.toHaveBeenCalled(); + }); + + it('capacity cleanup can be followed by a fresh admitted epoch and real SDK schedules', async () => { + sql.exec("UPDATE deployment_publish_jobs SET status='starting',executor_instance_id='job'"); + values.set('buildJob', { + jobId: 'job', + attempt: 1, + deadline: Date.now() + 60000, + stopRetryMs: 30000, + accepted: false, + reservationEpoch: null, + }); + await builder.stopJob({ + jobId: 'job', + attempt: 1, + notBefore: null, + retryAt: Date.now() - 1000, + }); + const admitted = await admitCloudflareBuild(drizzle(database, { schema }), 'job', { + platform: 6, + project: 2, + classMax: 6, + deadlineMs: 1800000, + }); + expect(admitted).toBeTruthy(); + vi.clearAllMocks(); + await builder.startJob('job', 1, admitted!.executorNotBefore); + expect(schedules()).toEqual([{ callback: 'enforceDeadline' }, { callback: 'launchBuilder' }]); + expect(native.setAlarm).toHaveBeenCalled(); + expect(nativeAlarm).not.toBeNull(); + assertNoGuestOperations(); + }); +}); diff --git a/apps/api/tests/unit/durable-objects/container-sdk-direct-egress.test.ts b/apps/api/tests/unit/durable-objects/container-sdk-direct-egress.test.ts new file mode 100644 index 0000000000..a8ec80ba5b --- /dev/null +++ b/apps/api/tests/unit/durable-objects/container-sdk-direct-egress.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it, vi } from 'vitest'; + +// Bypass the API suite's lightweight Container alias to exercise the installed +// SDK's reconstruction path. cloudflare:workers still uses the Node test seam. +import { Container } from '../../../node_modules/@cloudflare/containers/dist/lib/container.js'; + +describe('installed Container SDK direct egress after reconstruction', () => { + it('reconstructs a running guest without registering any outbound interceptors', async () => { + const persisted = new Map(); + const interceptHttp = vi.fn(); + const interceptHttps = vi.fn(); + const interceptAll = vi.fn(); + const proxy = vi.fn(() => ({ fetch: vi.fn() })); + const boot: Promise[] = []; + const ctx = { + id: { toString: () => 'builder-job' }, + exports: { ContainerProxy: proxy }, + blockConcurrencyWhile: (fn: () => Promise) => boot.push(fn()), + storage: { + sql: { exec: () => [] }, + kv: { + get: (key: string) => persisted.get(key), + put: (key: string, value: unknown) => persisted.set(key, value), + }, + setAlarm: vi.fn(async () => {}), + sync: vi.fn(async () => {}), + }, + container: { + running: true, + monitor: () => new Promise(() => {}), + interceptOutboundHttp: interceptHttp, + interceptOutboundHttps: interceptHttps, + interceptAllOutboundHttp: interceptAll, + }, + }; + // Reconstruct twice, including the empty configuration persisted by the SDK. + for (let i = 0; i < 2; i++) { + const instance = new Container(ctx as unknown as DurableObjectState, {}); + await Promise.all(boot.splice(0)); + await (instance as unknown as { applyOutboundInterceptionPromise: Promise }) + .applyOutboundInterceptionPromise; + expect(instance.enableInternet).toBe(true); + } + expect(proxy).toHaveBeenCalledTimes(2); + expect(interceptHttp).not.toHaveBeenCalled(); + expect(interceptHttps).not.toHaveBeenCalled(); + expect(interceptAll).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/api/tests/unit/mcp-build-and-publish.test.ts b/apps/api/tests/unit/mcp-build-and-publish.test.ts index c6c90d5f3e..ddbd62a794 100644 --- a/apps/api/tests/unit/mcp-build-and-publish.test.ts +++ b/apps/api/tests/unit/mcp-build-and-publish.test.ts @@ -17,6 +17,16 @@ const recordDeploymentPublishJobLifecycleEventBestEffort = vi.hoisted(() => vi.fn(async () => undefined) ); +const { collectContext, executorSetting } = vi.hoisted(() => ({ + collectContext: vi.fn(async () => ({ supported: true })), + executorSetting: vi.fn(async () => 'node'), +})); +vi.mock('../../src/services/build-context-collection', () => ({ + collectBuildContextOnSource: collectContext, + createBuildContextCollectionPorts: vi.fn(() => ({})), +})); +vi.mock('../../src/services/admin-settings', () => ({ resolveAdminSetting: executorSetting })); + vi.mock('drizzle-orm/d1', () => ({ drizzle: vi.fn(() => ({ mockedDb: true, @@ -83,6 +93,8 @@ describe('async build_and_publish MCP tools', () => { beforeEach(() => { vi.clearAllMocks(); nodeRuntime = 'vm'; + executorSetting.mockResolvedValue('node'); + collectContext.mockResolvedValue({ supported: true }); currentStatus = 'building'; mockAppendDeploymentPublishJobEvent.mockResolvedValue(true); mockAssertAgentDeploymentAllowed.mockResolvedValue({ @@ -134,18 +146,74 @@ describe('async build_and_publish MCP tools', () => { } ); - it('rejects Instant sessions before creating or starting a job', async () => { + it('collects an Instant context independently of the VM default', async () => { nodeRuntime = 'cf-container'; - const result = await handleBuildAndPublish( - 'instant', - { environment: 'staging' }, - tokenData(), - env() - ); - expect(result.error?.message).toContain( - "Deploying from Instant sessions isn't available yet; use a VM session" + const result = await handleBuildAndPublish(1, { environment: 'staging' }, tokenData(), env()); + expect(JSON.parse(result.result?.content?.[0]?.text as string)).toMatchObject({ + executor: 'cloudflare', + publishJobId: 'job-1', + }); + expect(mockCreateDeploymentPublishJob).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ executor: 'cloudflare' }) ); + expect(collectContext).toHaveBeenCalled(); + expect(mockStartBuildPublishJobOnVm).not.toHaveBeenCalled(); + }); + it('uses explicit Cloudflare selection for a VM without starting a source build', async () => { + executorSetting.mockResolvedValue('cloudflare'); + const result = await handleBuildAndPublish(1, { environment: 'staging' }, tokenData(), env()); + expect(JSON.parse(result.result?.content?.[0]?.text as string).executor).toBe('cloudflare'); + expect(collectContext).toHaveBeenCalled(); + expect(mockStartBuildPublishJobOnVm).not.toHaveBeenCalled(); + }); + it('rejects profile-less Cloudflare requests before queuing but retains the node path', async () => { + mockAssertAgentDeploymentAllowed.mockResolvedValue({ + environmentId: 'env-1', + taskAgentProfileId: null, + }); + executorSetting.mockResolvedValue('cloudflare'); + const rejected = await handleBuildAndPublish(1, { environment: 'staging' }, tokenData(), env()); + expect(rejected.error?.message).toContain('agent profile'); expect(mockCreateDeploymentPublishJob).not.toHaveBeenCalled(); + expect(collectContext).not.toHaveBeenCalled(); + executorSetting.mockResolvedValue('node'); + expect( + (await handleBuildAndPublish(2, { environment: 'staging' }, tokenData(), env())).error + ).toBeUndefined(); + expect(mockStartBuildPublishJobOnVm).toHaveBeenCalled(); + }); + it.each(['context_ready', 'starting', 'building', 'succeeded'])( + 'returns the same job after a late source timeout in %s', + async (status) => { + executorSetting.mockResolvedValue('cloudflare'); + currentStatus = status; + collectContext.mockRejectedValueOnce(new Error('source acceptance timed out after handoff')); + mockAppendDeploymentPublishJobEvent.mockImplementation( + async (_db, input) => input.eventType !== 'publish.job.start_failed' + ); + const result = await handleBuildAndPublish(1, { environment: 'staging' }, tokenData(), env()); + expect(result.error).toBeUndefined(); + expect(JSON.parse(result.result?.content?.[0]?.text as string)).toMatchObject({ + publishJobId: 'job-1', + status, + executor: 'cloudflare', + }); + expect(mockAppendDeploymentPublishJobEvent).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ eventType: 'publish.job.start_failed', sourceCollector: true }) + ); + expect(cancelAccepted).not.toHaveBeenCalled(); + expect(mockStartBuildPublishJobOnVm).not.toHaveBeenCalled(); + } + ); + it('never falls back to the source after explicit Cloudflare collection fails', async () => { + executorSetting.mockResolvedValue('cloudflare'); + collectContext.mockRejectedValueOnce( + new Error('source collection route unavailable; upgrade source agent') + ); + const result = await handleBuildAndPublish(1, { environment: 'staging' }, tokenData(), env()); + expect(JSON.parse(result.result?.content?.[0]?.text as string).status).toBe('failed'); expect(mockStartBuildPublishJobOnVm).not.toHaveBeenCalled(); }); @@ -193,6 +261,7 @@ describe('async build_and_publish MCP tools', () => { expect(result.error).toBeUndefined(); expect(mockCreateDeploymentPublishJob).toHaveBeenCalledWith(expect.anything(), { + executor: 'node', projectId: 'proj-1', environmentId: 'env-1', workspaceId: 'ws-1', diff --git a/apps/api/tests/unit/node-cleanup.test.ts b/apps/api/tests/unit/node-cleanup.test.ts index 9596c586a5..ca53a67068 100644 --- a/apps/api/tests/unit/node-cleanup.test.ts +++ b/apps/api/tests/unit/node-cleanup.test.ts @@ -284,6 +284,51 @@ describe('runNodeCleanupSweep', () => { }); describe('Layer 1: stale warm node destruction', () => { + it('continues to the next node when teardown and its failure handler both fail', async () => { + const { deleteNodeResourcesStrict } = await import('../../src/services/nodes'); + const outcomes = await import('../../src/scheduled/node-cleanup/cleanup-outcome'); + const { log } = await import('../../src/lib/logger'); + const failureHandler = vi + .spyOn(outcomes, 'handleCleanupFailure') + .mockRejectedValueOnce(new Error('failure diagnosis unavailable')); + vi.mocked(deleteNodeResourcesStrict).mockRejectedValueOnce(new Error('provider unavailable')); + const warmSince = new Date(Date.now() - 40 * 60 * 1000).toISOString(); + const env = createMockEnv( + new Map([ + [ + 'n.warm_since IS NOT NULL', + ['node-failed', 'node-next'].map((id) => ({ + id, + user_id: 'user-1', + warm_since: warmSince, + active_ws_count: 0, + })), + ], + ]) + ); + + try { + const result = await runNodeCleanupSweep(env); + + expect(vi.mocked(deleteNodeResourcesStrict).mock.calls.map(([id]) => id)).toEqual([ + 'node-failed', + 'node-next', + ]); + expect(result.staleDestroyed).toBe(1); + expect(result.errors).toBe(1); + expect(log.error).toHaveBeenCalledWith( + 'node_cleanup.failure_handler_failed', + expect.objectContaining({ + nodeId: 'node-failed', + error: 'failure diagnosis unavailable', + originalError: 'provider unavailable', + }) + ); + } finally { + failureHandler.mockRestore(); + } + }); + it('destroys stale warm nodes with no active workspaces', async () => { const { deleteNodeResourcesStrict } = await import('../../src/services/nodes'); const now = Date.now(); diff --git a/apps/api/tests/unit/routes/build-context-callback.test.ts b/apps/api/tests/unit/routes/build-context-callback.test.ts index fa9ff94d42..83d11c326c 100644 --- a/apps/api/tests/unit/routes/build-context-callback.test.ts +++ b/apps/api/tests/unit/routes/build-context-callback.test.ts @@ -6,6 +6,9 @@ import * as schema from '../../../src/db/schema'; import type { Env } from '../../../src/env'; import { AppError, errors } from '../../../src/middleware/error'; import { createSchemaTables, createSqliteD1 } from '../../helpers/sqlite-d1'; +vi.mock('../../../src/services/cloudflare-build-executor', () => ({ + dispatchCloudflareBuild: vi.fn(async () => true), +})); const lifecycle = vi.hoisted(() => vi.fn(async () => undefined)); const signed = vi.hoisted(() => vi.fn(async () => 'https://signed.invalid/object')); vi.mock('@aws-sdk/s3-request-presigner', () => ({ getSignedUrl: signed })); @@ -48,7 +51,13 @@ function request(operation: string, body: unknown = {}, project = 'project', tok { method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, - body: JSON.stringify({ attempt: 1, sizeBytes: 100, sha256, ...(body as object) }), + body: JSON.stringify({ + attempt: 1, + sizeBytes: 100, + sha256, + projectName: 'fixture', + ...(body as object), + }), }, env, { diff --git a/apps/api/tests/unit/routes/cloudflare-collector-handoff.test.ts b/apps/api/tests/unit/routes/cloudflare-collector-handoff.test.ts new file mode 100644 index 0000000000..9b035f911c --- /dev/null +++ b/apps/api/tests/unit/routes/cloudflare-collector-handoff.test.ts @@ -0,0 +1,160 @@ +import { admitCloudflareBuild } from '@simple-agent-manager/app-deployment'; +import Database from 'better-sqlite3'; +import { drizzle } from 'drizzle-orm/d1'; +import { Hono } from 'hono'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import * as schema from '../../../src/db/schema'; +import type { Env } from '../../../src/env'; +import { AppError } from '../../../src/middleware/error'; +import { createSchemaTables, createSqliteD1 } from '../../helpers/sqlite-d1'; + +const auth = vi.hoisted(() => ({ verify: vi.fn(), lifecycle: vi.fn(async () => undefined) })); +vi.mock('../../../src/routes/projects/_publish-callback-auth', () => ({ + verifyPublishCallback: auth.verify, +})); +vi.mock('../../../src/services/project-lifecycle-events', () => ({ + recordDeploymentPublishJobLifecycleEventBestEffort: auth.lifecycle, +})); +vi.mock('../../../src/routes/projects/publish-job-spec', async () => { + const { Hono } = await import('hono'); + return { publishJobSpecRoute: new Hono() }; +}); +import { deploymentPublishJobCallbackRoute } from '../../../src/routes/projects/deployment-publish-job-callback'; + +let sqlite: Database.Database; +let database: D1Database; +let admitAtCallbackFence: boolean; +const app = new Hono<{ Bindings: Env }>(); +app.onError((error, c) => + c.json({ error: error.message }, error instanceof AppError ? error.statusCode : 500) +); +app.route('/api/projects', deploymentPublishJobCallbackRoute); +beforeEach(() => { + vi.clearAllMocks(); + sqlite = new Database(':memory:'); + createSchemaTables(sqlite, [schema.deploymentPublishJobs, schema.deploymentPublishJobEvents]); + database = createSqliteD1(sqlite); + sqlite + .prepare( + `INSERT INTO deployment_publish_jobs + (id,project_id,environment_id,workspace_id,node_id,requested_by,executor,context_shadow,status,current_step,attempt,context_r2_key,context_sha256,created_at,updated_at) + VALUES ('job','project','env','workspace','node','user','cloudflare',0,'context_ready','context_ready',1,'context','digest',?,?)` + ) + .run(new Date().toISOString(), new Date().toISOString()); + admitAtCallbackFence = false; + auth.verify.mockImplementation(async (c) => ({ + body: await c.req.json(), + projectId: 'project', + workspaceId: 'workspace', + userId: 'user', + db: drizzle(database, { schema }), + assertCurrent: async () => { + if (admitAtCallbackFence) { + admitAtCallbackFence = false; + await admit(); + } + }, + })); +}); +afterEach(() => sqlite.close()); +async function admit() { + expect( + await admitCloudflareBuild(drizzle(database, { schema }), 'job', { + platform: 6, + project: 2, + classMax: 6, + deadlineMs: 1800000, + }) + ).toBeTruthy(); +} +function row() { + return sqlite + .prepare( + "SELECT status,current_step,executor_instance_id FROM deployment_publish_jobs WHERE id='job'" + ) + .get(); +} +function collected(extra = {}) { + return app.request( + '/api/projects/project/deployment-publish-jobs/job/events', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + eventType: 'publish.context.collected', + message: 'build context collection complete', + status: 'context_ready', + currentStep: 'context_ready', + ...extra, + }), + }, + { DATABASE: database } as Env, + { waitUntil: vi.fn(), passThroughOnException: vi.fn() } + ); +} +describe('source collector completion after verified-context handoff', () => { + it.each([false, true])( + 'does not undo atomic admission (admission races callback read: %s)', + async (race) => { + if (race) admitAtCallbackFence = true; + else await admit(); + const response = await collected(); + expect(response.status).toBe(200); + expect(row()).toEqual({ + status: 'starting', + current_step: 'builder_start', + executor_instance_id: 'job', + }); + expect(sqlite.prepare('SELECT event_type FROM deployment_publish_job_events').all()).toEqual([ + { event_type: 'publish.context.collected' }, + ]); + expect(auth.lifecycle).not.toHaveBeenCalled(); + } + ); + it('keeps recording source receipt without replacing builder progress', async () => { + await admit(); + sqlite + .prepare("UPDATE deployment_publish_jobs SET status='building', current_step='build'") + .run(); + expect((await collected()).status).toBe(200); + expect(row()).toEqual({ + status: 'building', + current_step: 'build', + executor_instance_id: 'job', + }); + }); + it('does not let the generic collector receipt replace context verification', async () => { + sqlite + .prepare("UPDATE deployment_publish_jobs SET status='collecting', current_step='collecting'") + .run(); + expect((await collected()).status).toBe(200); + expect(row()).toMatchObject({ status: 'collecting', current_step: 'collecting' }); + }); + it('preserves terminal completion for phase-2 shadow collection', async () => { + sqlite.prepare('UPDATE deployment_publish_jobs SET context_shadow=1').run(); + expect((await collected({ status: 'succeeded', terminal: true })).status).toBe(200); + expect(row()).toMatchObject({ status: 'succeeded' }); + }); + it('rejects a delayed collector receipt after terminal completion without writes', async () => { + sqlite + .prepare("UPDATE deployment_publish_jobs SET status='failed', current_step='deadline'") + .run(); + const before = row(); + expect((await collected()).status).toBe(409); + expect(row()).toEqual(before); + expect( + sqlite.prepare('SELECT count(*) AS count FROM deployment_publish_job_events').get() + ).toEqual({ count: 0 }); + expect(auth.lifecycle).not.toHaveBeenCalled(); + }); + it('accepts a real builder heartbeat with no status or step after admission', async () => { + await admit(); + sqlite.prepare("UPDATE deployment_publish_jobs SET last_heartbeat_at='2000-01-01T00:00:00.000Z'").run(); + auth.verify.mockImplementation(async (c) => ({ body: await c.req.json(), projectId: 'project', workspaceId: 'workspace', userId: 'user', db: drizzle(database, { schema }), assertCurrent: async () => {}, job: { attempt: 1 } })); + expect((await collected({eventType:'publish.job.heartbeat',status:undefined,currentStep:undefined})).status).toBe(200); + expect(row()).toMatchObject({status:'starting',current_step:'builder_start'}); + expect(sqlite.prepare('SELECT last_heartbeat_at FROM deployment_publish_jobs').get()).not.toEqual({last_heartbeat_at:'2000-01-01T00:00:00.000Z'}); + }); + +}); diff --git a/apps/api/tests/unit/routes/compose-image-artifacts-callback.test.ts b/apps/api/tests/unit/routes/compose-image-artifacts-callback.test.ts index 0356c7a25d..95cdd4aa87 100644 --- a/apps/api/tests/unit/routes/compose-image-artifacts-callback.test.ts +++ b/apps/api/tests/unit/routes/compose-image-artifacts-callback.test.ts @@ -154,6 +154,16 @@ describe('compose-image-artifacts callback (vertical slice)', () => { verifiedPayload = { workspace: 'ws-1', type: 'callback', scope: 'workspace' }; }); + it.each(['init', 'complete'] as const)( + 'bounds actual workspace-token %s body bytes', + async (path) => { + const app = await buildApp(); + const response = await request(app, 'proj-1', path, { padding: '界'.repeat(400_000) }, {}); + expect(response.status).toBe(413); + expect(createUploadsMock).not.toHaveBeenCalled(); + } + ); + describe('POST /init', () => { const validInit = { environment: 'staging', diff --git a/apps/api/tests/unit/routes/deployment-environment-observability.test.ts b/apps/api/tests/unit/routes/deployment-environment-observability.test.ts index 48246b5950..a92d4c9e12 100644 --- a/apps/api/tests/unit/routes/deployment-environment-observability.test.ts +++ b/apps/api/tests/unit/routes/deployment-environment-observability.test.ts @@ -47,7 +47,8 @@ vi.mock('drizzle-orm/d1', () => ({ drizzle: () => ({ select: mockSelect, update: mockUpdate, delete: mockDelete }), })); -vi.mock('drizzle-orm', () => ({ +vi.mock('drizzle-orm', async (importOriginal) => ({ + ...(await importOriginal()), and: (...args: unknown[]) => args, or: (...args: unknown[]) => args, isNull: (value: unknown) => [value, null], diff --git a/apps/api/tests/unit/routes/deployment-membership-auth.test.ts b/apps/api/tests/unit/routes/deployment-membership-auth.test.ts index 14dfdc787b..6c994fedb7 100644 --- a/apps/api/tests/unit/routes/deployment-membership-auth.test.ts +++ b/apps/api/tests/unit/routes/deployment-membership-auth.test.ts @@ -77,7 +77,8 @@ let memberRows: ProjectMemberRow[] = []; let environmentRows: EnvironmentRow[] = []; let nodeRows: NodeRow[] = []; -vi.mock('drizzle-orm', () => ({ +vi.mock('drizzle-orm', async (importOriginal) => ({ + ...(await importOriginal()), and: (...conds: Condition[]) => ({ op: 'and', conds }), eq: (col: unknown, val: unknown) => ({ op: 'eq', col, val }), })); diff --git a/apps/api/tests/unit/routes/deployment-publish-job-callback.test.ts b/apps/api/tests/unit/routes/deployment-publish-job-callback.test.ts index c4ff8895c2..61cf05f82b 100644 --- a/apps/api/tests/unit/routes/deployment-publish-job-callback.test.ts +++ b/apps/api/tests/unit/routes/deployment-publish-job-callback.test.ts @@ -3,6 +3,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { AppError } from '../../../src/middleware/error'; +vi.mock('../../../src/app-deployment-ports/cloudflare-builder', () => ({ + createCloudflareBuildPorts: vi.fn(), +})); +vi.mock('../../../src/routes/projects/publish-job-spec', async () => { + const { Hono } = await import('hono'); + return { publishJobSpecRoute: new Hono() }; +}); const WORKSPACES = { __table: 'workspaces', id: 'workspaces.id', @@ -35,7 +42,8 @@ const { appendMock, recordDeploymentPublishJobLifecycleEventBestEffort, signalCa signalCallbackMock: vi.fn(async () => undefined), })); -vi.mock('drizzle-orm', () => ({ +vi.mock('drizzle-orm', async (importOriginal) => ({ + ...(await importOriginal()), and: (...conds: unknown[]) => ({ op: 'and', conds }), eq: (col: unknown, val: unknown) => ({ op: 'eq', col, val }), })); @@ -77,6 +85,7 @@ vi.mock('../../../src/services/jwt', () => ({ })); vi.mock('../../../src/services/deployment-publish-jobs', () => ({ + PUBLISH_JOB_TERMINAL_STATUSES: new Set(['succeeded', 'failed', 'canceled', 'unknown']), appendDeploymentPublishJobEvent: (...args: unknown[]) => appendMock(...args), })); vi.mock('../../../src/services/project-lifecycle-events', () => ({ diff --git a/apps/api/tests/unit/routes/node-delete-real-sql.test.ts b/apps/api/tests/unit/routes/node-delete-real-sql.test.ts index 1076d6f22c..bf3fb04bc1 100644 --- a/apps/api/tests/unit/routes/node-delete-real-sql.test.ts +++ b/apps/api/tests/unit/routes/node-delete-real-sql.test.ts @@ -39,7 +39,10 @@ vi.mock('../../../src/services/node-lifecycle', () => ({ finalizeDeletion: (...args: unknown[]) => mocks.finalizeDeletion(...args), })); +import { drizzle } from 'drizzle-orm/d1'; + import { nodesRoutes } from '../../../src/routes/nodes'; +import { deleteOwnedNode } from '../../../src/routes/nodes/delete'; const TERMINATION_PROOF_AT = '2026-09-04T09:00:00.000Z'; const ORIGINAL_INCARNATION = 'runtime-node-1'; @@ -137,6 +140,53 @@ describe('DELETE /api/nodes/:id managed-node proof predicates — real SQL verti afterEach(() => sqlite.close()); + it.each(['DELETE', 'POST'])( + 'rejects owner/manual %s before provider teardown or attestation when a builder is reserved', + async (method) => { + seedNode(); + sqlite.exec(`INSERT INTO deployment_publish_jobs + (id,node_id,executor,context_shadow,executor_instance_id,status) + VALUES ('job','node-1','cloudflare',0,'job','succeeded')`); + const response = await app.request( + `/api/nodes/node-1${method === 'POST' ? '/manual-deletion' : ''}`, + { + method, + ...(method === 'POST' + ? { + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ confirmed: true }), + } + : {}), + }, + env + ); + expect(response.status).toBe(409); + expect(mocks.deleteNodeResources).not.toHaveBeenCalled(); + expect(mocks.finalizeDeletion).not.toHaveBeenCalled(); + expect(sqlite.prepare('SELECT runtime_termination_attested_at FROM nodes').get()).toEqual({ + runtime_termination_attested_at: null, + }); + expect(sqlite.prepare('SELECT id FROM deployment_publish_jobs').get()).toEqual({ id: 'job' }); + } + ); + + it('the shared Operations delete_node entry point rejects before provider teardown', async () => { + seedNode(); + sqlite.exec(`INSERT INTO deployment_publish_jobs + (id,node_id,executor,context_shadow,executor_instance_id,status) + VALUES ('job','node-1','cloudflare',0,'job','building')`); + await expect( + deleteOwnedNode( + env, + drizzle(env.DATABASE, { schema }), + await mocks.requireNodeOwnership(), + 'user-1' + ) + ).rejects.toMatchObject({ statusCode: 409 }); + expect(mocks.deleteNodeResources).not.toHaveBeenCalled(); + expect(mocks.finalizeDeletion).not.toHaveBeenCalled(); + }); + it('deletes only workspaces carrying the matching proof and the exact node incarnation', async () => { seedNode(); seedWorkspace('workspace-confirmed', TERMINATION_PROOF_AT); diff --git a/apps/api/tests/unit/routes/node-stop-status.test.ts b/apps/api/tests/unit/routes/node-stop-status.test.ts index 06d06053d8..2250ed0a3c 100644 --- a/apps/api/tests/unit/routes/node-stop-status.test.ts +++ b/apps/api/tests/unit/routes/node-stop-status.test.ts @@ -160,7 +160,9 @@ describe('POST /api/nodes/:id/stop', () => { const mockSelectChain: any = {}; mockSelectChain.from = vi.fn(() => mockSelectChain); - mockSelectChain.where = vi.fn(() => Promise.resolve([])); + mockSelectChain.where = vi.fn(() => + Object.assign(Promise.resolve([]), { limit: vi.fn(async () => []) }) + ); mockDeleteWhere = vi.fn(() => Promise.resolve()); @@ -228,7 +230,9 @@ describe('DELETE /api/nodes/:id', () => { const mockSelectChain: any = {}; mockSelectChain.from = vi.fn(() => mockSelectChain); - mockSelectChain.where = vi.fn(() => Promise.resolve([])); + mockSelectChain.where = vi.fn(() => + Object.assign(Promise.resolve([]), { limit: vi.fn(async () => []) }) + ); mockDeleteWhere = vi.fn(() => Promise.resolve()); (drizzle as any).mockReturnValue({ @@ -318,9 +322,14 @@ describe('DELETE /api/nodes/:id', () => { }); (drizzle as any).mockReturnValue({ select: vi.fn(() => { - const result = selectResults[selectIndex++] ?? []; + let result: any[] = []; const chain: any = {}; - chain.from = vi.fn(() => chain); + chain.from = vi.fn((table: any) => { + // Reservation preflights have their own table; do not consume proof fixtures. + result = table?.[Symbol.for('drizzle:Name')] === 'deployment_publish_jobs' + ? [] : (selectResults[selectIndex++] ?? []); + return chain; + }); chain.where = vi.fn(() => Object.assign(Promise.resolve(result), { limit: vi.fn(async () => result) }) ); diff --git a/apps/api/tests/unit/routes/project-delete-real-sql.test.ts b/apps/api/tests/unit/routes/project-delete-real-sql.test.ts index 0f82df6f13..2e92f4c52e 100644 --- a/apps/api/tests/unit/routes/project-delete-real-sql.test.ts +++ b/apps/api/tests/unit/routes/project-delete-real-sql.test.ts @@ -126,6 +126,19 @@ describe('DELETE /api/projects/:id library cleanup — real SQL vertical slice', afterEach(() => sqlite.close()); + it('rejects a reserved builder before deleting project records or R2 objects', async () => { + addProject(PROJECT_A, OWNER_A); + addFile(PROJECT_A, 'a-file-1'); + sqlite.exec(`INSERT INTO deployment_publish_jobs + (id,project_id,executor,context_shadow,executor_instance_id,status) + VALUES ('job','project-a','cloudflare',0,'job','succeeded')`); + const response = await app.request(`/api/projects/${PROJECT_A}`, { method: 'DELETE' }, env); + expect(response.status).toBe(409); + expect(ids('projects')).toContain(PROJECT_A); + expect(ids('project_files')).toContain('a-file-1'); + expect(deletedObjects).toEqual([]); + }); + it('deletes project A rows and R2 keys through the route while project B is untouched', async () => { addProject(PROJECT_A, OWNER_A); addProject(PROJECT_B, 'user-b'); diff --git a/apps/api/tests/unit/routes/project-delete.test.ts b/apps/api/tests/unit/routes/project-delete.test.ts index 35c9fdbeac..068cf57329 100644 --- a/apps/api/tests/unit/routes/project-delete.test.ts +++ b/apps/api/tests/unit/routes/project-delete.test.ts @@ -45,16 +45,20 @@ describe('DELETE /api/projects/:id', () => { select: vi.fn(() => { operations.push('select'); const selectChain: any = {}; - selectChain.from = vi.fn(() => selectChain); + let reservationQuery = false; + selectChain.from = vi.fn((table: any) => { + reservationQuery = table?.[Symbol.for('drizzle:Name')] === 'deployment_publish_jobs'; + return selectChain; + }); selectChain.where = vi.fn(() => selectChain); selectChain.orderBy = vi.fn(() => selectChain); selectChain.groupBy = vi.fn(() => selectChain); selectChain.limit = vi.fn(() => { - return Promise.resolve(selectResults.shift() ?? []); + return Promise.resolve(reservationQuery ? [] : (selectResults.shift() ?? [])); }); // When awaited directly (without .limit()), resolve to data selectChain.then = (resolve: any, reject: any) => { - return Promise.resolve(selectResults.shift() ?? []).then(resolve, reject); + return Promise.resolve(reservationQuery ? [] : (selectResults.shift() ?? [])).then(resolve, reject); }; return selectChain; }), diff --git a/apps/api/tests/unit/routes/publish-hardening-real-sqlite.test.ts b/apps/api/tests/unit/routes/publish-hardening-real-sqlite.test.ts index a6e937cba8..0f169d6dc2 100644 --- a/apps/api/tests/unit/routes/publish-hardening-real-sqlite.test.ts +++ b/apps/api/tests/unit/routes/publish-hardening-real-sqlite.test.ts @@ -1,15 +1,30 @@ import Database from 'better-sqlite3'; import { drizzle } from 'drizzle-orm/d1'; import { Hono } from 'hono'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { exportPKCS8, exportSPKI, generateKeyPair } from 'jose'; +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import * as schema from '../../../src/db/schema'; import type { Env } from '../../../src/env'; import { AppError } from '../../../src/middleware/error'; +import { signPublishJobToken } from '../../../src/services/publish-job-token'; import { createSchemaTables, createSqliteD1 } from '../../helpers/sqlite-d1'; let sqlite: Database.Database; let database: D1Database; +let keyEnv: Partial; +beforeAll(async () => { + const keys = await generateKeyPair('RS256', { extractable: true }); + keyEnv = { + JWT_PRIVATE_KEY: await exportPKCS8(keys.privateKey), + JWT_PUBLIC_KEY: await exportSPKI(keys.publicKey), + BASE_DOMAIN: 'example.test', + }; +}); +vi.mock('@aws-sdk/s3-request-presigner', () => ({ + getSignedUrl: vi.fn(async () => 'https://signed.invalid/artifact'), +})); +const stopBuilder = vi.hoisted(() => vi.fn(async () => {})); const cancelVm = vi.hoisted(() => vi.fn(async () => { throw new Error('VM returned 404'); @@ -23,7 +38,14 @@ vi.mock('../../../src/services/admin-settings', async (importOriginal) => { resolveAdminSetting: (async (env, name) => name === 'deployments.publishJobCancelTimeoutMs' ? 10 - : actual.resolveAdminSetting(env, name)) as typeof actual.resolveAdminSetting, + : (( + { + 'deployments.buildContextMaxBytes': 536870912, + 'deployments.buildContextUploadTtlSeconds': 900, + 'deployments.builderDaemonReadyTimeoutMs': 60000, + 'deployments.builderHeartbeatIntervalMs': 15000, + } as Record + )[name] ?? actual.resolveAdminSetting(env, name))) as typeof actual.resolveAdminSetting, }; }); vi.mock('../../../src/routes/mcp/workspace-tools', async (importOriginal) => ({ @@ -60,6 +82,8 @@ vi.mock('../../../src/services/project-lifecycle-events', () => ({ recordDeploymentPublishJobLifecycleEventBestEffort: lifecycle, })); +const { composeImageArtifactsCallbackRoute } = + await import('../../../src/routes/projects/compose-image-artifacts-callback'); const { handleCancelPublish } = await import('../../../src/routes/mcp/compose-publish-tools'); const { composePublishReleaseCallbackRoute } = await import('../../../src/routes/projects/compose-publish-release-callback'); @@ -72,12 +96,20 @@ app.onError((err, c) => : c.json({ error: err.message }, 500) ); app.route('/projects', composePublishReleaseCallbackRoute); +app.route('/projects', composeImageArtifactsCallbackRoute); app.route('/projects', deploymentPublishJobCallbackRoute); -function request(path: string, body: unknown) { +function request(path: string, body: unknown, bearer?: string, extraEnv: Partial = {}) { return app.request( `/projects/project/${path}`, - { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }, - { DATABASE: database } as Env, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(bearer ? { Authorization: `Bearer ${bearer}` } : {}), + }, + body: JSON.stringify(body), + }, + { ...extraEnv, DATABASE: database } as Env, { waitUntil: () => undefined, passThroughOnException: () => undefined, @@ -106,17 +138,20 @@ beforeEach(() => { schema.deploymentPublishJobs, schema.deploymentPublishJobEvents, schema.deploymentReleases, + schema.deploymentEnvironmentConfigVars, ]); database = createSqliteD1(sqlite); sqlite.exec( "INSERT INTO deployment_environments(id,project_id,node_id,status) VALUES('environment','project','node','running')" ); sqlite.exec( - "INSERT INTO deployment_publish_jobs(id,project_id,workspace_id,environment_id,node_id,requested_by,status,attempt) VALUES('job','project','workspace','environment','node','user','building',1)" + // The SQLite helper omits defaults; seed the real legacy-node defaults explicitly. + "INSERT INTO deployment_publish_jobs(id,project_id,workspace_id,environment_id,node_id,requested_by,status,attempt,executor,context_shadow) VALUES('job','project','workspace','environment','node','user','building',1,'node',0)" ); lifecycle.mockClear(); provisionVolumes.mockClear(); cancelVm.mockClear(); + stopBuilder.mockClear(); }); afterEach(() => sqlite.close()); describe('publish callback routes with real SQL', () => { @@ -303,3 +338,199 @@ describe('publish callback routes with real SQL', () => { expect((await submit()).status).toBe(200); }); }); + +describe('real signed job tokens through actual publish callback routes', () => { + async function identity() { + sqlite.exec( + "UPDATE deployment_publish_jobs SET executor='cloudflare',executor_instance_id='job',context_shadow=0,agent_profile_id='profile',environment_name='staging'" + ); + const env = { + ...keyEnv, + DATABASE: database, + R2: { head: async () => ({ size: 100 }) }, + CF_ACCOUNT_ID: 'test-account', + R2_ACCESS_KEY_ID: 'fake-access', + R2_SECRET_ACCESS_KEY: 'fake-secret', + R2_BUCKET_NAME: 'bucket', + COMPOSE_BUILDER: { idFromName: (id: string) => id, get: () => ({ stopJob: stopBuilder }) }, + } as unknown as Env; + const token = await signPublishJobToken( + env, + { + jobId: 'job', + projectId: 'project', + environmentId: 'environment', + agentProfileId: 'profile', + attempt: 1, + }, + Date.now() + 60000 + ); + return { env, token }; + } + const artifact = { + serviceName: 'web', + sourceRef: 'fixture:latest', + localImageRef: 'fixture:latest', + r2Key: 'compose-image-artifacts/project/environment/workspace/job-1/web.docker-save.tar', + sizeBytes: 100, + archiveSha256: 'sha256:' + 'a'.repeat(64), + archiveType: 'docker-save', + mediaType: 'application/vnd.docker.image.rootfs.diff.tar', + platform: { os: 'linux', architecture: 'amd64' }, + }; + it('parses the original body at events, artifact init/complete and release sinks, then revokes terminal identity', async () => { + const { env, token } = await identity(); + const policy = { + environment: 'staging', + environmentId: 'environment', + agentProfileId: 'profile', + }; + const progress = await request( + 'deployment-publish-jobs/job/events', + { eventType: 'publish.build.started', message: 'building', status: 'building' }, + token, + env + ); + expect(progress.status, await progress.clone().text()).toBe(200); + const init = await request( + 'compose-image-artifacts/init', + { ...policy, services: [{ serviceName: 'web', sourceRef: 'fixture:latest' }] }, + token, + env + ); + expect(init.status, await init.clone().text()).toBe(200); + expect(await init.json()).toMatchObject({ uploadId: 'job-1' }); + const complete = await request( + 'compose-image-artifacts/complete', + { ...policy, artifacts: [artifact] }, + token, + env + ); + expect(complete.status, await complete.clone().text()).toBe(200); + const release = await request( + 'compose-publish-release', + { + publishJobId: 'job', + attempt: 1, + environment: 'staging', + environmentId: 'environment', + composeYaml: 'services:\n web:\n image: fixture:latest\n', + services: [artifact], + submittedBy: { agentProfileId: 'profile' }, + }, + token, + env + ); + expect(release.status, await release.clone().text()).toBe(200); + const recorded = await release.json(); + const terminal = await request( + 'deployment-publish-jobs/job/events', + { + eventType: 'publish.job.completed', + message: 'complete', + status: 'succeeded', + releaseId: recorded.releaseId, + }, + token, + env + ); + expect(terminal.status, await terminal.clone().text()).toBe(200); + expect(stopBuilder).toHaveBeenCalled(); + expect( + ( + await request( + 'compose-image-artifacts/init', + { ...policy, services: [{ serviceName: 'web', sourceRef: 'fixture:latest' }] }, + token, + env + ) + ).status + ).toBe(410); + }); + it('serves only a verified admitted context through the existing job spec route', async () => { + const { env, token } = await identity(); + const get = (id = 'job') => + app.request( + `/projects/project/deployment-publish-jobs/${id}/spec`, + { + headers: { Authorization: `Bearer ${token}` }, + }, + env + ); + expect((await get()).status).toBe(409); + sqlite + .prepare( + 'UPDATE deployment_publish_jobs SET context_r2_key=?,context_sha256=?,context_bytes=100,context_project_name=?,executor_deadline_at=?' + ) + .run( + 'compose-build-contexts/project/environment/job/1.tar.zst', + 'a'.repeat(64), + 'source-project', + new Date(Date.now() + 60000).toISOString() + ); + const response = await get(); + expect(response.status, await response.clone().text()).toBe(200); + expect(await response.json()).toMatchObject({ + jobId: 'job', + attempt: 1, + projectName: 'source-project', + contextBytes: 100, + buildInterpolationEnv: {}, + secretInterpolationKeys: [], + }); + expect((await get('foreign')).status).toBe(403); + sqlite.exec("UPDATE deployment_publish_jobs SET status='canceled'"); + expect((await get()).status).toBe(410); + }); + it('rejects missing release fence and foreign artifact attempts with live owner controls', async () => { + const { env, token } = await identity(); + const policy = { + environment: 'staging', + environmentId: 'environment', + agentProfileId: 'profile', + }; + expect( + ( + await request( + 'compose-publish-release', + { ...policy, submittedBy: { agentProfileId: 'profile' } }, + token, + env + ) + ).status + ).toBe(403); + expect( + ( + await request( + 'compose-image-artifacts/complete', + { + ...policy, + artifacts: [{ ...artifact, r2Key: artifact.r2Key.replace('job-1', 'job-2') }], + }, + token, + env + ) + ).status + ).toBe(403); + expect( + ( + await request( + 'compose-image-artifacts/complete', + { ...policy, artifacts: [artifact] }, + token, + env + ) + ).status + ).toBe(200); + expect( + ( + await request( + 'deployment-publish-jobs/job/events', + { eventType: 'publish.release', message: 'fake', releaseId: 'foreign' }, + token, + env + ) + ).status + ).toBe(403); + }); +}); diff --git a/apps/api/tests/unit/routes/publish-job-authorization.test.ts b/apps/api/tests/unit/routes/publish-job-authorization.test.ts new file mode 100644 index 0000000000..fc8f6d4667 --- /dev/null +++ b/apps/api/tests/unit/routes/publish-job-authorization.test.ts @@ -0,0 +1,153 @@ +import Database from 'better-sqlite3'; +import { Hono } from 'hono'; +import { exportPKCS8, exportSPKI, generateKeyPair } from 'jose'; +import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import * as schema from '../../../src/db/schema'; +import type { Env } from '../../../src/env'; +import { AppError } from '../../../src/middleware/error'; +import { verifyPublishCallback } from '../../../src/routes/projects/_publish-callback-auth'; +import { signPublishJobToken } from '../../../src/services/publish-job-token'; +import { createSchemaTables, createSqliteD1 } from '../../helpers/sqlite-d1'; +let sqlite: Database.Database; +let env: Env; +let keys: { JWT_PRIVATE_KEY: string; JWT_PUBLIC_KEY: string }; +let token: string; +const claims = { + jobId: 'job', + projectId: 'project', + environmentId: 'env', + agentProfileId: 'profile', + attempt: 1, +}; +const release = { + environment: 'staging', + environmentId: 'env', + publishJobId: 'job', + attempt: 1, + submittedBy: { agentProfileId: 'profile', taskId: 'task' }, + services: [{ r2Key: 'compose-image-artifacts/project/env/ws/job-1/web.docker-save.tar' }], +}; +beforeAll(async () => { + const p = await generateKeyPair('RS256', { extractable: true }); + keys = { + JWT_PRIVATE_KEY: await exportPKCS8(p.privateKey), + JWT_PUBLIC_KEY: await exportSPKI(p.publicKey), + }; +}); +beforeEach(async () => { + sqlite = new Database(':memory:'); + createSchemaTables(sqlite, [schema.deploymentPublishJobs, schema.platformSettings]); + sqlite + .prepare( + `INSERT INTO deployment_publish_jobs(id,project_id,environment_id,workspace_id,node_id,requested_by,environment_name,status,executor,context_shadow,agent_profile_id,attempt,task_id) VALUES('job','project','env','ws','node','user','staging','building','cloudflare',0,'profile',1,'task')` + ) + .run(); + env = { ...keys, BASE_DOMAIN: 'example.test', DATABASE: createSqliteD1(sqlite) } as Env; + token = await signPublishJobToken(env, claims, Date.now() + 60_000); +}); +afterEach(() => sqlite.close()); +function request(body: unknown, project = 'project') { + const app = new Hono<{ Bindings: Env }>(); + app.onError((e, c) => c.json({ error: e.message }, e instanceof AppError ? e.statusCode : 500)); + app.post('/:id/compose-publish-release', async (c) => { + const v = await verifyPublishCallback(c, 'compose_publish_release', 'scope'); + await v.assertCurrent(); + expect(v.body).toBeDefined(); + return c.json({ jobId: v.job?.id }); + }); + return app.request( + `/${project}/compose-publish-release`, + { + method: 'POST', + headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }, + env + ); +} +describe('publish-job release authorization uses real signatures and SQLite ownership', () => { + it('accepts owner without a source workspace or node', async () => { + expect((await request(release)).status).toBe(200); + }); + for (const mutation of [ + { publishJobId: undefined }, + { attempt: undefined }, + { publishJobId: 'foreign' }, + { attempt: 2 }, + { environment: 'other' }, + { environmentId: 'other' }, + { submittedBy: { agentProfileId: 'foreign', taskId: 'task' } }, + { submittedBy: { agentProfileId: 'profile', taskId: 'other' } }, + { services: [{ r2Key: 'compose-image-artifacts/project/env/ws/job-2/web.docker-save.tar' }] }, + { + services: [{ r2Key: 'compose-image-artifacts/project/env/ws/foreign-1/web.docker-save.tar' }], + }, + ]) + it(`rejects scope smuggling ${JSON.stringify(mutation)} with owner control`, async () => { + expect((await request({ ...release, ...mutation })).status).toBe(403); + expect((await request(release)).status).toBe(200); + }); + it('rejects another project route and a canceled job', async () => { + expect((await request(release, 'foreign')).status).toBe(403); + sqlite.prepare("UPDATE deployment_publish_jobs SET status='canceled'").run(); + expect((await request(release)).status).toBe(410); + }); +}); + +describe('publish callback actual byte bounds', () => { + for (const contentLength of [undefined, '1']) { + it(`rejects overflowing UTF8 stream with declared length ${contentLength}`, async () => { + sqlite + .prepare( + "INSERT INTO platform_settings(key,value,updated_at,updated_by) VALUES('deployments.publishCallbackMaxBodyBytes','1024',?,NULL)" + ) + .run(new Date().toISOString()); + const app = new Hono<{ Bindings: Env }>(); + app.onError((e, c) => + c.json({ error: e.message }, e instanceof AppError ? e.statusCode : 500) + ); + app.post('/:id/events', async (c) => { + await verifyPublishCallback(c, 'deployment_publish_job_event', 'scope'); + return c.json({ ok: true }); + }); + const raw = new TextEncoder().encode(JSON.stringify({ message: '界'.repeat(400) })); + let offset = 0; + const body = new ReadableStream({ + pull(controller) { + if (offset === raw.length) { + controller.close(); + return; + } + controller.enqueue(raw.slice(offset, offset + 17)); + offset = Math.min(raw.length, offset + 17); + }, + }); + const headers: Record = { Authorization: `Bearer ${token}` }; + if (contentLength) headers['content-length'] = contentLength; + const req = new Request('http://localhost/project/events', { + method: 'POST', + headers, + body, + duplex: 'half', + } as RequestInit); + expect((await app.request(req, undefined, env)).status).toBe(413); + }); + } + it('preserves invalid JSON as400 and authenticates before reading', async () => { + const app = new Hono<{ Bindings: Env }>(); + app.onError((e, c) => c.json({ error: e.message }, e instanceof AppError ? e.statusCode : 500)); + app.post('/:id/events', async (c) => { + await verifyPublishCallback(c, 'deployment_publish_job_event', 'scope'); + return c.json({ ok: true }); + }); + const response = await app.request( + '/project/events', + { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: '{' }, + env + ); + expect(response.status).toBe(400); + const unauth = await app.request('/project/events', { method: 'POST', body: '{' }, env); + expect(unauth.status).toBe(401); + }); +}); diff --git a/apps/api/tests/unit/services/build-context-shadow.test.ts b/apps/api/tests/unit/services/build-context-shadow.test.ts index 91bf1411fb..2165ff059e 100644 --- a/apps/api/tests/unit/services/build-context-shadow.test.ts +++ b/apps/api/tests/unit/services/build-context-shadow.test.ts @@ -14,7 +14,13 @@ const mock = vi.hoisted(() => ({ })); vi.mock('../../../src/services/admin-settings', () => ({ resolveAdminSetting: async (_env: unknown, key: string) => - key.endsWith('CollectionMode') ? mock.mode : key.endsWith('MaxBytes') ? 2147483648 : 10000, + key === 'deployments.buildExecutor' + ? 'node' + : key.endsWith('CollectionMode') + ? mock.mode + : key.endsWith('MaxBytes') + ? 2147483648 + : 10000, })); vi.mock('@simple-agent-manager/worker-core', async (load) => ({ ...(await load()), @@ -84,7 +90,7 @@ beforeEach(() => { ]); sqlite.exec("INSERT INTO nodes(id,runtime) VALUES('node','vm')"); env = { DATABASE: createSqliteD1(sqlite), BASE_DOMAIN: 'staging.invalid' } as Env; - mock.fetch.mockResolvedValue(new Response('{}', { status: 202 })); + mock.fetch.mockReset().mockResolvedValue(new Response('{}', { status: 202 })); }); afterEach(() => sqlite.close()); describe('shadow collection through the real publish handler', () => { @@ -127,18 +133,22 @@ describe('shadow collection through the real publish handler', () => { .get() ).toEqual({ status: 'failed', release_id: null }); }); - it('Instant shadow collects via a workspace JWT while retaining the early node-build gate', async () => { + it('Instant always collects a real Cloudflare job even when shadow collection is enabled', async () => { mock.mode = 'shadow'; sqlite.exec("UPDATE nodes SET runtime='cf-container'"); const result = await publish(); await Promise.all(pending); - expect(result.error?.message).toContain("Instant sessions isn't available"); + expect(result.error).toBeUndefined(); + expect(JSON.parse(result.result!.content[0].text)).toMatchObject({ + executor: 'cloudflare', + status: 'queued', + }); expect(mock.start).not.toHaveBeenCalled(); expect(mock.fetch).toHaveBeenCalledTimes(1); const request = mock.fetch.mock.calls[0] as unknown as [string, Env, string, RequestInit]; const body = JSON.parse(String(request[3].body)); expect(body).toMatchObject({ - shadow: true, + shadow: false, attempt: 1, workingDir: '/workspaces/app', secretInterpolationKeys: ['PRIVATE'], @@ -146,7 +156,7 @@ describe('shadow collection through the real publish handler', () => { expect(body).not.toHaveProperty('PRIVATE'); expect( sqlite.prepare('SELECT executor,context_shadow FROM deployment_publish_jobs').all() - ).toEqual([{ executor: 'cloudflare', context_shadow: 1 }]); + ).toEqual([{ executor: 'cloudflare', context_shadow: 0 }]); }); it('hides shadow jobs from status and user cancel reads, with normal owner controls', async () => { mock.mode = 'shadow'; diff --git a/apps/api/tests/unit/services/build-context-state.test.ts b/apps/api/tests/unit/services/build-context-state.test.ts index 5386d4ca0d..46b1192e61 100644 --- a/apps/api/tests/unit/services/build-context-state.test.ts +++ b/apps/api/tests/unit/services/build-context-state.test.ts @@ -90,3 +90,32 @@ describe('build context conditional state on real SQLite D1', () => { expect(await reserveBuildContext(db, owner, descriptor)).toBeNull(); }); }); + +it('binds Compose project identity to exact context receipts', async () => { + const named = { ...descriptor, projectName: 'original-project' }; + expect(await reserveBuildContext(db, owner, named)).toMatchObject({ + contextProjectName: 'original-project', + }); + expect(await reserveBuildContext(db, owner, { ...named, projectName: 'other' })).toBeNull(); + expect(await completeBuildContext(db, owner, { ...named, projectName: 'other' })).toBeNull(); + expect(await completeBuildContext(db, owner, named)).toMatchObject({ status: 'context_ready' }); +}); + +it('reconciles a lost complete response after admission without rewinding the builder', async () => { + await reserveBuildContext(db, owner, descriptor); + await completeBuildContext(db, owner, descriptor); + sqlite.exec("UPDATE deployment_publish_jobs SET status='building', executor_instance_id='job'"); + const before = sqlite.prepare('SELECT updated_at FROM deployment_publish_jobs').get(); + const events = sqlite.prepare('SELECT count(*) AS n FROM deployment_publish_job_events').get(); + expect(await completeBuildContext(db, owner, descriptor)).toMatchObject({ + status: 'building', + replayed: true, + }); + expect(sqlite.prepare('SELECT updated_at FROM deployment_publish_jobs').get()).toEqual(before); + expect(sqlite.prepare('SELECT count(*) AS n FROM deployment_publish_job_events').get()).toEqual( + events + ); + expect(await completeBuildContext(db, owner, { ...descriptor, sizeBytes: 101 })).toBeNull(); + sqlite.exec("UPDATE deployment_publish_jobs SET status='canceled'"); + expect(await completeBuildContext(db, owner, descriptor)).toBeNull(); +}); diff --git a/apps/api/tests/unit/services/cloudflare-build-admission.test.ts b/apps/api/tests/unit/services/cloudflare-build-admission.test.ts new file mode 100644 index 0000000000..8dd9ce26cc --- /dev/null +++ b/apps/api/tests/unit/services/cloudflare-build-admission.test.ts @@ -0,0 +1,134 @@ +import { + admitCloudflareBuild, + recoverReservedCloudflareBuild, + releaseCloudflareBuildReservation, +} from '@simple-agent-manager/app-deployment'; +import Database from 'better-sqlite3'; +import { drizzle } from 'drizzle-orm/d1'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import * as schema from '../../../src/db/schema'; +import { createSchemaTables, createSqliteD1 } from '../../helpers/sqlite-d1'; + +let sqlite: Database.Database; +let db: ReturnType>; +const limits = { platform: 6, project: 2, classMax: 6, deadlineMs: 1_200_000 }; +function seed(id: string, project = 'project') { + sqlite + .prepare( + `INSERT INTO deployment_publish_jobs (id, project_id,environment_id,workspace_id,node_id,requested_by,environment_name,status,executor,context_shadow,context_r2_key,context_sha256,created_at,attempt) VALUES(?,?,'env','ws','node','user','staging','context_ready','cloudflare',0,'key','sha',?,1)` + ) + .run(id, project, new Date().toISOString()); +} +beforeEach(() => { + sqlite = new Database(':memory:'); + createSchemaTables(sqlite, [schema.deploymentPublishJobs]); + db = drizzle(createSqliteD1(sqlite), { schema }); +}); +afterEach(() => sqlite.close()); +describe('Cloudflare build final atomic reservation in SQLite D1', () => { + it('two contenders for the final project slot yield exactly one winner', async () => { + for (const id of ['a', 'b', 'c']) seed(id); + expect(await admitCloudflareBuild(db, 'a', limits)).toBeTruthy(); + const contenders = await Promise.all( + ['b', 'c'].map((id) => admitCloudflareBuild(db, id, limits)) + ); + expect(contenders.filter(Boolean)).toHaveLength(1); + expect( + sqlite + .prepare( + 'SELECT count(*) AS n FROM deployment_publish_jobs WHERE executor_instance_id IS NOT NULL' + ) + .get() + ).toEqual({ n: 2 }); + }); + it('caps platform across projects and never exceeds class max', async () => { + for (let i = 0; i < 8; i++) seed(String(i), 'project' + i); + const all = await Promise.all( + Array.from({ length: 8 }, (_, i) => + admitCloudflareBuild(db, String(i), { ...limits, classMax: 3 }) + ) + ); + expect(all.filter(Boolean)).toHaveLength(3); + }); + it('holds capacity until terminal container is confirmed stopped', async () => { + seed('a'); + seed('b'); + expect(await admitCloudflareBuild(db, 'a', { ...limits, platform: 1 })).toBeTruthy(); + sqlite.prepare("UPDATE deployment_publish_jobs SET status='canceled' WHERE id='a'").run(); + expect(await admitCloudflareBuild(db, 'b', { ...limits, platform: 1 })).toBeNull(); + expect(await releaseCloudflareBuildReservation(db, 'a', 2)).toHaveLength(0); + await releaseCloudflareBuildReservation(db, 'a', 1); + expect(await admitCloudflareBuild(db, 'b', { ...limits, platform: 1 })).toBeTruthy(); + }); + it('backs off capacity errors, preserving cancellation and absolute deadline', async () => { + seed('a'); + const admitted = await admitCloudflareBuild(db, 'a', limits); + const retry = Date.now() + 30_000; + await releaseCloudflareBuildReservation(db, 'a', 1, retry); + expect(await admitCloudflareBuild(db, 'a', limits)).toBeNull(); + expect((await admitCloudflareBuild(db, 'a', limits, retry + 1))?.executorDeadlineAt).toBe( + admitted?.executorDeadlineAt + ); + sqlite.prepare("UPDATE deployment_publish_jobs SET status='canceled' WHERE id='a'").run(); + await releaseCloudflareBuildReservation(db, 'a', 1, retry + 60_000); + expect(sqlite.prepare("SELECT status FROM deployment_publish_jobs WHERE id='a'").get()).toEqual( + { status: 'canceled' } + ); + }); + it('rejects shadow, node, terminal, missing context and expired jobs', async () => { + const changes = [ + 'context_shadow=1', + "executor='node'", + "status='failed'", + 'context_r2_key=NULL', + "created_at='2000-01-01T00:00:00.000Z'", + ]; + for (let i = 0; i < changes.length; i++) { + seed(String(i)); + sqlite.prepare(`UPDATE deployment_publish_jobs SET ${changes[i]} WHERE id=?`).run(String(i)); + expect(await admitCloudflareBuild(db, String(i), limits)).toBeNull(); + } + seed('owner'); + expect(await admitCloudflareBuild(db, 'owner', limits)).toBeTruthy(); + }); +}); + +describe('reserved Cloudflare context regression recovery', () => { + it.each([ + "status='canceled'", + "status='building'", + 'attempt=2', + 'executor_instance_id=NULL', + "executor_instance_id='foreign'", + 'context_shadow=1', + 'executor_deadline_at=NULL', + "executor_deadline_at='2000-01-01T00:00:00.000Z'", + ])('does not recover an ineligible reservation: %s', async (mutation) => { + seed('job'); + await admitCloudflareBuild(db, 'job', limits); + sqlite.prepare("UPDATE deployment_publish_jobs SET status='context_ready'").run(); + sqlite.prepare('UPDATE deployment_publish_jobs SET ' + mutation).run(); + const before = sqlite.prepare('SELECT * FROM deployment_publish_jobs').get(); + expect(await recoverReservedCloudflareBuild(db, 'job', 1)).toBeNull(); + expect(sqlite.prepare('SELECT * FROM deployment_publish_jobs').get()).toEqual(before); + }); +}); + +it('capacity release compares the reservation epoch through same-attempt readmission', async () => { + seed('job'); + const first = await admitCloudflareBuild(db, 'job', limits); + expect(first).toBeTruthy(); + const retryAt = Date.now() + 30000; + expect(await releaseCloudflareBuildReservation(db, 'job', 1, retryAt, null)).toHaveLength(1); + const second = await admitCloudflareBuild(db, 'job', limits, retryAt + 1); + expect(second?.executorNotBefore).toBe(new Date(retryAt).toISOString()); + expect(await releaseCloudflareBuildReservation(db, 'job', 1, retryAt + 60000, null)).toHaveLength( + 0 + ); + expect( + sqlite + .prepare("SELECT status,executor_instance_id FROM deployment_publish_jobs WHERE id='job'") + .get() + ).toEqual({ status: 'starting', executor_instance_id: 'job' }); +}); diff --git a/apps/api/tests/unit/services/cloudflare-build-deletion.test.ts b/apps/api/tests/unit/services/cloudflare-build-deletion.test.ts new file mode 100644 index 0000000000..a49e37bdc6 --- /dev/null +++ b/apps/api/tests/unit/services/cloudflare-build-deletion.test.ts @@ -0,0 +1,298 @@ +import { + admitCloudflareBuild, + appendDeploymentPublishJobEvent, + assertNoReservedCloudflareBuilds, + type CloudflareBuildPorts, + drainCloudflareBuilds, + forceReleaseExpiredCloudflareBuild, + isCloudflareBuildDeletionConflict, + releaseCloudflareBuildReservation, +} from '@simple-agent-manager/app-deployment'; +import Database from 'better-sqlite3'; +import { drizzle } from 'drizzle-orm/d1'; +import { Hono } from 'hono'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import * as schema from '../../../src/db/schema'; +import type { Env } from '../../../src/env'; +import { handleAppError } from '../../../src/middleware/app-error-handler'; +import { applySqliteMigration, createSqliteD1 } from '../../helpers/sqlite-d1'; + +let sqlite: Database.Database; +let db: ReturnType>; +const limits = { platform: 6, project: 2, classMax: 6, deadlineMs: 1_200_000 }; +beforeEach(() => { + sqlite = new Database(':memory:'); + sqlite.pragma('foreign_keys = ON'); + for (const table of [ + 'projects', + 'deployment_environments', + 'nodes', + 'users', + 'deployment_releases', + 'workspaces', + ]) { + sqlite.exec( + `CREATE TABLE ${table} (id TEXT PRIMARY KEY); INSERT INTO ${table} VALUES ('owner')` + ); + } + // Real job FKs and shipped trigger, not the constraint-free schema test helper. + for (const file of [ + '0077_deployment_publish_jobs.sql', + '0227_publish_job_heartbeat.sql', + '0230_publish_job_build_context.sql', + '0231_publish_job_context_shadow.sql', + '0242_cloudflare_build_executor.sql', + '0244_cloudflare_build_reservation_deletion_guard.sql', + ]) { + applySqliteMigration(sqlite, new URL(`../../../src/db/migrations/${file}`, import.meta.url)); + } + sqlite + .prepare( + `INSERT INTO deployment_publish_jobs + (id,project_id,environment_id,workspace_id,node_id,requested_by,environment_name,executor,status,context_r2_key,context_sha256,created_at) + VALUES ('job','owner','owner','owner','owner','owner','production','cloudflare','context_ready','key','sha',?)` + ) + .run(new Date().toISOString()); + db = drizzle(createSqliteD1(sqlite), { schema }); +}); +afterEach(() => sqlite.close()); + +describe('Cloudflare reservation deletion fence', () => { + it.each(['deployment_publish_jobs', 'nodes', 'projects', 'deployment_environments', 'users'])( + 'blocks %s deletion, even for terminal reservations, then allows it after confirmed release', + async (table) => { + expect(await admitCloudflareBuild(db, 'job', limits)).toBeTruthy(); + const id = table === 'deployment_publish_jobs' ? 'job' : 'owner'; + for (const status of ['starting', 'building', 'canceled', 'succeeded']) { + sqlite.prepare('UPDATE deployment_publish_jobs SET status=?').run(status); + expect(() => sqlite.prepare(`DELETE FROM ${table} WHERE id=?`).run(id)).toThrow( + 'cloudflare_build_reservation_held' + ); + expect(sqlite.prepare('SELECT id FROM deployment_publish_jobs').get()).toEqual({ + id: 'job', + }); + if (table !== 'deployment_publish_jobs') + expect(sqlite.prepare(`SELECT id FROM ${table}`).get()).toBeTruthy(); + } + await releaseCloudflareBuildReservation(db, 'job', 1); + sqlite.prepare(`DELETE FROM ${table} WHERE id=?`).run(id); + expect(sqlite.prepare('SELECT id FROM deployment_publish_jobs').get()).toBeUndefined(); + } + ); + it.each(["executor='node'", 'context_shadow=1', 'executor_instance_id=NULL'])( + 'preserves legacy, shadow and unreserved deletion behavior: %s', + (mutation) => { + sqlite.prepare("UPDATE deployment_publish_jobs SET executor_instance_id='job'").run(); + sqlite.exec(`UPDATE deployment_publish_jobs SET ${mutation}`); + sqlite.exec("DELETE FROM nodes WHERE id='owner'"); + expect(sqlite.prepare('SELECT id FROM deployment_publish_jobs').get()).toBeUndefined(); + } + ); + it('delete-before-admission cannot acquire a missing job', async () => { + sqlite.exec("DELETE FROM projects WHERE id='owner'"); + expect(await admitCloudflareBuild(db, 'job', limits)).toBeNull(); + }); + it('workspace deletion does not erase the job: workspace_id has deliberately never been an FK', async () => { + await admitCloudflareBuild(db, 'job', limits); + sqlite.exec("DELETE FROM workspaces WHERE id='owner'"); + expect( + sqlite.prepare('SELECT executor_instance_id FROM deployment_publish_jobs').get() + ).toEqual({ executor_instance_id: 'job' }); + }); + it('preflights all supported scopes, including terminal-but-stop-pending, and permits after release', async () => { + await admitCloudflareBuild(db, 'job', limits); + sqlite.exec("UPDATE deployment_publish_jobs SET status='succeeded'"); + for (const scope of [{ nodeId: 'owner' }, { projectId: 'owner' }, { environmentId: 'owner' }]) { + await expect(assertNoReservedCloudflareBuilds(db, scope)).rejects.toMatchObject({ + statusCode: 409, + }); + } + await expect( + assertNoReservedCloudflareBuilds(db, { nodeId: 'other' }) + ).resolves.toBeUndefined(); + await releaseCloudflareBuildReservation(db, 'job', 1); + await expect( + assertNoReservedCloudflareBuilds(db, { nodeId: 'owner' }) + ).resolves.toBeUndefined(); + }); + it('maps a wrapped final-mutation conflict to a safe 409 response', async () => { + const app = new Hono<{ Bindings: Env }>(); + app.onError(handleAppError); + app.delete('/resource', () => { + throw new Error('Failed query with private params', { + cause: new Error('D1_ERROR: cloudflare_build_reservation_held: SQLITE_CONSTRAINT'), + }); + }); + const response = await app.request('/resource', { method: 'DELETE' }, {} as Env); + expect(response.status).toBe(409); + expect(await response.text()).not.toContain('private params'); + }); + it('recognizes only the fixed trigger marker through nested D1 causes, with cycle protection', () => { + const cause = new Error('D1_ERROR: cloudflare_build_reservation_held: SQLITE_CONSTRAINT'); + expect( + isCloudflareBuildDeletionConflict(new Error('Failed query: private params', { cause })) + ).toBe(true); + expect(isCloudflareBuildDeletionConflict(new Error('another constraint'))).toBe(false); + const cycle = new Error('cycle'); + cycle.cause = cycle; + expect(isCloudflareBuildDeletionConflict(cycle)).toBe(false); + }); +}); + +describe('bounded reservation escape with real deletion FKs', () => { + const graceMs = 300000; + function ports(): CloudflareBuildPorts { + return { + classMax: 6, + settings: { + resolveSetting: async (name) => + ({ + 'deployments.builderReservationGraceMs': graceMs, + 'deployments.builderDrainLimit': 6, + 'deployments.builderProjectMaxConcurrent': 2, + 'deployments.publishJobDeadlineMs': 1800000, + })[name as string], + }, + builder: { + start: vi.fn(async () => 'started' as const), + stop: vi.fn(async () => { + throw new Error('unreachable DO'); + }), + }, + lifecycle: { recordPublishJobLifecycleEventBestEffort: vi.fn(async () => {}) }, + }; + } + it.each(['building', 'succeeded', 'canceled'])( + 'force releases an unreachable %s reservation after deadline + grace, then parent deletion succeeds', + async (status) => { + await admitCloudflareBuild(db, 'job', limits); + sqlite + .prepare('UPDATE deployment_publish_jobs SET status=?, executor_deadline_at=?') + .run(status, new Date(Date.now() - graceMs - 1000).toISOString()); + const p = ports(); + await drainCloudflareBuilds(createSqliteD1(sqlite), p); + expect(p.builder.stop).not.toHaveBeenCalled(); + expect( + sqlite.prepare('SELECT status, executor_instance_id FROM deployment_publish_jobs').get() + ).toEqual({ + status: status === 'building' ? 'unknown' : status, + executor_instance_id: null, + }); + expect( + sqlite + .prepare('SELECT level,event_type,detail_json FROM deployment_publish_job_events') + .get() + ).toMatchObject({ + level: 'alert', + event_type: 'publish.builder.reservation_force_released', + detail_json: expect.stringContaining('"physicalStopConfirmed":false'), + }); + // A late scoped callback cannot revive or mutate the forced-terminal job. + expect( + await appendDeploymentPublishJobEvent(db, { + publishJobId: 'job', + projectId: 'owner', + environmentId: 'owner', + workspaceId: 'owner', + nodeId: 'owner', + expectedAttempt: 1, + expectedExecutor: 'cloudflare', + expectedExecutorInstanceId: 'job', + eventType: 'publish.job.heartbeat', + message: 'late heartbeat', + status: 'building', + }) + ).toBe(false); + // A second tick cannot produce duplicate alerts or restart the job. + await drainCloudflareBuilds(createSqliteD1(sqlite), p); + expect( + sqlite.prepare('SELECT count(*) AS n FROM deployment_publish_job_events').get() + ).toEqual({ n: 1 }); + sqlite.exec("DELETE FROM nodes WHERE id='owner'"); + expect(sqlite.prepare('SELECT id FROM deployment_publish_jobs').get()).toBeUndefined(); + } + ); + it('retains the reservation and blocks cascading account deletion inside grace despite a failed stop', async () => { + await admitCloudflareBuild(db, 'job', limits); + sqlite + .prepare("UPDATE deployment_publish_jobs SET status='canceled',executor_deadline_at=?") + .run(new Date(Date.now() - graceMs + 60000).toISOString()); + const p = ports(); + await drainCloudflareBuilds(createSqliteD1(sqlite), p); + expect(p.builder.stop).toHaveBeenCalledTimes(1); + expect(() => sqlite.exec("DELETE FROM users WHERE id='owner'")).toThrow( + 'cloudflare_build_reservation_held' + ); + expect(sqlite.prepare('SELECT count(*) AS n FROM deployment_publish_job_events').get()).toEqual( + { n: 0 } + ); + }); + it.each([ + 'attempt=2', + "executor_not_before='replacement'", + "executor_deadline_at='2999-01-01T00:00:00.000Z'", + "executor_instance_id='other'", + ])('a stale expiry candidate cannot release a replacement: %s', async (mutation) => { + await admitCloudflareBuild(db, 'job', limits); + sqlite + .prepare('UPDATE deployment_publish_jobs SET executor_deadline_at=?') + .run(new Date(Date.now() - graceMs - 1000).toISOString()); + const job = await db.query.deploymentPublishJobs.findFirst(); + sqlite.exec(`UPDATE deployment_publish_jobs SET ${mutation}`); + expect(await forceReleaseExpiredCloudflareBuild(db, job!, graceMs)).toBe(false); + expect(() => sqlite.exec("DELETE FROM projects WHERE id='owner'")).toThrow( + 'cloudflare_build_reservation_held' + ); + }); + it('one expiry mutation failure does not suppress the next reserved job', async () => { + await admitCloudflareBuild(db, 'job', limits); + const deadline = new Date(Date.now() - graceMs - 1000).toISOString(); + sqlite + .prepare("UPDATE deployment_publish_jobs SET status='building',executor_deadline_at=?") + .run(deadline); + sqlite + .prepare( + `INSERT INTO deployment_publish_jobs + (id,project_id,environment_id,workspace_id,node_id,requested_by,environment_name,executor,status,executor_instance_id,executor_deadline_at) + VALUES ('job2','owner','owner','owner','owner','owner','production','cloudflare','building','job2',?)` + ) + .run(deadline); + sqlite.exec(`CREATE TRIGGER reject_first_release BEFORE UPDATE ON deployment_publish_jobs + WHEN OLD.id='job' AND NEW.executor_instance_id IS NULL + BEGIN SELECT RAISE(ABORT, 'first mutation unavailable'); END`); + await drainCloudflareBuilds(createSqliteD1(sqlite), ports()); + expect( + sqlite + .prepare('SELECT id FROM deployment_publish_jobs WHERE executor_instance_id IS NOT NULL') + .all() + ).toEqual([{ id: 'job' }]); + expect( + sqlite.prepare("SELECT status FROM deployment_publish_jobs WHERE id='job2'").get() + ).toEqual({ status: 'unknown' }); + }); + it('an alert persistence failure cannot wedge release or prevent later expired candidates', async () => { + await admitCloudflareBuild(db, 'job', limits); + const deadline = new Date(Date.now() - graceMs - 1000).toISOString(); + sqlite.prepare('UPDATE deployment_publish_jobs SET executor_deadline_at=?').run(deadline); + sqlite + .prepare( + `INSERT INTO deployment_publish_jobs + (id,project_id,environment_id,workspace_id,node_id,requested_by,environment_name,executor,status,executor_instance_id,executor_deadline_at) + VALUES ('job2','owner','owner','owner','owner','owner','production','cloudflare','canceled','job2',?)` + ) + .run(deadline); + sqlite.exec(`CREATE TRIGGER reject_alert BEFORE INSERT ON deployment_publish_job_events + BEGIN SELECT RAISE(ABORT, 'journal unavailable'); END`); + await drainCloudflareBuilds(createSqliteD1(sqlite), ports()); + expect( + sqlite + .prepare( + 'SELECT count(*) AS n FROM deployment_publish_jobs WHERE executor_instance_id IS NOT NULL' + ) + .get() + ).toEqual({ n: 0 }); + sqlite.exec("DELETE FROM users WHERE id='owner'"); + expect(sqlite.prepare('SELECT id FROM deployment_publish_jobs').get()).toBeUndefined(); + }); +}); diff --git a/apps/api/tests/unit/services/cloudflare-build-executor.test.ts b/apps/api/tests/unit/services/cloudflare-build-executor.test.ts new file mode 100644 index 0000000000..e87150143f --- /dev/null +++ b/apps/api/tests/unit/services/cloudflare-build-executor.test.ts @@ -0,0 +1,184 @@ +import { + type CloudflareBuildPorts, + dispatchCloudflareBuild, + drainCloudflareBuilds, + releaseCloudflareBuildReservation, +} from '@simple-agent-manager/app-deployment'; +import Database from 'better-sqlite3'; +import { drizzle } from 'drizzle-orm/d1'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import * as schema from '../../../src/db/schema'; +import { createSchemaTables, createSqliteD1 } from '../../helpers/sqlite-d1'; +let sqlite: Database.Database; +let database: D1Database; +let ports: CloudflareBuildPorts; +function seed(id = 'job', project = 'project') { + const now = new Date().toISOString(); + sqlite + .prepare( + `INSERT INTO deployment_publish_jobs(id,project_id,environment_id,workspace_id,node_id,requested_by,environment_name,status,executor,context_shadow,attempt,context_r2_key,context_sha256,created_at,updated_at) VALUES(?,?,'env','ws','node','user','staging','context_ready','cloudflare',0,1,'key','sha',?,?)` + ) + .run(id, project, now, now); +} +function row() { + return sqlite + .prepare( + "SELECT status,executor_instance_id,executor_not_before FROM deployment_publish_jobs WHERE id='job'" + ) + .get(); +} +beforeEach(() => { + sqlite = new Database(':memory:'); + createSchemaTables(sqlite, [schema.deploymentPublishJobs, schema.deploymentPublishJobEvents]); + database = createSqliteD1(sqlite); + ports = { + classMax: 6, + settings: { + resolveSetting: async (name) => + ({ + 'deployments.builderMaxConcurrent': 6, + 'deployments.builderProjectMaxConcurrent': 2, + 'deployments.publishJobDeadlineMs': 1800000, + 'deployments.builderDeadlineMs': 1200000, + 'deployments.builderCapacityBackoffMs': 30000, + 'deployments.builderDrainLimit': 6, + 'deployments.builderReservationGraceMs': 300000, + })[name as string], + }, + builder: { + start: vi.fn(async () => 'started' as const), + stop: vi.fn(async (job, capacity) => { + if (capacity) + await releaseCloudflareBuildReservation( + drizzle(database, { schema }), + job.id, + capacity.attempt, + capacity.retryAt, + capacity.notBefore + ); + }), + }, + lifecycle: { recordPublishJobLifecycleEventBestEffort: vi.fn(async () => {}) }, + }; +}); +afterEach(() => sqlite.close()); +describe('Cloudflare queue orchestration on actual D1 SQL', () => { + it('starts admitted jobs once and respects final capacity', async () => { + seed(); + expect(await dispatchCloudflareBuild(database, ports, 'job')).toBe(true); + expect(await dispatchCloudflareBuild(database, ports, 'job')).toBe(false); + expect(ports.builder.start).toHaveBeenCalledTimes(1); + expect(row()).toMatchObject({ status: 'starting', executor_instance_id: 'job' }); + }); + it('confirms stop then backs off platform capacity without source fallback', async () => { + seed(); + ports.builder.start = vi.fn(async () => 'capacity'); + expect(await dispatchCloudflareBuild(database, ports, 'job')).toBe(false); + expect(ports.builder.stop).toHaveBeenCalledTimes(1); + expect(row()).toMatchObject({ + status: 'context_ready', + executor_instance_id: null, + executor_not_before: expect.any(String), + }); + await drainCloudflareBuilds(database, ports); + expect(ports.builder.start).toHaveBeenCalledTimes(1); + }); + it('preserves cancellation that races admission/startup', async () => { + seed(); + ports.builder.start = vi.fn(async () => { + sqlite.exec("UPDATE deployment_publish_jobs SET status='canceled'"); + return 'capacity'; + }); + await dispatchCloudflareBuild(database, ports, 'job'); + expect(row()).toMatchObject({ status: 'canceled', executor_instance_id: null }); + }); + it('fails noncapacity errors and retains reservations until stop succeeds', async () => { + seed(); + ports.builder.start = vi.fn(async () => { + throw new Error('image unavailable'); + }); + ports.builder.stop = vi.fn(async () => { + throw new Error('stop unavailable'); + }); + await dispatchCloudflareBuild(database, ports, 'job'); + expect(row()).toMatchObject({ status: 'failed', executor_instance_id: 'job' }); + ports.builder.stop = vi.fn(async () => {}); + await drainCloudflareBuilds(database, ports); + expect(row()).toMatchObject({ status: 'failed', executor_instance_id: null }); + }); +}); + +it('cron recovers a reservation whose HTTP caller disappeared before DO kickoff', async () => { + seed(); + sqlite.exec("UPDATE deployment_publish_jobs SET status='starting',executor_instance_id='job'"); + await drainCloudflareBuilds(database, ports); + expect(ports.builder.start).toHaveBeenCalledTimes(1); + expect(row()).toMatchObject({ status: 'starting', executor_instance_id: 'job' }); +}); + +it.each([ + "status='building'", + "status='context_ready',executor_instance_id=NULL", + "status='starting',executor_not_before='2099-01-01T00:00:00.000Z'", +])('stale startup failure cannot fail or stop changed reservation: %s', async (change) => { + seed(); + ports.builder.start = vi.fn(async () => { + sqlite.exec('UPDATE deployment_publish_jobs SET ' + change); + throw new Error('delayed startup failure'); + }); + await dispatchCloudflareBuild(database, ports, 'job'); + expect(ports.builder.stop).not.toHaveBeenCalled(); + expect((row() as { status: string }).status).not.toBe('failed'); + expect(ports.lifecycle.recordPublishJobLifecycleEventBestEffort).not.toHaveBeenCalled(); +}); +it('project-capped backlog cannot hide eligible work behind the drain limit', async () => { + for (const id of ['a-active', 'b-active']) { + seed(id); + sqlite + .prepare( + "UPDATE deployment_publish_jobs SET status='building',executor_instance_id=id WHERE id=?" + ) + .run(id); + } + for (let i = 0; i < 8; i++) seed('c-queued-' + i); + seed('z-other', 'another-project'); + await drainCloudflareBuilds(database, ports); + expect(ports.builder.start).toHaveBeenCalledWith(expect.objectContaining({ id: 'z-other' })); +}); + +it('late capacity result cannot release a same-attempt replacement reservation', async () => { + seed(); + ports.builder.start = vi.fn(async () => { + sqlite.exec( + "UPDATE deployment_publish_jobs SET executor_not_before='2099-01-01T00:00:00.000Z'" + ); + return 'capacity'; + }); + await dispatchCloudflareBuild(database, ports, 'job'); + expect(row()).toEqual({ + status: 'starting', + executor_instance_id: 'job', + executor_not_before: '2099-01-01T00:00:00.000Z', + }); +}); +it('expired or incomplete queue entries cannot consume the eligible drain batch', async () => { + for (let i = 0; i < 8; i++) { + seed('a-bad-' + i, 'bad-' + i); + sqlite + .prepare('UPDATE deployment_publish_jobs SET context_r2_key=NULL WHERE id=?') + .run('a-bad-' + i); + } + for (let i = 0; i < 8; i++) { + seed('b-old-' + i, 'old-' + i); + sqlite + .prepare( + "UPDATE deployment_publish_jobs SET created_at='2000-01-01T00:00:00.000Z' WHERE id=?" + ) + .run('b-old-' + i); + } + seed('z-good', 'good'); + await drainCloudflareBuilds(database, ports); + expect(ports.builder.start).toHaveBeenCalledTimes(1); + expect(ports.builder.start).toHaveBeenCalledWith(expect.objectContaining({ id: 'z-good' })); +}); diff --git a/apps/api/tests/unit/services/deployment-publish-job-hardening.test.ts b/apps/api/tests/unit/services/deployment-publish-job-hardening.test.ts index b0434cd480..9488af12cb 100644 --- a/apps/api/tests/unit/services/deployment-publish-job-hardening.test.ts +++ b/apps/api/tests/unit/services/deployment-publish-job-hardening.test.ts @@ -92,6 +92,75 @@ beforeEach(() => { afterEach(() => sqlite.close()); describe('publish job atomic guards on SQLite', () => { + it.each([ + ['starting', 'builder_start', 'context_ready', 'context_ready'], + ['building', 'compose_build', 'validating', 'compose_config'], + ['recording_release', 'release_submission', 'uploading', 'upload_archive'], + ['uploading', 'artifact_complete', 'uploading', 'artifact_init'], + ['starting', 'builder_start', undefined, 'context_ready'], + ])( + 'atomically rejects backward Cloudflare progress %s/%s to %s/%s', + async (from, step, to, incomingStep) => { + seed(); + sqlite + .prepare("UPDATE deployment_publish_jobs SET executor='cloudflare',status=?,current_step=?") + .run(from, step); + const before = row(); + expect( + await appendDeploymentPublishJobEvent(db(), { + ...event, + status: to, + currentStep: incomingStep, + }) + ).toBe(false); + expect(row()).toEqual(before); + expect( + sqlite.prepare('SELECT count(*) AS n FROM deployment_publish_job_events').get() + ).toEqual({ n: 0 }); + } + ); + it('allows in-order progress, including the export/upload loop for two services', async () => { + seed('job', 'context_ready'); + sqlite + .prepare( + "UPDATE deployment_publish_jobs SET executor='cloudflare',current_step='context_ready'" + ) + .run(); + for (const [status, currentStep] of [ + ['starting', 'builder_start'], + ['starting', 'builder_ready'], + ['validating', 'compose_config'], + ['building', 'compose_build'], + ['uploading', 'artifact_init'], + ['exporting', 'docker_save'], + ['uploading', 'upload_archive'], + ['exporting', 'docker_save'], + ['uploading', 'upload_archive'], + ['uploading', 'artifact_complete'], + ['recording_release', 'release_submission'], + ['succeeded', 'complete'], + ]) { + expect(await appendDeploymentPublishJobEvent(db(), { ...event, status, currentStep })).toBe( + true + ); + expect(row()).toMatchObject({ status, current_step: currentStep }); + } + }); + + it.each([ + { status: undefined, currentStep: null }, + { status: 'constructor', currentStep: undefined }, + { status: 'building', currentStep: '__proto__' }, + { status: 'toString', currentStep: 'compose_build' }, + ])('rejects invalid or clearing Cloudflare progress without throwing: %j', async (incoming) => { + seed(); + sqlite.exec( + "UPDATE deployment_publish_jobs SET executor='cloudflare',current_step='compose_build'" + ); + const before = row(); + expect(await appendDeploymentPublishJobEvent(db(), { ...event, ...incoming })).toBe(false); + expect(row()).toEqual(before); + }); it.each([undefined, 'building'])( 'rejects terminal flag with non-terminal status %s without writes', async (status) => { @@ -364,3 +433,107 @@ describe('publish job atomic guards on SQLite', () => { expect(await release('owner-release')).toBe(true); }); }); + +describe('Cloudflare queue and attempt fences', () => { + it('does not stall queued context_ready jobs but enforces the absolute deadline', async () => { + seed('queued', 'context_ready', recent, old, old); + expect(await failExpiredDeploymentPublishJobs(db(), settings, now)).toHaveLength(0); + expect( + await failExpiredDeploymentPublishJobs(db(), settings, now + settings.deadlineMs) + ).toHaveLength(1); + }); + it('atomically rejects an old attempt without history or state mutations', async () => { + seed(); + sqlite.exec("UPDATE deployment_publish_jobs SET executor='cloudflare'"); + expect( + await appendDeploymentPublishJobEvent(db(), { + ...event, + expectedAttempt: 2, + expectedExecutor: 'cloudflare', + }) + ).toBe(false); + expect(sqlite.prepare('SELECT count(*) AS n FROM deployment_publish_job_events').get()).toEqual( + { n: 0 } + ); + expect( + await appendDeploymentPublishJobEvent(db(), { + ...event, + expectedAttempt: 1, + expectedExecutor: 'cloudflare', + }) + ).toBe(true); + }); +}); + +describe('source collector terminal authority ends at context handoff', () => { + for (const status of [ + 'context_ready', + 'starting', + 'building', + 'uploading', + 'recording_release', + ]) { + it(`rejects delayed source failure in ${status}, allows the builder verdict`, async () => { + seed('job', status); + sqlite + .prepare("UPDATE deployment_publish_jobs SET executor='cloudflare',context_shadow=0") + .run(); + expect( + await appendDeploymentPublishJobEvent(db(), { + ...event, + sourceCollector: true, + status: 'failed', + currentStep: 'source_failed', + terminal: true, + }) + ).toBe(false); + expect(row().status).toBe(status); + expect( + sqlite.prepare('SELECT count(*) AS n FROM deployment_publish_job_events').get() + ).toEqual({ n: 0 }); + expect( + await appendDeploymentPublishJobEvent(db(), { + ...event, + expectedExecutor: 'cloudflare', + status: 'failed', + terminal: true, + }) + ).toBe(true); + }); + } + for (const status of ['queued', 'collecting']) + it(`keeps prehandoff source failure in ${status}`, async () => { + seed('job', status); + sqlite + .prepare("UPDATE deployment_publish_jobs SET executor='cloudflare',context_shadow=0") + .run(); + expect( + await appendDeploymentPublishJobEvent(db(), { + ...event, + sourceCollector: true, + status: 'failed', + terminal: true, + }) + ).toBe(true); + }); + it('retains legacy and shadow source failures', async () => { + for (const [id, executor, shadow] of [ + ['node', 'node', 0], + ['shadow', 'cloudflare', 1], + ] as const) { + seed(id); + sqlite + .prepare('UPDATE deployment_publish_jobs SET executor=?,context_shadow=? WHERE id=?') + .run(executor, shadow, id); + expect( + await appendDeploymentPublishJobEvent(db(), { + ...event, + publishJobId: id, + sourceCollector: true, + status: 'failed', + terminal: true, + }) + ).toBe(true); + } + }); +}); diff --git a/apps/api/tests/unit/services/publish-job-token.test.ts b/apps/api/tests/unit/services/publish-job-token.test.ts new file mode 100644 index 0000000000..2e0b04d724 --- /dev/null +++ b/apps/api/tests/unit/services/publish-job-token.test.ts @@ -0,0 +1,77 @@ +import Database from 'better-sqlite3'; +import { exportPKCS8, exportSPKI, generateKeyPair } from 'jose'; +import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import * as schema from '../../../src/db/schema'; +import type { Env } from '../../../src/env'; +import { verifyCallbackToken } from '../../../src/services/jwt'; +import { + signPublishJobToken, + verifyPublishJobToken, +} from '../../../src/services/publish-job-token'; +import { createSchemaTables, createSqliteD1 } from '../../helpers/sqlite-d1'; +let sqlite: Database.Database; +let env: Env; +let keys: { JWT_PRIVATE_KEY: string; JWT_PUBLIC_KEY: string }; +const claims = { + jobId: 'job', + projectId: 'project', + environmentId: 'env', + agentProfileId: 'profile', + attempt: 1, +}; +beforeAll(async () => { + const pair = await generateKeyPair('RS256', { extractable: true }); + keys = { + JWT_PRIVATE_KEY: await exportPKCS8(pair.privateKey), + JWT_PUBLIC_KEY: await exportSPKI(pair.publicKey), + }; +}); +beforeEach(() => { + sqlite = new Database(':memory:'); + createSchemaTables(sqlite, [schema.deploymentPublishJobs]); + sqlite + .prepare( + `INSERT INTO deployment_publish_jobs(id,project_id,environment_id,workspace_id,node_id,requested_by,environment_name,status,executor,context_shadow,agent_profile_id,attempt) VALUES('job','project','env','sleeping-workspace','sleeping-node','user','staging','building','cloudflare',0,'profile',1)` + ) + .run(); + env = { ...keys, BASE_DOMAIN: 'example.test', DATABASE: createSqliteD1(sqlite) } as Env; +}); +afterEach(() => sqlite.close()); +describe('real signed job callback capability', () => { + it('survives source disappearance but generic callback sinks reject it', async () => { + const token = await signPublishJobToken(env, claims, Date.now() + 60_000); + expect((await verifyPublishJobToken(env, token)).job.workspaceId).toBe('sleeping-workspace'); + await expect(verifyCallbackToken(token, env)).rejects.toMatchObject({ statusCode: 401 }); + }); + for (const mutation of [ + { jobId: 'other' }, + { projectId: 'other' }, + { environmentId: 'other' }, + { agentProfileId: 'other' }, + { attempt: 2 }, + ]) + it(`rejects foreign identity ${JSON.stringify(mutation)} with owner control`, async () => { + await expect( + verifyPublishJobToken( + env, + await signPublishJobToken(env, { ...claims, ...mutation }, Date.now() + 60_000) + ) + ).rejects.toThrow(); + expect( + ( + await verifyPublishJobToken( + env, + await signPublishJobToken(env, claims, Date.now() + 60_000) + ) + ).job.id + ).toBe('job'); + }); + it('revokes terminal jobs and stale attempts', async () => { + const token = await signPublishJobToken(env, claims, Date.now() + 60_000); + sqlite.prepare("UPDATE deployment_publish_jobs SET status='canceled'").run(); + await expect(verifyPublishJobToken(env, token)).rejects.toThrow(); + sqlite.prepare("UPDATE deployment_publish_jobs SET status='building', attempt=2").run(); + await expect(verifyPublishJobToken(env, token)).rejects.toThrow(); + }); +}); diff --git a/apps/api/vitest.config.ts b/apps/api/vitest.config.ts index c72e300d42..4ba720c8bc 100644 --- a/apps/api/vitest.config.ts +++ b/apps/api/vitest.config.ts @@ -13,7 +13,9 @@ export default defineConfig({ }, test: { // Transform this Workers-only dependency so its runtime import uses the test alias. - server: { deps: { inline: ['@cloudflare/workers-oauth-provider'] } }, + server: { + deps: { inline: ['@cloudflare/workers-oauth-provider', /@cloudflare\/containers\//] }, + }, globals: true, setupFiles: ['./tests/setup/project-data-ports.ts', './tests/setup/repo-hosting-ports.ts'], include: ['tests/**/*.test.ts'], diff --git a/apps/api/wrangler.toml b/apps/api/wrangler.toml index bed7b329aa..c7145eed43 100644 --- a/apps/api/wrangler.toml +++ b/apps/api/wrangler.toml @@ -511,3 +511,18 @@ crons = ["* * * * *", "*/5 * * * *", "30 * * * *", "0 3 * * *"] # - CF_AIG_TOKEN (optional — Cloudflare AI Gateway Unified Billing token; enables OpenAI/Anthropic models without separate API keys) # - SMOKE_TEST_AUTH_ENABLED (optional — enables smoke-test token auth for test environments) # - AGENT_SIGN_IN_TRUST (optional — test instances only: JSON trust configuration for agent sign-in through workload identity; see services/agent-sign-in/config.ts) + +# Dedicated per-publish-job DinD build executor (instance sizing resolved at deploy time). +[[containers]] +class_name = "ComposeBuilderContainer" +image = "./Dockerfile.compose-builder" +instance_type = "standard-4" +max_instances = 6 + +[[durable_objects.bindings]] +name = "COMPOSE_BUILDER" +class_name = "ComposeBuilderContainer" + +[[migrations]] +tag = "v23" +new_sqlite_classes = ["ComposeBuilderContainer"] diff --git a/apps/www/src/content/docs/docs/architecture/security.md b/apps/www/src/content/docs/docs/architecture/security.md index 9561364bda..e4f37f4d11 100644 --- a/apps/www/src/content/docs/docs/architecture/security.md +++ b/apps/www/src/content/docs/docs/architecture/security.md @@ -490,6 +490,21 @@ Escaping a devcontainer reaches only the user's own VM, whether the escape comes Ways to run nested containers without `privileged`, such as a user-namespaced container runtime, are welcome improvements, provided Docker, Compose and Testcontainers keep working inside workspaces. +## Application Build Executor + +Cloudflare application builds run arbitrary Dockerfile `RUN` code as root inside Docker-in-Docker with host build networking. Builds have unrestricted internet access, like VM workspaces; package repositories and presigned R2 transfers are reached directly without an outbound proxy, host allowlist or HTTPS interception CA. This is the deployment-build egress decision approved on November 15, 2026. Network access is not a security boundary for build code. + +Each publish job gets its own microVM, identified by `publishJobId`, with no reuse across jobs or projects. SAM delivers no platform cloud credentials, signing keys, workspace callback token, or runtime deployment secret values to that guest. The Go supervisor holds the job callback token in memory; it is not placed in process arguments, environment variables or files. Arbitrary root code shares the guest with that supervisor, so assume it can obtain and use the authority of that one job. It can also use the job's short-lived presigned object URLs. It has no authority over other jobs, projects, credential endpoints or Worker bindings. + +The enforcing paths are: + +- `apps/api/src/durable-objects/compose-builder-container.ts` enables direct internet access, passes only nonsecret timing budgets through the environment, checks the builder version, and sends a single launch payload through the SDK's private container transport. It never calls the guest control port after launch acceptance, because root build code could bind that port later. Its persisted deadline alarm destroys the microVM before recording the timeout in D1 and retries failed destruction. +- `packages/vm-agent/cmd/sam-builder/main.go` closes the bootstrap HTTP listener before starting the build. `packages/vm-agent/internal/builder/` keeps the callback token in supervisor memory, verifies context size and SHA-256 before extraction, and rejects HTTP redirects for authenticated control-plane and presigned transfers. +- `apps/api/src/services/jwt.ts` verifies the publish-job token's signature, issuer, audience, expiration and claims. `apps/api/src/services/publish-job-token.ts` binds it to the current nonterminal job row, project, environment, profile, executor and attempt on every authorized callback. Completion, cancellation or an attempt change revokes callback authority immediately. Generic workspace/node callback sinks reject this scope. +- The existing publish callback routes fence artifact keys, event updates and release submission to that job and attempt. Presigned URLs carry only the specific context download or image upload authority until their expiry; a terminal job cannot obtain new URLs, but an already-issued URL remains usable until it expires. + +The build microVM is the isolation boundary. Root execution and open egress are intentional capabilities; the restrictions protect control-plane and cross-project authority while allowing ordinary Docker builds. Deployment target nodes retain their separate restricted Compose policy described above. + ## Security Best Practices - **Rotate keys quarterly** — regenerate JWT and encryption keys diff --git a/apps/www/src/content/docs/docs/guides/app-deployments.md b/apps/www/src/content/docs/docs/guides/app-deployments.md index 9f65cce96b..96f6f6d068 100644 --- a/apps/www/src/content/docs/docs/guides/app-deployments.md +++ b/apps/www/src/content/docs/docs/guides/app-deployments.md @@ -17,8 +17,7 @@ to it, and an agent ships your app there when you ask. You don't run Docker or t **Nobody yet** (turn it on later from the environment). Select **Create environment**. 4. On the environment's page, select **Ask an agent to deploy**. A new chat opens with the request already written; pick the profile and send it. You can also just ask in any chat, for example - "deploy this to staging". Pick a profile that runs on a VM (**Cloud VM**): an - [Instant](/docs/guides/instant-sessions/) chat can't deploy yet, and is told so. + "deploy this to staging". Both **Cloud VM** and [Instant](/docs/guides/instant-sessions/) chats can publish. 5. Watch **Recent deploys**: the newest version lists the steps the server reports as it goes. When it's **Live**, select **Open app**. @@ -73,14 +72,16 @@ Agents can discover this whole flow at runtime by calling the `deployments_read` Publishing is a two-step, asynchronous flow: -1. `deployments_write` with `method: "publish"` (`environment`, optional `reference` and `workingDir`) starts a build/publish job on the SAM VM and immediately returns a durable `publishJobId`. The job builds the workspace's Docker Compose stack, uploads built service images as scoped artifacts, and records the release server-side. Agents never run docker or registry commands and never receive registry credentials. +1. `deployments_write` with `method: "publish"` (`environment`, optional `reference` and `workingDir`) starts a build/publish job and immediately returns a durable `publishJobId`. The job builds the workspace's Docker Compose stack, uploads built service images as scoped artifacts, and records the release server-side. Agents never run docker or registry commands and never receive registry credentials. 2. `deployments_read` with `method: "publish_status"` and the `publishJobId` reports progress. Poll it until the status is terminal — `succeeded`, `failed`, `canceled`, or `unknown` — rather than retrying `deployments_write` method `publish` blindly. To stop a running build, call `deployments_write` with `method: "cancel_publish"` and `publishJobId` (also callable as `cancel_publish(publishJobId)`). It uses the same project and requesting-workspace scope as `deployments_read` method `publish_status`. Cancellation is durable even if the build machine is unreachable. Terminal jobs stay unchanged. A release already recorded before cancellation continues deploying; cancellation does not roll it back. A heartbeat-capable job whose executor stops sending heartbeats and progress events fails with `errorCode: stalled`; a job that exceeds its overall time budget fails with `errorCode: deadline_exceeded`. Both are retryable. Inspect the recent events before starting a new job. The default silence threshold is five minutes and the overall deadline is thirty minutes; the scheduled sweep detects expiry on its next tick. Healthy builds and uploads may be silent while executor heartbeats continue. Older VM agents without heartbeats, and executors lost before their first successful heartbeat, are bounded by the overall deadline only. The VM heartbeat interval defaults to one minute (`DEPLOY_PUBLISH_HEARTBEAT_INTERVAL`); keep any overridden heartbeat interval well below the stall threshold. The API enforces a minimum stall threshold of 150 seconds, covering two default heartbeat intervals plus callback grace. The API deadline includes admission and callback margin beyond the VM’s default twenty-minute build/publish timeout. If overriding the VM timeout, increase the API deadline accordingly. Installation admins can change these in **Admin → Settings** (`deployments.publishJobStallMs` and `deployments.publishJobDeadlineMs`). -Publishing currently requires a **VM session**. Instant sessions receive “Deploying from Instant sessions isn't available yet; use a VM session” before any build job is created. +Instant sessions build in a dedicated Cloudflare Container. VM sessions build on their source node by default; installation admins can select Cloudflare in **Admin → Settings → deployments.buildExecutor**. Keep the VM executor at `node` until a staging VM trial verifies a served release and unchanged source build/save counters. That VM validation remains pending; the Instant path has been verified. An explicit Cloudflare selection never silently falls back to the source node. If the source agent lacks collection support, restart the workspace to upgrade it. + +For Cloudflare builds, keep the source session awake while SAM collects and verifies its context. Once the job reports `context_ready` (or a later build step), the source can sleep: the independent builder owns the job. Capacity-limited builds queue, and SAM retries admission automatically. Cancellation and the hard builder deadline stop the dedicated container. Confirmed stops also remove the builder’s deadline schedule and native alarm, so completed builds do not retain a wake at their former deadline. The default builder deadline is twenty minutes after first admission, capped by the overall publish-job deadline. A queued job does not need executor heartbeats. After a successful publish, agents can verify runtime health with `deployments_read` (`method: "logs"`). @@ -274,14 +275,34 @@ of scope for this version. Updated VM agents include `publishJobId` and `attempt` in release callbacks. SAM accepts a release only while its job is non-terminal, the attempt matches, and no release is linked. Duplicate, canceled, expired, or stale submissions return HTTP 409 and create no release. Terminal jobs reject later event updates. During rollout, older agents that omit `publishJobId` retain the legacy release behavior without this fence; older agents without the cancel endpoint may continue building locally after the control plane marks their job canceled. Refresh VM agents to obtain the full guarantee. -## Portable build contexts (executor preparation) +## Portable build contexts + +The authenticated node system-info response includes optional `publishExecution` +diagnostics on updated agents: a process incarnation and monotonically increasing +Compose-build and Docker-save execution-attempt counts. Failed attempts count too. +These snapshots are uncached. To verify remote execution, compare snapshots from +the same source node, agent version, and process incarnation before and after its +publish job. An unchanged count confirms that the vm-agent publish path attempted +no source build or save during that interval. A restart, missing fields, or an +increased count cannot establish that proof. These counters do not observe other +host processes; older agents omit them and remain compatible. -SAM includes an internal context collector for future Cloudflare build execution. Publishing still uses the VM node executor; Instant publishing remains unavailable until the remote executor ships. This feature applies to application deployments, not SAM installation or self-hosting builds. +Cloudflare builds use a portable context collected from the calling session. This applies to application deployments; deployment targets remain VMs. It does not build SAM installation or self-hosting releases. + +Cloudflare build failures currently show a generic error without the failing Dockerfile step or detailed build output. Adding a bounded, redacted build-output tail is tracked in SAM idea `01M7HDK9DV8G2JPBK1KTVNY6JN` as the first follow-up after this executor ships. VM sessions using the default node executor retain their existing build error details. The collector uses Compose discovery, overrides, and server-supplied non-secret interpolation config. It creates one `tar.zst` bundle with the original relative layout of local build contexts, Dockerfiles, and Compose files. Docker ignore filtering is conservative: if either the context `.dockerignore` or the Dockerfile-specific ignore rules include a file, the bundle retains it. Runtime `env_file`, Compose secret files, and interpolation dotenv files become empty placeholders, including filesystem aliases. Ordinary Compose config files retain their contents. Supply build interpolation values through SAM deployment config; runtime secrets cannot be used in image/build fields. Remote/Git contexts, non-local additional contexts, inputs outside the selected working directory, escaping symlinks, and over-limit bundles fail before upload. VM collection reads the devcontainer volume; Instant collection reads `/workspaces` directly without Docker. The source directory is held open from its trusted runtime base, and discovery, configuration, ignore rules, traversal and payload reads stay relative to that directory handle so workspace path changes cannot redirect collection outside it. Legacy agents return an unsupported-capability result and require a workspace restart to obtain the current agent. -The API signs short-lived PUTs for server-derived `compose-build-contexts/{project}/{environment}/{job}/{attempt}.tar.zst` keys. Completion checks R2 HEAD size and the recorded SHA-256 metadata, then atomically records `context_ready` and timing history. This records the source's digest; it does not independently hash the object on the API Worker. The future builder must hash downloaded bytes against that digest before extraction. No build is started by context completion in this phase. An installation admin can temporarily enable `deployments.buildContextCollectionMode=shadow` to verify collection through the normal publish call. The default is `off`. Shadow collection is accepted asynchronously in a separate internal job, cannot submit or link a release, and is hidden from publish status, project events, and publish failure counts. The existing node build and Instant early gate do not wait for it or depend on its success. Successful probes record `context_ready` and then terminalize as `succeeded`; stalled probes use the existing deadline sweep. +The API signs short-lived PUTs for server-derived `compose-build-contexts/{project}/{environment}/{job}/{attempt}.tar.zst` keys. Completion checks R2 HEAD size and the recorded SHA-256 metadata, then atomically records `context_ready` and timing history. This records the source's digest; it does not independently hash the object on the API Worker. The builder independently checks the downloaded byte count and SHA-256 before safe extraction. Context completion queues the job for atomic admission (at most two builds per project and six across the installation, also bounded by the deployed class capacity). An installation admin can temporarily enable `deployments.buildContextCollectionMode=shadow` to verify collection through the normal publish call. The default is `off`. Shadow collection is accepted asynchronously in a separate internal job, cannot submit or link a release, and is hidden from publish status, project events, and publish failure counts. Node builds do not wait for shadow collection or depend on its success. Shadow mode applies only to the node execution path. Successful probes record `context_ready` and then terminalize as `succeeded`; stalled probes use the existing deadline sweep. + +Bundles for active jobs are retained. Abandoned and terminal bundles expire through the existing daily Compose artifact cleanup (48 hours by default). After a builder releases its reservation through confirmed stop or the deadline-plus-grace escape, the original source-node delete cascade can remove the job; its orphaned bundle becomes eligible after retention. + +Cloudflare builders start cold with no shared layer cache. The initial instance is `standard-4` (4 vCPU, 12 GiB memory, 20 GB ephemeral disk), as measured in the deployment-build spike. Context, pulled images, build layers and exported archives share that disk. For larger workloads, use a VM session with the node executor, or reduce the context and image sizes. Builds target Linux amd64. An independent hard deadline attempts to stop the builder even if the control plane cannot read the job. If shutdown cannot be confirmed, the deadline-plus-grace escape below bounds reservation retention. + +Builds have unrestricted internet access, like VM workspaces, so Dockerfile `RUN` steps can install packages from public repositories. Context downloads and image uploads use direct, short-lived presigned URLs. Arbitrary build steps run as root with host networking inside a dedicated microVM. The microVM receives only one job's callback authority and object transfers; SAM does not supply platform credentials or runtime secret values. See the [build trust model](/docs/architecture/security/#application-build-executor). + +A running Cloudflare build normally retains its capacity reservation until its builder stops, including after cancellation. Deleting its source node, deployment environment, or project returns a conflict until that reservation is released. Sleeping the source remains supported after context acceptance. -Bundles for active jobs are retained. Abandoned and terminal bundles expire through the existing daily Compose artifact cleanup (48 hours by default). Source `node_id` and its original delete cascade remain unchanged: deleting the source node removes the job, and its orphaned bundle becomes eligible after retention. +If a Cloudflare builder cannot confirm shutdown, deletion may briefly report that a build is still stopping. After its build deadline plus the shutdown grace period (five minutes by default), SAM releases the reservation and records an alert. An unfinished job becomes `unknown`. This lets deletion proceed; it does not confirm that the builder stopped, and platform capacity may remain occupied until Cloudflare reclaims it. Operators can tune `deployments.builderReservationGraceMs` in Admin settings. diff --git a/apps/www/src/content/docs/docs/guides/instant-sessions.md b/apps/www/src/content/docs/docs/guides/instant-sessions.md index 68b87f9d3a..5b20d8dd88 100644 --- a/apps/www/src/content/docs/docs/guides/instant-sessions.md +++ b/apps/www/src/content/docs/docs/guides/instant-sessions.md @@ -44,7 +44,7 @@ The practical trade: an Instant session needs **no cloud provider credential**, | Survives runtime teardown | Yes — via snapshot restore, see below | Yes — via snapshot and replacement VM restore | | [Resource history](/docs/guides/session-resources/) | No — the **Resources** panel stays empty | Yes — CPU, memory, I/O and OOM events are retained | -Instant is the right choice for conversation, planning, code reading, and focused edits. Reach for a VM when the agent has to build your stack, run your test suite, start services, or use Docker. +Instant is the right choice for conversation, planning, code reading, and focused edits. Reach for a VM when the agent needs to build or test locally, start services, or use Docker. Instant can [publish a Compose application](/docs/guides/app-deployments/) through a separate Cloudflare builder. `git` and `gh` in an Instant session are signed in to GitHub for your repository, and SAM renews that sign-in as it expires, so an agent can still push and open a pull request after the diff --git a/apps/www/src/content/docs/docs/guides/self-hosting.mdx b/apps/www/src/content/docs/docs/guides/self-hosting.mdx index 635cf2e7b0..e993da7793 100644 --- a/apps/www/src/content/docs/docs/guides/self-hosting.mdx +++ b/apps/www/src/content/docs/docs/guides/self-hosting.mdx @@ -888,3 +888,9 @@ and [observability pricing](https://developers.cloudflare.com/observability/pric choosing ongoing sampling. The generated configuration redacts query strings from observability URLs because callback and terminal URLs can contain credentials. Traces can still include URL paths and database statement metadata; restrict access to observability data as you would for production logs. + +### Application deployment builds + +Instant sessions publish applications through a dedicated Cloudflare Container build executor. Cloudflare Containers are already part of SAM's supported setup, so this adds no separate cloud account or manual secret prerequisite. Deployment targets remain VMs. VM sessions retain the node executor by default; keep `deployments.buildExecutor=node` in **Admin → Settings** until a staging VM trial verifies a served release with unchanged source build/save counters. VM publishing through Cloudflare remains unverified. `DEPLOY_BUILDER_INSTANCE_TYPE` and `DEPLOY_BUILDER_MAX_INSTANCES` are deployment-time sizing controls; see the [configuration reference](/docs/reference/configuration/#cloudflare-application-build-executor). + +The builder runs one job per ephemeral container and can execute arbitrary Dockerfile steps as root inside DinD with host build networking and unrestricted internet access, just like VM workspaces. Context and image transfers use direct presigned URLs; no outbound proxy or HTTPS interception CA is installed. It receives no user or installation credentials, runtime secret values or workspace token. Its callback token stays in the Go supervisor's memory and authorizes only one job and attempt until that job's deadline or terminal state. Treat arbitrary root code as having that job's authority. The bootstrap listener closes before build steps run, and a durable alarm attempts to destroy the microVM at the hard deadline, independent of source-session liveness. If shutdown cannot be confirmed, cron force-releases the reservation after the stored deadline plus `deployments.builderReservationGraceMs` (five minutes by default), marks unfinished jobs `unknown` and records an alert. This permits deletion and new admissions without claiming physical shutdown; Cloudflare capacity can remain occupied until reclaimed. See the [build trust model](/docs/architecture/security/#application-build-executor) for the enforcing code paths. diff --git a/apps/www/src/content/docs/docs/reference/configuration.md b/apps/www/src/content/docs/docs/reference/configuration.md index 9bb3364f68..d2ce258257 100644 --- a/apps/www/src/content/docs/docs/reference/configuration.md +++ b/apps/www/src/content/docs/docs/reference/configuration.md @@ -2044,9 +2044,40 @@ Installation admins edit these at **Admin → Settings**. They use the existing | `deployments.buildContextStartTimeoutMs` | 10,000 | Bounds control-plane wait for source collection acceptance | | `deployments.buildContextMaxBytes` | 2 GiB | Maximum raw tar (including headers) and compressed bundle bytes | | `deployments.buildContextCollectTimeoutMs` | 120,000 | Source collection deadline | -| `deployments.buildContextUploadTtlSeconds` | 300 | Presigned upload URL lifetime | +| `deployments.buildContextUploadTtlSeconds` | 300 | Presigned upload/download URL lifetime | | `deployments.buildContextRetentionHours` | 48 | Minimum age before abandoned/terminal bundles are deleted | | `deployments.buildContextCleanupBudgetMs` | 10,000 | Work budget per daily cleanup pass | | `deployments.buildContextCleanupPageSize` | 250 | R2 listing page size; a persisted cursor resumes remaining pages | Collection has no file-count cutoff. For a 100,000-file context near 1.5 GiB, tar headers add at least 49 MiB, plus filename/padding metadata. At 50 MiB/s the payload alone needs about 31 seconds to collect and another 31 seconds to upload; filesystem traversal, compression, and network conditions add time. Collection stops at its deadline rather than repeatedly processing a fixed batch. Phase timings are stored in publish-job events. The source request retains the existing overall VM publish timeout (20 minutes by default) and emits publish heartbeats throughout collection/upload. + +## Cloudflare application build executor + +Edit runtime controls in **Admin → Settings**. Instant sessions always use Cloudflare; `deployments.buildExecutor` selects the VM-session executor. These controls are independent of the default-off context shadow probe. Keep the VM setting at `node` until staging validates Cloudflare publishing from a VM with unchanged source build/save counters and a served release; that validation remains pending. + +| Runtime setting | Default | Meaning | +| ----------------------------------------- | --------- | --------------------------------------------------------------------------------------------------- | +| `deployments.buildExecutor` | `node` | VM build executor (`node` or `cloudflare`); explicit Cloudflare selection never silently falls back | +| `deployments.builderMaxConcurrent` | 6 | Platform reservations, clamped to the deployed class capacity; maximum 6 | +| `deployments.builderProjectMaxConcurrent` | 2 | Per-project reservations; maximum 2 | +| `deployments.builderReservationGraceMs` | 300,000 | Grace after the stored builder deadline before cron force-releases unconfirmed reservations with an alert; active jobs become unknown, and physical shutdown may remain unconfirmed | +| `deployments.builderDeadlineMs` | 1,200,000 | Absolute deadline after first admission; also capped by the overall publish-job deadline | +| `deployments.builderCapacityBackoffMs` | 30,000 | Delay before retrying platform capacity errors | +| `deployments.builderDrainLimit` | 6 | Maximum queued jobs considered per cron tick | +| `deployments.builderDaemonReadyTimeoutMs` | 60,000 | DinD readiness deadline | +| `deployments.publishCallbackMaxBodyBytes` | 1,048,576 | Maximum actual JSON bytes for authenticated publish events, image artifacts and release callbacks, for source and builder tokens. | +| `deployments.builderCallbackTimeoutMs` | 30,000 | Control-plane HTTP timeout; also controls bootstrap HTTP shutdown | +| `deployments.builderCallbackAttempts` | 3 | Maximum attempts for retryable callbacks | +| `deployments.builderCallbackRetryDelayMs` | 5,000 | Delay between retryable callbacks | +| `deployments.builderHeartbeatIntervalMs` | 15,000 | Builder liveness callback interval | + +Deployment topology is configured through GitHub Environment variables: + +| Variable | Default | Meaning | +| ------------------------------ | ------------ | ---------------------------------------------------------------------------- | +| `DEPLOY_BUILDER_INSTANCE_TYPE` | `standard-4` | Cloudflare Container instance type; applies on deployment | +| `DEPLOY_BUILDER_MAX_INSTANCES` | 6 | `ComposeBuilderContainer` class capacity; runtime admission never exceeds it | + +The deploy generator mirrors actual class capacity into the Worker binding `DEPLOY_BUILDER_CLASS_MAX_INSTANCES`; do not set that binding independently. Builder images contain Docker, Compose and `sam-builder`; no installation or user credentials are baked into them. Each job receives only a job-and-attempt callback token and short-lived presigned URLs for its context and image keys. The control plane checks the builder against `VM_AGENT_REQUIRED_VERSION`, when configured, before accepting a job. + +Application builders have unrestricted internet egress. Package installation in Dockerfile `RUN` steps and direct presigned object transfers use normal TLS trust; there is no builder host allowlist, outbound proxy, or interception CA setting. Isolation relies on the dedicated microVM, one-job callback authority, and hard deadline. See the [security architecture](/docs/architecture/security/#application-build-executor). diff --git a/packages/app-deployment/src/build-context-state.ts b/packages/app-deployment/src/build-context-state.ts index 82b4e6f62b..e5ddc151b0 100644 --- a/packages/app-deployment/src/build-context-state.ts +++ b/packages/app-deployment/src/build-context-state.ts @@ -1,9 +1,10 @@ import { ulid } from '@simple-agent-manager/worker-core'; import * as schema from '@simple-agent-manager/worker-core/schema'; -import { and, eq, sql } from 'drizzle-orm'; +import { and, eq, isNotNull, notInArray, or, sql } from 'drizzle-orm'; import type { drizzle } from 'drizzle-orm/d1'; import { BUILD_CONTEXT_PREFIX } from './build-context-defaults'; +import { PUBLISH_JOB_TERMINAL_STATUSES } from './deployment-publish-jobs'; type Db = ReturnType>; export interface BuildContextOwner { @@ -18,6 +19,7 @@ export interface BuildContextDescriptor { sizeBytes: number; sha256: string; durationMs?: number; + projectName?: string; } export function buildContextKey(owner: BuildContextOwner): string { const parts = [owner.projectId, owner.environmentId, owner.id]; @@ -71,7 +73,8 @@ export async function completeBuildContext( eq(j.status, 'collecting'), eq(j.contextR2Key, buildContextKey(owner)), eq(j.contextBytes, descriptor.sizeBytes), - eq(j.contextSha256, descriptor.sha256) + eq(j.contextSha256, descriptor.sha256), + sql`coalesce(${j.contextProjectName}, '') = ${descriptor.projectName ?? ''}` ) ); } @@ -126,11 +129,12 @@ async function transitionContext( update.contextR2Key = buildContextKey(owner); update.contextBytes = descriptor.sizeBytes; update.contextSha256 = descriptor.sha256; + update.contextProjectName = descriptor.projectName ?? null; } else update.queuedAt = now; const [, rows] = await db.batch([history, db.update(j).set(update).where(predicate).returning()]); if (rows[0]) return { ...rows[0], replayed: false }; // The response can be lost after this transaction commits. Recognize only - // the exact receipt in the operation's destination state; never revive a + // the exact receipt in the operation's destination state, or its admitted forward state; never revive a // canceled/terminal job or reissue an upload after completion. Replays do // not update timestamps or insert duplicate history. const [receipt] = await db @@ -139,10 +143,19 @@ async function transitionContext( .where( and( ownerPredicate(owner), - eq(j.status, status), + status === 'context_ready' + ? or( + eq(j.status, status), + and( + isNotNull(j.executorInstanceId), + notInArray(j.status, [...PUBLISH_JOB_TERMINAL_STATUSES]) + ) + ) + : eq(j.status, status), eq(j.contextR2Key, buildContextKey(owner)), eq(j.contextBytes, descriptor.sizeBytes), - eq(j.contextSha256, descriptor.sha256) + eq(j.contextSha256, descriptor.sha256), + sql`coalesce(${j.contextProjectName}, '') = ${descriptor.projectName ?? ''}` ) ) .limit(1); diff --git a/packages/app-deployment/src/build-context-upload.ts b/packages/app-deployment/src/build-context-upload.ts index 2621d329c9..94c0e8b47c 100644 --- a/packages/app-deployment/src/build-context-upload.ts +++ b/packages/app-deployment/src/build-context-upload.ts @@ -1,4 +1,4 @@ -import { PutObjectCommand } from '@aws-sdk/client-s3'; +import { GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3'; import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; import type { BuildContextDescriptor, BuildContextOwner } from './build-context-state'; @@ -42,3 +42,11 @@ export async function verifyBuildContextObject( head.customMetadata?.sha256 === descriptor.sha256 ); } + +export async function createBuildContextDownload(env: Env, r2Key: string, expiresIn: number) { + return getSignedUrl( + getS3Client(env, 'WHEN_REQUIRED'), + new GetObjectCommand({ Bucket: env.R2_BUCKET_NAME, Key: r2Key }), + { expiresIn } + ); +} diff --git a/packages/app-deployment/src/cloudflare-build-admission.ts b/packages/app-deployment/src/cloudflare-build-admission.ts new file mode 100644 index 0000000000..ccd71eb3ca --- /dev/null +++ b/packages/app-deployment/src/cloudflare-build-admission.ts @@ -0,0 +1,185 @@ +import { errors } from '@simple-agent-manager/worker-core'; +import * as schema from '@simple-agent-manager/worker-core/schema'; +import { and, eq, isNotNull, isNull, lte, or, sql } from 'drizzle-orm'; +import type { drizzle } from 'drizzle-orm/d1'; + +import { PUBLISH_JOB_TERMINAL_STATUSES } from './deployment-publish-jobs'; + +type Db = ReturnType>; + +/** Repair only an already owned, live reservation. Do not readmit, acquire a + * second slot, extend a deadline, or revive canceled/advanced execution. */ +export async function recoverReservedCloudflareBuild(db: Db, jobId: string, attempt: number) { + const j = schema.deploymentPublishJobs; + const now = new Date().toISOString(); + const [job] = await db + .update(j) + .set({ status: 'starting', currentStep: 'builder_start', updatedAt: now, lastHeartbeatAt: now }) + .where( + and( + eq(j.id, jobId), + eq(j.attempt, attempt), + eq(j.executor, 'cloudflare'), + eq(j.contextShadow, false), + eq(j.status, 'context_ready'), + eq(j.executorInstanceId, jobId), + sql`${j.executorDeadlineAt} > ${now}` + ) + ) + .returning(); + return job ?? null; +} +export const DEFAULT_DEPLOY_BUILDER_MAX_CONCURRENT = 6; +export const DEFAULT_DEPLOY_BUILDER_PROJECT_MAX_CONCURRENT = 2; +export const DEFAULT_DEPLOY_BUILDER_CAPACITY_BACKOFF_MS = 30_000; +export const DEFAULT_DEPLOY_BUILDER_DRAIN_LIMIT = 6; +export const DEFAULT_DEPLOY_BUILDER_DEADLINE_MS = 20 * 60_000; +export const DEFAULT_DEPLOY_BUILDER_RESERVATION_GRACE_MS = 5 * 60_000; + +/** Reservation ownership outlives a terminal verdict until stop is confirmed + * or the exceptional deadline-plus-grace escape revokes it. + * Both caps are checked in the final mutation, never a preceding SELECT. */ +export async function admitCloudflareBuild( + db: Db, + jobId: string, + limits: { + platform: number; + project: number; + classMax: number; + deadlineMs: number; + buildTimeoutMs?: number; + }, + nowMs = Date.now() +) { + const j = schema.deploymentPublishJobs; + const platform = Math.min(limits.platform, limits.classMax); + if ( + ![ + platform, + limits.project, + limits.deadlineMs, + limits.buildTimeoutMs ?? DEFAULT_DEPLOY_BUILDER_DEADLINE_MS, + ].every((n) => Number.isSafeInteger(n) && n > 0) + ) + throw new Error('Invalid Cloudflare build admission limits'); + const now = new Date(nowMs).toISOString(); + const rows = await db + .update(j) + .set({ + executorInstanceId: jobId, + executorDeadlineAt: sql`coalesce(${j.executorDeadlineAt}, min(strftime('%Y-%m-%dT%H:%M:%fZ', ${j.createdAt}, ${'+' + limits.deadlineMs / 1000 + ' seconds'}), ${new Date(nowMs + (limits.buildTimeoutMs ?? DEFAULT_DEPLOY_BUILDER_DEADLINE_MS)).toISOString()}))`, + status: 'starting', + currentStep: 'builder_start', + updatedAt: now, + lastHeartbeatAt: now, + }) + .where( + and( + eq(j.id, jobId), + eq(j.executor, 'cloudflare'), + eq(j.contextShadow, false), + eq(j.status, 'context_ready'), + isNull(j.executorInstanceId), + isNotNull(j.contextR2Key), + isNotNull(j.contextSha256), + or(isNull(j.executorNotBefore), lte(j.executorNotBefore, now)), + sql`${j.createdAt} > ${new Date(nowMs - limits.deadlineMs).toISOString()}`, + sql`(SELECT count(*) FROM deployment_publish_jobs AS active WHERE active.executor = 'cloudflare' AND active.executor_instance_id IS NOT NULL) < ${platform}`, + sql`(SELECT count(*) FROM deployment_publish_jobs AS active WHERE active.executor = 'cloudflare' AND active.executor_instance_id IS NOT NULL AND active.project_id = ${j.projectId}) < ${limits.project}` + ) + ) + .returning(); + return rows[0] ?? null; +} + +/** Call only after the DO confirms stop/no running process. Cancellation that + * raced startup remains terminal; only a still-starting job may be requeued. */ +export async function releaseCloudflareBuildReservation( + db: Db, + jobId: string, + attempt: number, + retryAt?: number, + expectedEpoch?: string | null +) { + const j = schema.deploymentPublishJobs; + return db + .update(j) + .set({ + executorInstanceId: null, + ...(retryAt === undefined + ? {} + : { + status: sql`CASE WHEN ${j.status} = 'starting' THEN 'context_ready' ELSE ${j.status} END`, + currentStep: sql`CASE WHEN ${j.status} = 'starting' THEN 'capacity_backoff' ELSE ${j.currentStep} END`, + executorNotBefore: new Date( + Math.max(retryAt, expectedEpoch ? Date.parse(expectedEpoch) + 1 : 0) + ).toISOString(), + }), + }) + .where( + and( + eq(j.id, jobId), + eq(j.attempt, attempt), + expectedEpoch !== undefined ? sql`${j.executorNotBefore} IS ${expectedEpoch}` : undefined, + expectedEpoch !== undefined ? eq(j.executorInstanceId, jobId) : undefined, + retryAt !== undefined + ? or( + eq(j.status, 'starting'), + sql`${j.status} IN (${sql.join( + [...PUBLISH_JOB_TERMINAL_STATUSES].map((s) => sql`${s}`), + sql`,` + )})` + ) + : undefined, + retryAt === undefined + ? sql`${j.status} IN (${sql.join( + [...PUBLISH_JOB_TERMINAL_STATUSES].map((s) => sql`${s}`), + sql`,` + )})` + : undefined + ) + ) + .returning(); +} + +/** Friendly preflight; the deletion trigger remains the atomic race fence. */ +export async function assertNoReservedCloudflareBuilds( + db: Db, + scope: { nodeId: string } | { projectId: string } | { environmentId: string } +): Promise { + const j = schema.deploymentPublishJobs; + const predicate = + 'nodeId' in scope + ? eq(j.nodeId, scope.nodeId) + : 'projectId' in scope + ? eq(j.projectId, scope.projectId) + : eq(j.environmentId, scope.environmentId); + const [reserved] = await db + .select({ id: j.id }) + .from(j) + .where( + and( + predicate, + eq(j.executor, 'cloudflare'), + eq(j.contextShadow, false), + isNotNull(j.executorInstanceId) + ) + ) + .limit(1); + if (reserved) throw errors.conflict(CLOUDFLARE_BUILD_DELETION_CONFLICT); +} + +export const CLOUDFLARE_BUILD_DELETION_CONFLICT = + 'A Cloudflare build is still stopping or running. Wait for it to stop before deleting this resource.'; + +/** D1/Drizzle wrap SQLite trigger errors in causes. Match only our fixed marker. */ +export function isCloudflareBuildDeletionConflict(error: unknown): boolean { + let current: unknown = error; + const seen = new Set(); + while (current instanceof Error && !seen.has(current)) { + seen.add(current); + if (current.message.includes('cloudflare_build_reservation_held')) return true; + current = current.cause; + } + return false; +} diff --git a/packages/app-deployment/src/cloudflare-build-executor.ts b/packages/app-deployment/src/cloudflare-build-executor.ts new file mode 100644 index 0000000000..5fbef1fc9b --- /dev/null +++ b/packages/app-deployment/src/cloudflare-build-executor.ts @@ -0,0 +1,238 @@ +import { log } from '@simple-agent-manager/worker-core'; +import * as schema from '@simple-agent-manager/worker-core/schema'; +import { and, asc, eq, inArray, isNotNull, isNull, lte, or, sql } from 'drizzle-orm'; +import { drizzle } from 'drizzle-orm/d1'; + +import { + admitCloudflareBuild, + releaseCloudflareBuildReservation, +} from './cloudflare-build-admission'; +import { forceReleaseExpiredCloudflareBuild } from './cloudflare-build-reservation-expiry'; +import { + appendDeploymentPublishJobEvent, + PUBLISH_JOB_TERMINAL_STATUSES, +} from './deployment-publish-jobs'; +import type { DeploymentLifecyclePort, DeploymentSettingsPort } from './ports'; + +type Job = schema.DeploymentPublishJobRow; +export interface CloudflareBuildStopGuard { + jobId: string; + attempt: number; + notBefore: string | null; + retryAt: number; +} +export interface CloudflareBuildPorts { + settings: DeploymentSettingsPort; + lifecycle: DeploymentLifecyclePort; + classMax: number; + builder: { + start(job: Job): Promise<'started' | 'capacity'>; + /** Resolves only once the container is stopped, including no-running cases. */ + stop(job: Pick, capacity?: CloudflareBuildStopGuard): Promise; + }; +} + +export async function dispatchCloudflareBuild( + database: D1Database, + ports: CloudflareBuildPorts, + jobId: string +) { + const db = drizzle(database, { schema }); + const [platform, project, deadlineMs, buildTimeoutMs] = await Promise.all([ + ports.settings.resolveSetting('deployments.builderMaxConcurrent'), + ports.settings.resolveSetting('deployments.builderProjectMaxConcurrent'), + ports.settings.resolveSetting('deployments.publishJobDeadlineMs'), + ports.settings.resolveSetting('deployments.builderDeadlineMs'), + ]); + const job = await admitCloudflareBuild(db, jobId, { + platform: Number(platform), + project: Number(project), + classMax: ports.classMax, + deadlineMs: Number(deadlineMs), + buildTimeoutMs: Number(buildTimeoutMs), + }); + if (!job) return false; + await appendDeploymentPublishJobEvent(db, { + publishJobId: job.id, + projectId: job.projectId, + environmentId: job.environmentId, + nodeId: job.nodeId, + workspaceId: job.workspaceId, + expectedAttempt: job.attempt, + expectedStatus: 'starting', + currentStep: 'builder_start', + eventType: 'publish.builder.admitted', + message: 'Cloudflare build capacity reserved', + }); + return startReservedCloudflareBuild(database, ports, job); +} + +/** Shared by durable kickoff alarms and cron recovery of a lost caller. */ +export async function startReservedCloudflareBuild( + database: D1Database, + ports: CloudflareBuildPorts, + job: Job +) { + const db = drizzle(database, { schema }); + const backoffMs = Number( + await ports.settings.resolveSetting('deployments.builderCapacityBackoffMs') + ); + try { + const result = await ports.builder.start(job); + if (result === 'capacity') { + // Stop and release share the DO serialization boundary and reservation + // epoch. A stale capacity response cannot stop a readmitted guest. + try { + await ports.builder.stop(job, { + jobId: job.id, + attempt: job.attempt, + notBefore: job.executorNotBefore, + retryAt: Date.now() + backoffMs, + }); + } catch { + log.warn('cloudflare_builder.stop_pending', { publishJobId: job.id }); + } + } + return result === 'started'; + } catch { + const changed = await appendDeploymentPublishJobEvent(db, { + publishJobId: job.id, + projectId: job.projectId, + environmentId: job.environmentId, + nodeId: job.nodeId, + workspaceId: job.workspaceId, + expectedAttempt: job.attempt, + expectedStatus: 'starting', + expectedExecutor: 'cloudflare', + expectedExecutorInstanceId: job.id, + expectedReservationEpoch: job.executorNotBefore, + status: 'failed', + currentStep: 'builder_start', + eventType: 'publish.builder.start_failed', + message: 'Cloudflare builder failed to start', + errorCode: 'builder_start_failed', + terminal: true, + }); + if (!changed) return false; + try { + await ports.builder.stop(job); + await releaseCloudflareBuildReservation(db, job.id, job.attempt); + } catch { + log.warn('cloudflare_builder.stop_pending', { publishJobId: job.id }); + } + await ports.lifecycle.recordPublishJobLifecycleEventBestEffort({ + projectId: job.projectId, + publishJobId: job.id, + environmentId: job.environmentId, + status: 'failed', + terminal: true, + source: 'cloudflare_builder.start', + occurredAt: Date.now(), + }); + return false; + } +} + +/** At most the configured batch of queued starts and at most classMax stop + * reconciliations per cron tick. Each start has the same final atomic gate. */ +export async function drainCloudflareBuilds(database: D1Database, ports: CloudflareBuildPorts) { + const db = drizzle(database, { schema }); + const j = schema.deploymentPublishJobs; + const graceMs = Number( + await ports.settings.resolveSetting('deployments.builderReservationGraceMs') + ); + if (!Number.isSafeInteger(graceMs) || graceMs <= 0) + throw new Error('Invalid Cloudflare reservation grace'); + // Do this before contacting any DO. An unreachable stop must not wedge + // capacity or FK-cascaded deletion forever, even if the job sweep was lost. + const expired = await db + .select() + .from(j) + .where( + and( + eq(j.executor, 'cloudflare'), + eq(j.contextShadow, false), + isNotNull(j.executorInstanceId), + lte(j.executorDeadlineAt, new Date(Date.now() - graceMs).toISOString()) + ) + ) + .orderBy(asc(j.executorDeadlineAt), asc(j.id)) + .limit(ports.classMax); + for (const job of expired) { + try { + await forceReleaseExpiredCloudflareBuild(db, job, graceMs); + } catch { + log.error('cloudflare_builder.reservation_expiry_failed', { publishJobId: job.id }); + } + } + const terminal = await db + .select() + .from(j) + .where( + and( + eq(j.executor, 'cloudflare'), + isNotNull(j.executorInstanceId), + inArray(j.status, [...PUBLISH_JOB_TERMINAL_STATUSES]) + ) + ) + .limit(ports.classMax); + for (const job of terminal) { + try { + await ports.builder.stop(job); + await releaseCloudflareBuildReservation(db, job.id, job.attempt); + } catch { + log.warn('cloudflare_builder.stop_pending', { publishJobId: job.id }); + } + } + // Recover a lost HTTP waiter after reservation but before durable DO kickoff. + const starting = await db + .select() + .from(j) + .where( + and( + eq(j.executor, 'cloudflare'), + eq(j.contextShadow, false), + inArray(j.status, ['starting', 'context_ready']), + isNotNull(j.executorInstanceId) + ) + ) + .limit(ports.classMax); + for (const job of starting) await startReservedCloudflareBuild(database, ports, job); + const [limit, projectMax, deadlineMs] = await Promise.all([ + ports.settings.resolveSetting('deployments.builderDrainLimit'), + ports.settings.resolveSetting('deployments.builderProjectMaxConcurrent'), + ports.settings.resolveSetting('deployments.publishJobDeadlineMs'), + ]).then( + ([batch, project, deadline]) => [Number(batch), Number(project), Number(deadline)] as const + ); + if (![limit, projectMax, deadlineMs].every((value) => Number.isSafeInteger(value) && value > 0)) + throw new Error('Invalid Cloudflare drain limits'); + const now = new Date().toISOString(); + const queued = await db + .select({ id: j.id }) + .from(j) + .where( + and( + eq(j.executor, 'cloudflare'), + eq(j.contextShadow, false), + eq(j.status, 'context_ready'), + isNull(j.executorInstanceId), + isNotNull(j.contextR2Key), + isNotNull(j.contextSha256), + sql`${j.createdAt} > ${new Date(Date.now() - deadlineMs).toISOString()}`, + sql`(SELECT count(*) FROM deployment_publish_jobs AS active WHERE active.executor = 'cloudflare' AND active.executor_instance_id IS NOT NULL AND active.project_id = ${j.projectId}) < ${projectMax}`, + or(isNull(j.executorNotBefore), lte(j.executorNotBefore, now)) + ) + ) + .orderBy(asc(j.queuedAt), asc(j.id)) + .limit(limit); + for (const job of queued) await dispatchCloudflareBuild(database, ports, job.id); + return { considered: queued.length }; +} + +export function isCloudflareBuildCapacityError(error: unknown): boolean { + return ( + error instanceof Error && + /Maximum number of running containers|container.*capacity.*exceeded/i.test(error.message) + ); +} diff --git a/packages/app-deployment/src/cloudflare-build-reservation-expiry.ts b/packages/app-deployment/src/cloudflare-build-reservation-expiry.ts new file mode 100644 index 0000000000..3149a9a321 --- /dev/null +++ b/packages/app-deployment/src/cloudflare-build-reservation-expiry.ts @@ -0,0 +1,86 @@ +import { log, ulid } from '@simple-agent-manager/worker-core'; +import * as schema from '@simple-agent-manager/worker-core/schema'; +import { and, eq, isNotNull, lte, sql } from 'drizzle-orm'; +import type { drizzle } from 'drizzle-orm/d1'; + +import { PUBLISH_JOB_TERMINAL_STATUSES } from './deployment-publish-jobs'; + +type Db = ReturnType>; +type Job = schema.DeploymentPublishJobRow; + +/** Exceptional liveness escape, not proof of physical shutdown. Immutable + * deadline + grace bounds a lost stop RPC. Revoke live callback authority in + * the same mutation as ownership; never release a replacement attempt/epoch. */ +export async function forceReleaseExpiredCloudflareBuild( + db: Db, + job: Job, + graceMs: number, + nowMs = Date.now() +): Promise { + if (!Number.isSafeInteger(graceMs) || graceMs <= 0) + throw new Error('Invalid Cloudflare reservation grace'); + if (!job.executorInstanceId || !job.executorDeadlineAt) return false; + const j = schema.deploymentPublishJobs; + const terminal = sql.join( + [...PUBLISH_JOB_TERMINAL_STATUSES].map((s) => sql`${s}`), + sql`,` + ); + const [released] = await db + .update(j) + .set({ + executorInstanceId: null, + status: sql`CASE WHEN ${j.status} IN (${terminal}) THEN ${j.status} ELSE 'unknown' END`, + completedAt: sql`coalesce(${j.completedAt}, ${new Date(nowMs).toISOString()})`, + errorCode: sql`CASE WHEN ${j.status} IN (${terminal}) THEN ${j.errorCode} ELSE 'builder_stop_unconfirmed' END`, + errorMessage: sql`CASE WHEN ${j.status} IN (${terminal}) THEN ${j.errorMessage} ELSE 'Builder deadline and shutdown grace elapsed; physical stop is unconfirmed' END`, + updatedAt: new Date(nowMs).toISOString(), + }) + .where( + and( + eq(j.id, job.id), + eq(j.attempt, job.attempt), + eq(j.executor, 'cloudflare'), + eq(j.contextShadow, false), + eq(j.executorInstanceId, job.executorInstanceId), + sql`${j.executorNotBefore} IS ${job.executorNotBefore}`, + eq(j.executorDeadlineAt, job.executorDeadlineAt), + isNotNull(j.executorDeadlineAt), + lte(j.executorDeadlineAt, new Date(nowMs - graceMs).toISOString()) + ) + ) + .returning(); + if (!released) return false; + // Never attach provider/RPC error text: it may include credentials. Alert + // failure cannot roll back the escape or prevent later candidates progressing. + const detail = { + publishJobId: job.id, + projectId: job.projectId, + attempt: job.attempt, + executorInstanceId: job.executorInstanceId, + executorDeadlineAt: job.executorDeadlineAt, + reservationEpoch: job.executorNotBefore, + graceMs, + physicalStopConfirmed: false, + }; + log.error('cloudflare_builder.reservation_force_released', detail); + try { + // Terminal jobs reject normal agent events. This control-plane alert is + // deliberately journaled separately and never changes their verdict. + await db.run(sql`INSERT INTO deployment_publish_job_events + (id, publish_job_id, project_id, environment_id, node_id, + workspace_id, seq, level, event_type, message, detail_json, created_at) + SELECT ${ulid()}, ${j.id}, ${j.projectId}, ${j.environmentId}, ${j.nodeId}, + ${j.workspaceId}, + (SELECT coalesce(max(seq), 0) + 1 FROM deployment_publish_job_events WHERE publish_job_id = ${job.id}), + 'alert', 'publish.builder.reservation_force_released', + 'Builder reservation force-released after deadline and shutdown grace; physical stop is unconfirmed', + ${JSON.stringify(detail)}, ${new Date(nowMs).toISOString()} + FROM ${j} WHERE ${j.id} = ${job.id} AND ${j.attempt} = ${job.attempt}`); + } catch { + log.error('cloudflare_builder.reservation_alert_failed', { + publishJobId: job.id, + attempt: job.attempt, + }); + } + return true; +} diff --git a/packages/app-deployment/src/deployment-publish-job-cancel.ts b/packages/app-deployment/src/deployment-publish-job-cancel.ts index b191b8cf8e..9c63730454 100644 --- a/packages/app-deployment/src/deployment-publish-job-cancel.ts +++ b/packages/app-deployment/src/deployment-publish-job-cancel.ts @@ -6,11 +6,16 @@ import type { DeploymentPublishJobPorts } from './ports'; /** Durable verdicts are authoritative even if an old or dead executor cannot cancel. */ export async function cancelDeploymentPublishJobOnVmBestEffort( - ports: Pick, - job: Pick, + ports: Pick, + job: Pick & + Partial, timeoutOverrideMs?: number ) { try { + if (job.executor === 'cloudflare' && job.executorInstanceId) { + if (ports.builder) await ports.builder.stop(job); + return; + } const timeoutMs = timeoutOverrideMs ?? (await getDeploymentPublishJobSettings(ports.settings)).cancelTimeoutMs; await ports.vm.cancelPublishJob( diff --git a/packages/app-deployment/src/deployment-publish-jobs.ts b/packages/app-deployment/src/deployment-publish-jobs.ts index 40845c14c0..f24776fc5b 100644 --- a/packages/app-deployment/src/deployment-publish-jobs.ts +++ b/packages/app-deployment/src/deployment-publish-jobs.ts @@ -1,9 +1,11 @@ import { redactCredentialTokens } from '@simple-agent-manager/worker-core'; import { ulid } from '@simple-agent-manager/worker-core'; import * as schema from '@simple-agent-manager/worker-core/schema'; -import { and, asc, desc, eq, gt, isNull, lt, notInArray, or, sql } from 'drizzle-orm'; +import { and, asc, desc, eq, gt, inArray, isNull, lt, ne, notInArray, or, sql } from 'drizzle-orm'; import type { drizzle } from 'drizzle-orm/d1'; +import { publishJobTransitionPredicate } from './publish-job-transitions'; + type Db = ReturnType>; export const PUBLISH_JOB_TERMINAL_STATUSES = new Set([ @@ -129,6 +131,10 @@ export async function createDeploymentPublishJob( } export interface AppendDeploymentPublishJobEventInput { + expectedAttempt?: number; + /** Source collector authority ends at verified context handoff. */ + sourceCollector?: boolean; + expectedExecutor?: 'cloudflare'; publishJobId: string; projectId: string; environmentId: string; @@ -136,6 +142,8 @@ export interface AppendDeploymentPublishJobEventInput { workspaceId: string; status?: string; expectedStatus?: string; + expectedReservationEpoch?: string | null; + expectedExecutorInstanceId?: string; currentStep?: string | null; level?: string; eventType: string; @@ -162,6 +170,12 @@ export async function appendDeploymentPublishJobEvent( const terminal = input.terminal || (status ? PUBLISH_JOB_TERMINAL_STATUSES.has(status) : false); const predicate = and( eq(schema.deploymentPublishJobs.id, input.publishJobId), + input.expectedAttempt !== undefined + ? eq(schema.deploymentPublishJobs.attempt, input.expectedAttempt) + : undefined, + input.expectedExecutor + ? eq(schema.deploymentPublishJobs.executor, input.expectedExecutor) + : undefined, input.releaseId != null ? visiblePublishJobPredicate() : undefined, input.releaseId != null ? or( @@ -172,7 +186,21 @@ export async function appendDeploymentPublishJobEvent( input.expectedStatus ? eq(schema.deploymentPublishJobs.status, input.expectedStatus) : undefined, - notInArray(schema.deploymentPublishJobs.status, [...PUBLISH_JOB_TERMINAL_STATUSES]) + input.expectedReservationEpoch !== undefined + ? sql`${schema.deploymentPublishJobs.executorNotBefore} IS ${input.expectedReservationEpoch}` + : undefined, + input.expectedExecutorInstanceId !== undefined + ? eq(schema.deploymentPublishJobs.executorInstanceId, input.expectedExecutorInstanceId) + : undefined, + notInArray(schema.deploymentPublishJobs.status, [...PUBLISH_JOB_TERMINAL_STATUSES]), + input.sourceCollector && terminal + ? or( + ne(schema.deploymentPublishJobs.executor, 'cloudflare'), + eq(schema.deploymentPublishJobs.contextShadow, true), + inArray(schema.deploymentPublishJobs.status, ['queued', 'collecting']) + ) + : undefined, + publishJobTransitionPredicate(status, input.currentStep, terminal) ); if (input.eventType === 'publish.job.heartbeat') { // Heartbeats prove executor liveness independently of slow build/upload progress. @@ -370,7 +398,7 @@ export async function failExpiredDeploymentPublishJobs( const deadlineCutoff = new Date(nowMs - settings.deadlineMs).toISOString(); // SQL NULL never satisfies the heartbeat comparison: legacy agents are deadline-only. const expired = sql`(${schema.deploymentPublishJobs.createdAt} <= ${deadlineCutoff} - OR ${schema.deploymentPublishJobs.lastHeartbeatAt} <= ${stallCutoff})`; + OR (${schema.deploymentPublishJobs.status} <> 'context_ready' AND ${schema.deploymentPublishJobs.lastHeartbeatAt} <= ${stallCutoff}))`; // Disjoint status ranges use the existing (status, updated_at) index and // exclude terminal history. Unlike a fixed active-status list, this also // covers new non-terminal states introduced by later executors. diff --git a/packages/app-deployment/src/index.ts b/packages/app-deployment/src/index.ts index 4bc70073b5..27fb3eb3ba 100644 --- a/packages/app-deployment/src/index.ts +++ b/packages/app-deployment/src/index.ts @@ -11,9 +11,21 @@ export { collectBuildContextOnSource } from './build-context-collection'; export * from './build-context-defaults'; export { scheduleBuildContextShadow } from './build-context-shadow'; -export type { BuildContextDescriptor,BuildContextOwner } from './build-context-state'; -export { buildContextKey, completeBuildContext,reserveBuildContext } from './build-context-state'; -export { createBuildContextUpload, verifyBuildContextObject } from './build-context-upload'; +export type { BuildContextDescriptor, BuildContextOwner } from './build-context-state'; +export { buildContextKey, completeBuildContext, reserveBuildContext } from './build-context-state'; +export { + createBuildContextDownload, + createBuildContextUpload, + verifyBuildContextObject, +} from './build-context-upload'; +export * from './cloudflare-build-admission'; +export { + assertNoReservedCloudflareBuilds, + CLOUDFLARE_BUILD_DELETION_CONFLICT, + isCloudflareBuildDeletionConflict, +} from './cloudflare-build-admission'; +export * from './cloudflare-build-executor'; +export { forceReleaseExpiredCloudflareBuild } from './cloudflare-build-reservation-expiry'; export type { ComposeImageArtifactDescriptor, ComposeImageArtifactDownload, diff --git a/packages/app-deployment/src/ports.ts b/packages/app-deployment/src/ports.ts index a41fcca205..5600286ed3 100644 --- a/packages/app-deployment/src/ports.ts +++ b/packages/app-deployment/src/ports.ts @@ -24,6 +24,8 @@ export interface DeploymentSecretCipher { } export type DeploymentPublishJobSettingName = + | 'deployments.buildExecutor' + | `deployments.builder${'DeadlineMs' | 'ReservationGraceMs' | 'MaxConcurrent' | 'ProjectMaxConcurrent' | 'CapacityBackoffMs' | 'DrainLimit' | 'DaemonReadyTimeoutMs' | 'HeartbeatIntervalMs' | 'CallbackTimeoutMs' | 'CallbackAttempts' | 'CallbackRetryDelayMs'}` | `deployments.buildContext${'CollectionMode' | 'StartTimeoutMs' | 'MaxBytes' | 'CollectTimeoutMs' | 'UploadTtlSeconds' | 'RetentionHours' | 'CleanupBudgetMs' | 'CleanupPageSize'}` | 'deployments.publishJobStallMs' | 'deployments.publishJobDeadlineMs' @@ -71,6 +73,11 @@ export interface DeploymentLifecyclePort { export interface DeploymentPublishJobPorts { settings: DeploymentSettingsPort; vm: DeploymentPublishVmPort; + builder?: { + stop( + job: Pick + ): Promise; + }; lifecycle: DeploymentLifecyclePort; } diff --git a/packages/app-deployment/src/publish-job-transitions.ts b/packages/app-deployment/src/publish-job-transitions.ts new file mode 100644 index 0000000000..b3f8a4eb23 --- /dev/null +++ b/packages/app-deployment/src/publish-job-transitions.ts @@ -0,0 +1,72 @@ +import * as schema from '@simple-agent-manager/worker-core/schema'; +import { and, eq, ne, or, type SQL, sql } from 'drizzle-orm'; + +// Export/upload repeat per service. They share a phase; artifact initialization +// and completion still delimit that loop so delayed receipts cannot rewind it. +const PHASES: Record = { + queued: 0, + collecting: 1, + context_ready: 2, + starting: 3, + validating: 4, + building: 5, + exporting: 6, + uploading: 6, + recording_release: 7, +}; +const STEPS: Record = { + queued: 0, + collecting: 1, + context_ready: 2, + accepted: 3, + started: 3, + builder_start: 3, + builder_ready: 3, + compose_config: 4, + compose_build: 5, + artifact_init: 6, + docker_save: 7, + upload_archive: 7, + artifact_complete: 8, + release_submission: 9, +}; +function rank( + column: SQL | typeof schema.deploymentPublishJobs.status, + phases: Record +) { + return sql`CASE ${column} ${sql.join( + Object.entries(phases).map(([name, phase]) => sql`WHEN ${name} THEN ${phase}`), + sql` ` + )} ELSE -1 END`; +} + +/** Evaluated with history and the final UPDATE, never a preceding SELECT. + * Legacy node executors and phase-2 shadows retain their existing protocol. + * Only verified context completion and atomic admission may bypass this helper. + */ +export function publishJobTransitionPredicate( + status?: string, + step?: string | null, + terminal = false +) { + if (terminal || (!status && step === undefined)) return undefined; + const j = schema.deploymentPublishJobs; + return or( + ne(j.executor, 'cloudflare'), + eq(j.contextShadow, true), + and( + status + ? !Object.hasOwn(PHASES, status) + ? sql`0` + : sql`${rank(j.status, PHASES)} <= ${PHASES[status]}` + : undefined, + step === null + ? sql`0` + : step + ? !Object.hasOwn(STEPS, step) + ? eq(j.currentStep, step) + : sql`${rank(sql`${j.currentStep}`, STEPS)} <= ${STEPS[step]}` + : undefined + ) + ); +} diff --git a/packages/shared/src/types/workspace.ts b/packages/shared/src/types/workspace.ts index bed7173ab4..29a79a363c 100644 --- a/packages/shared/src/types/workspace.ts +++ b/packages/shared/src/types/workspace.ts @@ -193,6 +193,12 @@ export interface NodeResponse { /** Full system info from on-demand VM Agent endpoint */ export interface NodeSystemInfo { + /** Uncached process-local publish command attempts; absent on older agents. */ + publishExecution?: { + processIncarnation: string; + composeBuildAttempts: number; + dockerSaveAttempts: number; + }; cpu: { loadAvg1: number; loadAvg5: number; diff --git a/packages/vm-agent/Makefile b/packages/vm-agent/Makefile index aab64407d0..96d281d733 100644 --- a/packages/vm-agent/Makefile +++ b/packages/vm-agent/Makefile @@ -59,7 +59,11 @@ build-linux-amd64: prepare-codex-runtime: @bash ../../scripts/deploy/prepare-codex-runtime-artifact.sh "$(CONTAINER_ARTIFACT_DIR)" -prepare-container: prepare-codex-runtime build-linux-amd64 +prepare-builder: + @mkdir -p $(CONTAINER_ARTIFACT_DIR) + CGO_ENABLED=0 GOOS=linux GOARCH=amd64 $(GO) build $(GOFLAGS) -o $(CONTAINER_ARTIFACT_DIR)/sam-builder-linux-amd64 ./cmd/sam-builder + +prepare-container: prepare-codex-runtime build-linux-amd64 prepare-builder @mkdir -p $(CONTAINER_ARTIFACT_DIR) @cp bin/$(BINARY_NAME)-linux-amd64 $(CONTAINER_ARTIFACT_DIR)/vm-agent-linux-amd64 @cp internal/acp/opencode_install.sh $(CONTAINER_ARTIFACT_DIR)/install-opencode.sh diff --git a/packages/vm-agent/cmd/sam-builder/main.go b/packages/vm-agent/cmd/sam-builder/main.go new file mode 100644 index 0000000000..23f755ca57 --- /dev/null +++ b/packages/vm-agent/cmd/sam-builder/main.go @@ -0,0 +1,102 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net" + "net/http" + "os" + "os/signal" + "strconv" + "sync" + "syscall" + "time" + + "github.com/workspace/vm-agent/internal/builder" + "github.com/workspace/vm-agent/internal/sysinfo" +) + +const bootstrapTimeout = 60 * time.Second +const controllerAddress = ":8080" +const maxLaunchBytes = 16 * 1024 + +func durationEnv(name string, fallback time.Duration) time.Duration { + value, err := strconv.Atoi(os.Getenv(name)) + if err == nil && value > 0 { + return time.Duration(value) * time.Millisecond + } + return fallback +} +func main() { + if err := run(); err != nil { + fmt.Fprintln(os.Stderr, "sam-builder stopped:", err) + os.Exit(1) + } +} +func run() error { + bootstrapBudget := durationEnv("SAM_BUILDER_BOOTSTRAP_TIMEOUT_MS", bootstrapTimeout) + controlBudget := durationEnv("SAM_BUILDER_CONTROL_TIMEOUT_MS", builder.DefaultCallbackTimeout) + ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer cancel() + listener, err := net.Listen("tcp", controllerAddress) + if err != nil { + return err + } + return serveController(ctx, listener, bootstrapBudget, controlBudget, builder.Run) +} + +func controller(launches chan<- builder.Launch) http.Handler { + var once sync.Once + mux := http.NewServeMux() + mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]string{"version": sysinfo.Version}) + }) + mux.HandleFunc("POST /start", func(w http.ResponseWriter, r *http.Request) { + var launch builder.Launch + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxLaunchBytes)).Decode(&launch); err != nil || launch.Token == "" || launch.ProjectID == "" || launch.JobID == "" || launch.Attempt < 1 || launch.DeadlineAt.Before(time.Now()) { + http.Error(w, "invalid launch", http.StatusBadRequest) + return + } + accepted := false + once.Do(func() { launches <- launch; accepted = true }) + if !accepted { + http.Error(w, "already accepted", http.StatusConflict) + return + } + w.WriteHeader(http.StatusAccepted) + }) + return mux +} + +// The listener is always closed before untrusted build execution is invoked. +func serveController(ctx context.Context, listener net.Listener, bootstrapBudget, controlBudget time.Duration, execute func(context.Context, builder.Launch) error) error { + // Close even if cancellation wins before http.Server registers the listener. + defer listener.Close() + launches := make(chan builder.Launch, 1) + server := &http.Server{Handler: controller(launches), ReadHeaderTimeout: controlBudget, ReadTimeout: controlBudget, WriteTimeout: controlBudget} + serverErr := make(chan error, 1) + go func() { serverErr <- server.Serve(listener) }() + timer := time.NewTimer(bootstrapBudget) + defer timer.Stop() + defer server.Close() + select { + case launch := <-launches: + // Close the bootstrap listener before any Dockerfile runs. A RUN with host + // networking can neither retrieve a token nor submit a second launch. + shutdownCtx, stop := context.WithTimeout(ctx, controlBudget) + defer stop() + if err := server.Shutdown(shutdownCtx); err != nil { + return errors.New("controller shutdown failed") + } + return execute(ctx, launch) + case <-ctx.Done(): + return ctx.Err() + case err := <-serverErr: + return err + case <-timer.C: + return errors.New("builder bootstrap deadline") + } +} diff --git a/packages/vm-agent/cmd/sam-builder/main_test.go b/packages/vm-agent/cmd/sam-builder/main_test.go new file mode 100644 index 0000000000..4bc3ccf974 --- /dev/null +++ b/packages/vm-agent/cmd/sam-builder/main_test.go @@ -0,0 +1,142 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/workspace/vm-agent/internal/builder" + "github.com/workspace/vm-agent/internal/sysinfo" +) + +func launchFixture() builder.Launch { + return builder.Launch{Token: "test-job-capability-canary", JobID: "job", ProjectID: "project", Attempt: 1, ControlPlaneURL: "https://control.invalid", DeadlineAt: time.Now().Add(time.Minute)} +} +func postLaunch(t *testing.T, client *http.Client, url string, launch builder.Launch) int { + t.Helper() + raw, err := json.Marshal(launch) + if err != nil { + t.Fatal(err) + } + response, err := client.Post(url+"/start", "application/json", bytes.NewReader(raw)) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + body, err := io.ReadAll(response.Body) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(body), launch.Token) || strings.Contains(string(body), launch.ControlPlaneURL) { + t.Fatal("launch capability reflected in response") + } + return response.StatusCode +} +func TestControllerAcceptsExactlyOneLaunchWithoutExposingCapabilities(t *testing.T) { + launches := make(chan builder.Launch, 2) + server := httptest.NewServer(controller(launches)) + defer server.Close() + launch := launchFixture() + if status := postLaunch(t, server.Client(), server.URL, launch); status != http.StatusAccepted { + t.Fatalf("initial status %d", status) + } + received := <-launches + if received.Token != launch.Token || received.ControlPlaneURL != launch.ControlPlaneURL { + t.Fatal("accepted launch changed") + } + replacement := launch + replacement.Token = "replacement-capability" + replacement.ControlPlaneURL = "https://replacement.invalid" + if status := postLaunch(t, server.Client(), server.URL, replacement); status != http.StatusConflict { + t.Fatalf("second status %d", status) + } + select { + case <-launches: + t.Fatal("second launch reached executor") + default: + } + response, err := server.Client().Get(server.URL + "/health") + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + var health map[string]string + if err := json.NewDecoder(response.Body).Decode(&health); err != nil { + t.Fatal(err) + } + if len(health) != 1 || health["version"] != sysinfo.Version { + t.Fatal("health exposes fields other than version") + } + for _, path := range []string{"/spec", "/token", "/start"} { + r, err := server.Client().Get(server.URL + path) + if err != nil { + t.Fatal(err) + } + raw, _ := io.ReadAll(r.Body) + r.Body.Close() + if r.StatusCode < 400 || strings.Contains(string(raw), launch.Token) { + t.Fatalf("unsafe GET %s", path) + } + } +} +func TestBootstrapClosesListenerBeforeBuildExecution(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer listener.Close() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + finished := make(chan error, 1) + address := listener.Addr().String() + go func() { + finished <- serveController(ctx, listener, time.Second, time.Second, func(_ context.Context, launch builder.Launch) error { + connection, err := net.DialTimeout("tcp", address, 100*time.Millisecond) + if err == nil { + connection.Close() + return errors.New("bootstrap port reachable during build execution") + } + if launch.Token != launchFixture().Token { + return errors.New("launch capability changed") + } + return nil + }) + }() + client := &http.Client{Timeout: 2 * time.Second} + if status := postLaunch(t, client, "http://"+address, launchFixture()); status != http.StatusAccepted { + t.Fatalf("status %d", status) + } + select { + case err := <-finished: + if err != nil { + t.Fatal(err) + } + case <-ctx.Done(): + t.Fatal("executor did not finish") + } +} +func TestCanceledBootstrapClosesWithoutStartingBuild(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer listener.Close() + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := serveController(ctx, listener, time.Second, time.Second, func(context.Context, builder.Launch) error { t.Fatal("canceled bootstrap executed job"); return nil }); !errors.Is(err, context.Canceled) { + t.Fatalf("error %v", err) + } + connection, err := net.DialTimeout("tcp", listener.Addr().String(), 100*time.Millisecond) + if err == nil { + connection.Close() + t.Fatal("canceled bootstrap retained listener") + } +} diff --git a/packages/vm-agent/internal/builder/archive.go b/packages/vm-agent/internal/builder/archive.go new file mode 100644 index 0000000000..86f3b7a2e4 --- /dev/null +++ b/packages/vm-agent/internal/builder/archive.go @@ -0,0 +1,153 @@ +package builder + +import ( + "archive/tar" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "net/http" + "os" + "path" + "sort" + "strings" + + "github.com/klauspost/compress/zstd" +) + +type contextReader struct { + ctx context.Context + reader io.Reader +} + +func (r contextReader) Read(p []byte) (int, error) { + if err := r.ctx.Err(); err != nil { + return 0, err + } + return r.reader.Read(p) +} + +// Download verifies both declared bytes and the digest before any extraction. +// Signed URLs are never included in returned errors, including redirect errors. +func Download(ctx context.Context, client *http.Client, url string, size int64, digest string, max int64, output *os.File) error { + if size <= 0 || size > max || len(digest) != 64 { + return errors.New("invalid context descriptor") + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return errors.New("invalid context download URL") + } + response, err := client.Do(req) + if err != nil { + return errors.New("context download failed") + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return fmt.Errorf("context download returned %d", response.StatusCode) + } + hash := sha256.New() + n, err := io.Copy(io.MultiWriter(output, hash), io.LimitReader(response.Body, size+1)) + if err != nil { + return errors.New("context download interrupted") + } + if n != size || hex.EncodeToString(hash.Sum(nil)) != digest { + return errors.New("context size or sha256 mismatch") + } + _, err = output.Seek(0, io.SeekStart) + return err +} + +// Extract uses one directory capability, refuses special files and links out of +// the root, and bounds decompressed tar bytes (headers and payload). No guest +// command runs until extraction has completed. +func Extract(ctx context.Context, input io.Reader, destination string, max int64) error { + decoder, err := zstd.NewReader(input, zstd.WithDecoderConcurrency(1), zstd.WithDecoderMaxMemory(uint64(max))) + if err != nil { + return err + } + defer decoder.Close() + limited := &io.LimitedReader{R: contextReader{ctx, decoder}, N: max + 1} + reader := tar.NewReader(limited) + root, err := os.OpenRoot(destination) + if err != nil { + return err + } + defer root.Close() + // Keep extraction writable until all children exist; apply archive modes only + // after success. Implicit parents match the collector's normal directory mode. + directories := map[string]os.FileMode{} + rememberParents := func(name string) { + for parent := path.Dir(name); parent != "."; parent = path.Dir(parent) { + if _, ok := directories[parent]; !ok { + directories[parent] = 0755 + } + } + } + for { + header, err := reader.Next() + if err == io.EOF { + if limited.N <= 1 { + return errors.New("expanded context exceeds maximum bytes") + } + names := make([]string, 0, len(directories)) + for name := range directories { + names = append(names, name) + } + sort.Slice(names, func(i, j int) bool { return strings.Count(names[i], "/") > strings.Count(names[j], "/") }) + for _, name := range names { + if err := root.Chmod(name, directories[name]); err != nil { + return err + } + } + return nil + } + if err != nil { + return errors.New("invalid or oversized context archive") + } + name := path.Clean(header.Name) + if name == "." || !safeRelative(name) || strings.Contains(header.Name, "\\") { + return errors.New("unsafe archive path") + } + if header.Size < 0 || header.Size > max || limited.N-header.Size <= 0 { + return errors.New("expanded context exceeds maximum bytes") + } + rememberParents(name) + if err = root.MkdirAll(path.Dir(name), 0700); err != nil { + return err + } + switch header.Typeflag { + case tar.TypeDir: + directories[name] = os.FileMode(header.Mode) & 0777 + if err = root.MkdirAll(name, 0700); err != nil { + return err + } + case tar.TypeReg, tar.TypeRegA: + file, err := root.OpenFile(name, os.O_CREATE|os.O_EXCL|os.O_WRONLY, os.FileMode(header.Mode)&0777) + if err != nil { + return errors.New("duplicate or unsafe archive entry") + } + _, copyErr := io.CopyN(file, reader, header.Size) + closeErr := file.Close() + if copyErr != nil { + return errors.New("truncated archive entry") + } + if closeErr != nil { + return closeErr + } + case tar.TypeSymlink: + if !safeRelative(path.Join(path.Dir(name), header.Linkname)) || path.IsAbs(header.Linkname) || strings.Contains(header.Linkname, "\\") { + return errors.New("unsafe archive symlink") + } + if err = root.Symlink(header.Linkname, name); err != nil { + return err + } + default: + return errors.New("unsupported archive entry type") + } + } +} +func safeRelative(name string) bool { + return name != "" && !path.IsAbs(name) && name != ".." && !strings.HasPrefix(name, "../") +} diff --git a/packages/vm-agent/internal/builder/archive_test.go b/packages/vm-agent/internal/builder/archive_test.go new file mode 100644 index 0000000000..37bae6ab67 --- /dev/null +++ b/packages/vm-agent/internal/builder/archive_test.go @@ -0,0 +1,154 @@ +package builder + +import ( + "archive/tar" + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/klauspost/compress/zstd" +) + +func bundle(t *testing.T, headers []*tar.Header, content []byte) []byte { + t.Helper() + var b bytes.Buffer + encoder, err := zstd.NewWriter(&b) + if err != nil { + t.Fatal(err) + } + tw := tar.NewWriter(encoder) + for _, h := range headers { + if err = tw.WriteHeader(h); err != nil { + t.Fatal(err) + } + if h.Typeflag == tar.TypeReg { + if _, err = tw.Write(content[:h.Size]); err != nil { + t.Fatal(err) + } + } + } + if err = tw.Close(); err != nil { + t.Fatal(err) + } + if err = encoder.Close(); err != nil { + t.Fatal(err) + } + return b.Bytes() +} +func TestExtractPortableContext(t *testing.T) { + raw := bundle(t, []*tar.Header{{Name: "ctx/file", Typeflag: tar.TypeReg, Mode: 0755, Size: 4}, {Name: "runtime.env", Typeflag: tar.TypeReg, Mode: 0600}, {Name: "link", Typeflag: tar.TypeSymlink, Linkname: "ctx/file"}}, []byte("test")) + dir := t.TempDir() + if err := Extract(context.Background(), bytes.NewReader(raw), dir, 8<<20); err != nil { + t.Fatal(err) + } + for _, name := range []string{"ctx/file", "link"} { + value, err := os.ReadFile(filepath.Join(dir, name)) + if err != nil || string(value) != "test" { + t.Fatalf("%s %q %v", name, value, err) + } + } + info, err := os.Stat(filepath.Join(dir, "runtime.env")) + if err != nil || info.Size() != 0 { + t.Fatal("placeholder not empty") + } +} +func TestExtractRejectsEscapeAndSpecialEntries(t *testing.T) { + for _, header := range []*tar.Header{ + {Name: "../outside", Typeflag: tar.TypeReg}, {Name: "/outside", Typeflag: tar.TypeReg}, + {Name: "escape", Typeflag: tar.TypeSymlink, Linkname: "../outside"}, + {Name: "escape", Typeflag: tar.TypeSymlink, Linkname: "/etc/passwd"}, + {Name: "fifo", Typeflag: tar.TypeFifo}, {Name: "device", Typeflag: tar.TypeChar}, + {Name: "hardlink", Typeflag: tar.TypeLink, Linkname: "/etc/passwd"}, + } { + t.Run(header.Name+string(header.Typeflag), func(t *testing.T) { + raw := bundle(t, []*tar.Header{header}, nil) + if err := Extract(context.Background(), bytes.NewReader(raw), t.TempDir(), 8<<20); err == nil { + t.Fatal("unsafe archive accepted") + } + }) + } +} +func TestExtractBoundsExpandedBytesAndDuplicateNames(t *testing.T) { + raw := bundle(t, []*tar.Header{{Name: "large", Typeflag: tar.TypeReg, Size: 2 << 20}}, make([]byte, 2<<20)) + if err := Extract(context.Background(), bytes.NewReader(raw), t.TempDir(), 1<<20); err == nil { + t.Fatal("expansion accepted") + } + raw = bundle(t, []*tar.Header{{Name: "same", Typeflag: tar.TypeReg}, {Name: "same", Typeflag: tar.TypeReg}}, nil) + if err := Extract(context.Background(), bytes.NewReader(raw), t.TempDir(), 8<<20); err == nil { + t.Fatal("duplicate accepted") + } +} +func TestDownloadDigestSizeAndRedirect(t *testing.T) { + payload := []byte("verified compressed bytes") + digest := sha256.Sum256(payload) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/redirect" { + http.Redirect(w, r, "/ok", 302) + return + } + _, _ = w.Write(payload) + })) + defer server.Close() + for _, tc := range []struct { + name, url, sha string + size int64 + ok bool + }{ + {"owner", server.URL, hex.EncodeToString(digest[:]), int64(len(payload)), true}, + {"hash", server.URL, "0000000000000000000000000000000000000000000000000000000000000000", int64(len(payload)), false}, + {"size", server.URL, hex.EncodeToString(digest[:]), int64(len(payload) - 1), false}, + {"redirect", server.URL + "/redirect", hex.EncodeToString(digest[:]), int64(len(payload)), false}, + } { + t.Run(tc.name, func(t *testing.T) { + f, err := os.CreateTemp(t.TempDir(), "context") + if err != nil { + t.Fatal(err) + } + defer f.Close() + err = Download(context.Background(), Client(DefaultCallbackTimeout), tc.url, tc.size, tc.sha, 1024, f) + if (err == nil) != tc.ok { + t.Fatalf("download err %v", err) + } + }) + } +} + +func TestExtractRestoresDirectoryPermissionsAfterAllEntries(t *testing.T) { + for _, tc := range []struct { + name string + headers []*tar.Header + modes map[string]os.FileMode + }{ + {"explicit", []*tar.Header{{Name: "public", Typeflag: tar.TypeDir, Mode: 0755}, {Name: "public/nested", Typeflag: tar.TypeDir, Mode: 0750}, {Name: "public/nested/file", Typeflag: tar.TypeReg, Mode: 0644, Size: 4}}, map[string]os.FileMode{"public": 0755, "public/nested": 0750}}, + {"late-directory", []*tar.Header{{Name: "public/nested/file", Typeflag: tar.TypeReg, Mode: 0644, Size: 4}, {Name: "public", Typeflag: tar.TypeDir, Mode: 0755}, {Name: "public/nested", Typeflag: tar.TypeDir, Mode: 0750}}, map[string]os.FileMode{"public": 0755, "public/nested": 0750}}, + {"implicit", []*tar.Header{{Name: "public/nested/file", Typeflag: tar.TypeReg, Mode: 0644, Size: 4}}, map[string]os.FileMode{"public": 0755, "public/nested": 0755}}, + {"restricted-parent", []*tar.Header{{Name: "public", Typeflag: tar.TypeDir, Mode: 0500}, {Name: "public/nested", Typeflag: tar.TypeDir, Mode: 0750}, {Name: "public/nested/file", Typeflag: tar.TypeReg, Mode: 0644, Size: 4}}, map[string]os.FileMode{"public": 0500, "public/nested": 0750}}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + defer os.Chmod(filepath.Join(dir, "public"), 0700) + if err := Extract(context.Background(), bytes.NewReader(bundle(t, tc.headers, []byte("test"))), dir, 8<<20); err != nil { + t.Fatal(err) + } + for name, mode := range tc.modes { + info, err := os.Stat(filepath.Join(dir, name)) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != mode { + t.Errorf("%s permissions %o, want %o", name, info.Mode().Perm(), mode) + } + } + data, err := os.ReadFile(filepath.Join(dir, "public/nested/file")) + if err != nil || string(data) != "test" { + t.Fatalf("file content %q, %v", data, err) + } + }) + } +} diff --git a/packages/vm-agent/internal/builder/runner.go b/packages/vm-agent/internal/builder/runner.go new file mode 100644 index 0000000000..66a3405fca --- /dev/null +++ b/packages/vm-agent/internal/builder/runner.go @@ -0,0 +1,263 @@ +// Package builder hosts the existing publish engine in a single-job DinD VM. +package builder + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "time" + + "github.com/workspace/vm-agent/internal/publish" +) + +const DefaultDaemonReadyTimeout = 60 * time.Second +const DefaultHeartbeatInterval = 15 * time.Second +const DefaultCallbackTimeout = 30 * time.Second +const MaxSpecBytes = 2 * 1024 * 1024 + +type Launch struct { + CallbackTimeoutMs int `json:"callbackTimeoutMs"` + CallbackAttempts int `json:"callbackAttempts"` + CallbackRetryDelayMs int `json:"callbackRetryDelayMs"` + ControlPlaneURL string `json:"controlPlaneUrl"` + ProjectID string `json:"projectId"` + JobID string `json:"jobId"` + Attempt int `json:"attempt"` + Token string `json:"token"` + DeadlineAt time.Time `json:"deadlineAt"` +} +type Spec struct { + ProjectName string `json:"projectName"` + DaemonReadyTimeoutMs int `json:"daemonReadyTimeoutMs"` + HeartbeatIntervalMs int `json:"heartbeatIntervalMs"` + + JobID string `json:"jobId"` + Attempt int `json:"attempt"` + Environment string `json:"environment"` + EnvironmentID string `json:"environmentId"` + Reference string `json:"reference"` + AgentProfileID string `json:"agentProfileId"` + TaskID string `json:"taskId"` + ContextURL string `json:"contextUrl"` + ContextBytes int64 `json:"contextBytes"` + ContextSHA256 string `json:"contextSha256"` + MaxBytes int64 `json:"maxBytes"` + BuildEnv map[string]string `json:"buildInterpolationEnv"` + SecretKeys []string `json:"secretInterpolationKeys"` +} + +// Callbacks never redirect a bearer token to another origin. Download/upload +// errors omit signed URLs; no token or capability is placed in the environment. +func Client(timeout time.Duration) *http.Client { + return &http.Client{Timeout: timeout, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect rejected") }} +} +func (l Launch) jobURL() string { + return l.ControlPlaneURL + "/api/projects/" + l.ProjectID + "/deployment-publish-jobs/" + l.JobID +} + +type callbackStatusError struct{ status int } + +func (e callbackStatusError) Error() string { + return fmt.Sprintf("builder callback returned %d", e.status) +} + +const DefaultCallbackAttempts = 3 +const DefaultCallbackRetryDelay = 5 * time.Second + +func (l Launch) callbackTimeout() time.Duration { + if l.CallbackTimeoutMs > 0 { + return time.Duration(l.CallbackTimeoutMs) * time.Millisecond + } + return DefaultCallbackTimeout +} +func (l Launch) send(ctx context.Context, method, url string, body any, result any) error { + attempts, retryDelay := l.CallbackAttempts, time.Duration(l.CallbackRetryDelayMs)*time.Millisecond + if attempts < 1 { + attempts = DefaultCallbackAttempts + } + if retryDelay <= 0 { + retryDelay = DefaultCallbackRetryDelay + } + var last error + for attempt := 0; attempt < attempts; attempt++ { + last = l.sendOnce(ctx, method, url, body, result) + if last == nil { + return nil + } + var status callbackStatusError + if errors.As(last, &status) && status.status < 500 { + return last + } + if attempt+1 < attempts { + timer := time.NewTimer(retryDelay) + select { + case <-ctx.Done(): + timer.Stop() + return ctx.Err() + case <-timer.C: + } + } + } + return last +} +func (l Launch) sendOnce(ctx context.Context, method, url string, body any, result any) error { + var input io.Reader + if body != nil { + raw, err := json.Marshal(body) + if err != nil { + return err + } + input = bytes.NewReader(raw) + } + req, err := http.NewRequestWithContext(ctx, method, url, input) + if err != nil { + return errors.New("invalid callback URL") + } + req.Header.Set("Authorization", "Bearer "+l.Token) + req.Header.Set("Content-Type", "application/json") + response, err := Client(l.callbackTimeout()).Do(req) + if err != nil { + return errors.New("builder callback failed") + } + defer response.Body.Close() + if response.StatusCode < 200 || response.StatusCode >= 300 { + return callbackStatusError{response.StatusCode} + } + if result != nil { + return json.NewDecoder(io.LimitReader(response.Body, MaxSpecBytes)).Decode(result) + } + return nil +} + +func Run(parent context.Context, launch Launch) error { + ctx, cancel := context.WithDeadline(parent, launch.DeadlineAt) + defer cancel() + var spec Spec + if err := launch.send(ctx, http.MethodGet, launch.jobURL()+"/spec", nil, &spec); err != nil { + return err + } + if spec.JobID != launch.JobID || spec.Attempt != launch.Attempt { + return errors.New("builder spec identity mismatch") + } + if spec.DaemonReadyTimeoutMs < 1000 || spec.DaemonReadyTimeoutMs > 120000 || spec.HeartbeatIntervalMs < 1000 || spec.HeartbeatIntervalMs > 30000 { + return errors.New("invalid builder timing configuration") + } + + sink := publish.EventFunc(func(eventCtx context.Context, event publish.Event) { + // Only safe, structured errors reach callbacks; Docker output is not attached + // to the runner's terminal event (a RUN may print arbitrary credentials). + _ = launch.send(eventCtx, http.MethodPost, launch.jobURL()+"/events", event, nil) + }) + done := make(chan struct{}) + defer close(done) + go func() { + ticker := time.NewTicker(time.Duration(spec.HeartbeatIntervalMs) * time.Millisecond) + defer ticker.Stop() + for { + select { + case <-done: + return + case <-ctx.Done(): + return + case <-ticker.C: + err := launch.send(ctx, http.MethodPost, launch.jobURL()+"/events", publish.Event{EventType: "publish.job.heartbeat", Message: "builder alive"}, nil) + if err != nil { // A revoked job token or failed control plane never extends compute. + cancel() + return + } + } + } + }() + err := run(ctx, launch, spec, sink) + if err != nil { + finalCtx, stop := context.WithTimeout(context.Background(), launch.callbackTimeout()) + defer stop() + _ = launch.send(finalCtx, http.MethodPost, launch.jobURL()+"/events", publish.Event{Status: "failed", CurrentStep: "builder", Level: "error", EventType: "publish.builder.failed", Message: "Cloudflare build failed; inspect publish progress", ErrorCode: "cloudflare_build_failed", Terminal: true}, nil) + } + return err +} +func run(ctx context.Context, launch Launch, spec Spec, sink publish.EventSink) error { + temp, err := os.MkdirTemp("", "sam-builder-") + if err != nil { + return err + } + defer os.RemoveAll(temp) + archive, err := os.CreateTemp(temp, "context-*.tar.zst") + if err != nil { + return err + } + defer archive.Close() + if err = Download(ctx, Client(time.Until(launch.DeadlineAt)), spec.ContextURL, spec.ContextBytes, spec.ContextSHA256, spec.MaxBytes, archive); err != nil { + return err + } + if !validProjectName(spec.ProjectName) { + return errors.New("invalid Compose project identity") + } + source := filepath.Join(temp, spec.ProjectName) + if err = os.Mkdir(source, 0700); err != nil { + return err + } + if err = Extract(ctx, archive, source, spec.MaxBytes); err != nil { + return err + } + if err = archive.Close(); err != nil { + return err + } + if err = os.Remove(archive.Name()); err != nil { + return err + } + daemon := exec.CommandContext(ctx, "/usr/local/bin/dockerd", "--host=unix:///var/run/docker.sock", "--iptables=false", "--ip6tables=false", "--ip-forward=false", "--exec-opt", "native.cgroupdriver=cgroupfs") + // Keep daemon diagnostics off callbacks; never print a job launch payload. + daemon.Stdout = os.Stderr + daemon.Stderr = os.Stderr + if err = daemon.Start(); err != nil { + return errors.New("dockerd failed to start") + } + defer func() { _ = daemon.Process.Signal(os.Interrupt); _ = daemon.Process.Kill(); _ = daemon.Wait() }() + readyCtx, readyCancel := context.WithTimeout(ctx, time.Duration(spec.DaemonReadyTimeoutMs)*time.Millisecond) + defer readyCancel() + for { + if exec.CommandContext(readyCtx, "/usr/local/bin/docker", "info").Run() == nil { + break + } + select { + case <-readyCtx.Done(): + return errors.New("dockerd readiness deadline") + case <-time.After(time.Duration(spec.DaemonReadyTimeoutMs) * time.Millisecond / 300): + } + } + sink.Event(ctx, publish.Event{Status: "starting", CurrentStep: "builder_ready", EventType: "publish.builder.ready", Message: "DinD builder ready"}) + artifact, err := publish.Build(ctx, publish.BuildOptions{WorkspaceDir: source, Reference: spec.Reference, BuildEnv: spec.BuildEnv, SecretKeys: spec.SecretKeys, BuildNetwork: "host", Events: sink}) + if err != nil { + // TODO(01M7HDK9DV8G2JPBK1KTVNY6JN): preserve the failing step and a bounded, + // redacted build-output tail; Cloudflare callbacks currently expose only this generic error. + return errors.New("compose build failed") + } + plane := publish.NewHTTPControlPlane(publish.HTTPControlPlaneOptions{BaseURL: launch.ControlPlaneURL, Token: launch.Token, Client: Client(launch.callbackTimeout())}) + orchestrator := publish.New(publish.Options{PublishJobID: launch.JobID, Attempt: launch.Attempt, ControlPlane: plane, Docker: publish.NewHostDocker(), HTTPClient: Client(time.Until(launch.DeadlineAt)), Events: sink}) + result, err := orchestrator.Publish(ctx, launch.ProjectID, spec.Environment, spec.EnvironmentID, artifact, &publish.ReleaseSubmittedBy{AgentProfileID: spec.AgentProfileID, TaskID: spec.TaskID}) + if err != nil { + return errors.New("image publication failed") + } + return launch.send(ctx, http.MethodPost, launch.jobURL()+"/events", publish.Event{Status: "succeeded", CurrentStep: "complete", EventType: "publish.job.completed", Message: "Cloudflare publish complete", Terminal: true, ReleaseID: result.ReleaseID, ReleaseVersion: result.Version, ReleaseStatus: result.Status}, nil) +} + +func validProjectName(name string) bool { + if name == "" || len(name) > 255 { + return false + } + for i, c := range name { + if c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || i > 0 && (c == '_' || c == '-') { + continue + } + return false + } + return true +} diff --git a/packages/vm-agent/internal/builder/runner_test.go b/packages/vm-agent/internal/builder/runner_test.go new file mode 100644 index 0000000000..9db4fe4d04 --- /dev/null +++ b/packages/vm-agent/internal/builder/runner_test.go @@ -0,0 +1,65 @@ +package builder + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" +) + +func TestCallbackRetriesTransientFailureWithIdenticalBodyAndToken(t *testing.T) { + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer job-token" { + t.Error("missing job token") + } + raw, _ := io.ReadAll(r.Body) + if string(raw) != "{\"terminal\":true}" { + t.Errorf("body changed %q", raw) + } + if calls.Add(1) == 1 { + w.WriteHeader(503) + return + } + w.WriteHeader(200) + })) + defer server.Close() + launch := Launch{Token: "job-token"} + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := launch.send(ctx, http.MethodPost, server.URL, map[string]bool{"terminal": true}, nil); err != nil { + t.Fatal(err) + } + if calls.Load() != 2 { + t.Fatalf("calls %d", calls.Load()) + } +} +func TestCallbackStopsImmediatelyOnRevocationAndCancelsRetryDelay(t *testing.T) { + for _, status := range []int{401, 403, 404, 409, 410} { + t.Run(http.StatusText(status), func(t *testing.T) { + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls.Add(1); w.WriteHeader(status) })) + defer server.Close() + if err := (Launch{}).send(context.Background(), http.MethodPost, server.URL, nil, nil); err == nil { + t.Fatal("revocation accepted") + } + if calls.Load() != 1 { + t.Fatal("retried revoked token") + } + }) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(503); cancel() })) + defer server.Close() + started := time.Now() + if err := (Launch{}).send(ctx, http.MethodPost, server.URL, nil, nil); err == nil { + t.Fatal("cancellation ignored") + } + if time.Since(started) > time.Second { + t.Fatal("retry delay ignored cancellation") + } +} diff --git a/packages/vm-agent/internal/publish/build.go b/packages/vm-agent/internal/publish/build.go index 539dddb9e5..be5029538d 100644 --- a/packages/vm-agent/internal/publish/build.go +++ b/packages/vm-agent/internal/publish/build.go @@ -24,6 +24,10 @@ const unsupportedComposeVolumesGuidance = "build_and_publish supports safe named // BuildOptions configures a host-side compose build. type BuildOptions struct { + // BuildNetwork overrides networking only for build commands on remote DinD. + // The captured release retains the original service/runtime networks. + BuildNetwork string + // WorkspaceDir is the host path of the cloned repo (the compose project // root). It is the same directory passed to `devcontainer up`. WorkspaceDir string @@ -240,7 +244,7 @@ func Build(ctx context.Context, opts BuildOptions) (*BuildArtifact, error) { if opts.Events != nil { opts.Events.Event(ctx, Event{Status: "building", CurrentStep: "compose_build", EventType: "publish.build.started", Message: "docker compose build started", Detail: map[string]any{"targetCount": len(targets)}}) } - if _, err := runCompose(ctx, composeCmd, opts.WorkspaceDir, composeEnv, "build"); err != nil { + if _, err := buildComposeServices(ctx, composeCmd, opts, cfg, composeEnv); err != nil { log.Error("compose build command failed", "composeCmd", composeCmd, "error", err) return nil, fmt.Errorf("build: docker compose build: %w", err) } @@ -676,8 +680,28 @@ func inspectImage(ctx context.Context, image string) (*imageInspect, error) { } // runCompose runs the configured compose CLI (which may be multi-word, e.g. -// "docker compose") with args in dir, returning stdout. +// "docker compose") for non-build operations. Builds must use runComposeBuild: +// inferring them from an argument position could silently undercount attempts. func runCompose(ctx context.Context, composeCmd, dir string, env map[string]string, args ...string) ([]byte, error) { + for _, arg := range append(strings.Fields(composeCmd), args...) { + if arg == "build" { + return nil, fmt.Errorf("publish Compose builds require the counted runComposeBuild helper") + } + } + return executeCompose(ctx, composeCmd, dir, env, args...) +} + +// runComposeBuild separates global Compose options from build options/services, +// ensuring every build attempt counts even with trailing flags or service names. +func runComposeBuild(ctx context.Context, composeCmd, dir string, env map[string]string, prefixArgs []string, buildArgs ...string) ([]byte, error) { + args := append(append([]string{}, prefixArgs...), "build") + args = append(args, buildArgs...) + composeBuildAttempts.Add(1) + return executeCompose(ctx, composeCmd, dir, env, args...) +} + +// executeCompose is shared only by the guarded config and counted build helpers. +func executeCompose(ctx context.Context, composeCmd, dir string, env map[string]string, args ...string) ([]byte, error) { parts := strings.Fields(composeCmd) if len(parts) == 0 { return nil, fmt.Errorf("empty compose command") diff --git a/packages/vm-agent/internal/publish/build_network.go b/packages/vm-agent/internal/publish/build_network.go new file mode 100644 index 0000000000..ffe1673afa --- /dev/null +++ b/packages/vm-agent/internal/publish/build_network.go @@ -0,0 +1,49 @@ +package publish + +import ( + "context" + "fmt" + "os" + "path/filepath" + + "gopkg.in/yaml.v3" +) + +// Compose auto-discovery/overrides are resolved before augmentation. Never +// overwrite the user's compose files or include builder networking in releases. +func buildComposeServices(ctx context.Context, command string, opts BuildOptions, cfg *composeConfig, env map[string]string) ([]byte, error) { + if opts.BuildNetwork == "" { + return runComposeBuild(ctx, command, opts.WorkspaceDir, env, nil) + } + if opts.BuildNetwork != "host" { + return nil, fmt.Errorf("unsupported builder network") + } + base, err := runCompose(ctx, command, opts.WorkspaceDir, env, "config") + if err != nil { + return nil, err + } + temp, err := os.MkdirTemp("", "sam-build-network-") + if err != nil { + return nil, err + } + defer os.RemoveAll(temp) + basePath := filepath.Join(temp, "compose.yaml") + if err = os.WriteFile(basePath, base, 0600); err != nil { + return nil, err + } + services := map[string]any{} + for name, svc := range cfg.Services { + if len(svc.Build) > 0 && string(svc.Build) != "null" { + services[name] = map[string]any{"build": map[string]string{"network": "host"}} + } + } + overlay, err := yaml.Marshal(map[string]any{"services": services}) + if err != nil { + return nil, err + } + overlayPath := filepath.Join(temp, "network.yaml") + if err = os.WriteFile(overlayPath, overlay, 0600); err != nil { + return nil, err + } + return runComposeBuild(ctx, command, opts.WorkspaceDir, env, []string{"--project-directory", opts.WorkspaceDir, "-f", basePath, "-f", overlayPath}) +} diff --git a/packages/vm-agent/internal/publish/build_network_test.go b/packages/vm-agent/internal/publish/build_network_test.go new file mode 100644 index 0000000000..8ff38ce755 --- /dev/null +++ b/packages/vm-agent/internal/publish/build_network_test.go @@ -0,0 +1,138 @@ +package publish + +import ( + "context" + "encoding/json" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestRemoteBuildNetworkPreservesResolvedOverridesAndUserFiles(t *testing.T) { + dir := t.TempDir() + binary := filepath.Join(dir, "docker") + // The fake receiver enforces the real Compose argument boundary and copies + // temporary config while it exists, before the helper cleans up. + script := `#!/bin/sh +if [ "$2" = "config" ]; then + printf 'name: fixture\nservices:\n web:\n image: fixture\n build:\n context: .\n args:\n OVERRIDE: present\n' + exit 0 +fi +if [ "$2" != "--project-directory" ] || [ "$4" != "-f" ] || [ "$6" != "-f" ] || [ "$8" != "build" ]; then exit 91; fi +cp "$5" "$3/captured.yaml" +cp "$7" "$3/network.yaml" +` + if err := os.WriteFile(binary, []byte(script), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + original := []byte("original compose override") + if err := os.WriteFile(filepath.Join(dir, "compose.override.yaml"), original, 0600); err != nil { + t.Fatal(err) + } + cfg := &composeConfig{Services: map[string]composeConfigService{"web": {Build: json.RawMessage(`{"context":"."}`)}, "db": {Image: "postgres"}}} + beforeExecution := ExecutionCounters() + if _, err := buildComposeServices(context.Background(), "docker compose", BuildOptions{WorkspaceDir: dir, BuildNetwork: "host"}, cfg, nil); err != nil { + t.Fatal(err) + } + if ExecutionCounters().ComposeBuildAttempts != beforeExecution.ComposeBuildAttempts+1 { + t.Fatal("host-network build attempt not observed") + } + base, err := os.ReadFile(filepath.Join(dir, "captured.yaml")) + if err != nil || !strings.Contains(string(base), "OVERRIDE: present") { + t.Fatalf("override lost %s %v", base, err) + } + network, err := os.ReadFile(filepath.Join(dir, "network.yaml")) + if err != nil || !strings.Contains(string(network), "network: host") || strings.Contains(string(network), "db:") { + t.Fatalf("network override %s %v", network, err) + } + unchanged, err := os.ReadFile(filepath.Join(dir, "compose.override.yaml")) + if err != nil || string(unchanged) != string(original) { + t.Fatal("source compose was modified") + } +} + +func TestRemoteBuildConfigInterpolatesBeforePathResolution(t *testing.T) { + dir := t.TempDir() + binary := filepath.Join(dir, "docker") + script := `#!/bin/sh +if [ "$2" = "config" ]; then + [ "$#" = 2 ] || exit 92 + [ "$SUBDIR" = "services/api" ] || exit 93 + printf 'services:\n web:\n build:\n context: /resolved/services\n' + exit 0 +fi +[ "$8" = build ] || exit 94 +cp "$5" "$3/captured.yaml" +` + if err := os.WriteFile(binary, []byte(script), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + cfg := &composeConfig{Services: map[string]composeConfigService{"web": {Build: json.RawMessage(`{"context":"${SUBDIR}/.."}`)}}} + if _, err := buildComposeServices(context.Background(), "docker compose", BuildOptions{WorkspaceDir: dir, BuildNetwork: "host"}, cfg, map[string]string{"SUBDIR": "services/api"}); err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(filepath.Join(dir, "captured.yaml")) + if err != nil || !strings.Contains(string(data), "/resolved/services") { + t.Fatalf("resolved build context %q, %v", data, err) + } +} + +// Compose's interpolation/path normalization cannot be represented by a shell +// fixture. This exercises the real config command without a daemon or image. +func TestRemoteBuildRealComposeInterpolatesContextBeforeDotDot(t *testing.T) { + docker, err := exec.LookPath("docker") + if err != nil { + t.Skip("Docker Compose unavailable") + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + if err = exec.CommandContext(ctx, docker, "compose", "version").Run(); err != nil { + t.Skip("Docker Compose plugin unavailable") + } + dir := t.TempDir() + if err = os.MkdirAll(filepath.Join(dir, "services/api"), 0755); err != nil { + t.Fatal(err) + } + compose := []byte("services:\n web:\n image: fixture\n build:\n context: ${SUBDIR}/..\n environment:\n RUNTIME_SECRET: ${RUNTIME_SECRET}\n") + if err = os.WriteFile(filepath.Join(dir, "compose.yaml"), compose, 0600); err != nil { + t.Fatal(err) + } + shim := filepath.Join(dir, "compose-shim") + script := `#!/bin/sh +if [ "$2" = config ]; then exec "$REAL_COMPOSE_DOCKER" "$@"; fi +[ "$8" = build ] || exit 94 +cp "$5" "$3/captured.yaml" +cp "$7" "$3/network.yaml" +` + if err = os.WriteFile(shim, []byte(script), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("REAL_COMPOSE_DOCKER", docker) + cfg := &composeConfig{Services: map[string]composeConfigService{"web": {Build: json.RawMessage(`{"context":"."}`)}}} + env := buildComposeCommandEnv(map[string]string{"SUBDIR": "services/api"}, []string{"RUNTIME_SECRET"}) + if _, err = buildComposeServices(ctx, shim+" compose", BuildOptions{WorkspaceDir: dir, BuildNetwork: "host"}, cfg, env); err != nil { + t.Fatal(err) + } + base, err := os.ReadFile(filepath.Join(dir, "captured.yaml")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(base), "context: "+filepath.Join(dir, "services")) { + t.Fatalf("build context normalized before interpolation: %s", base) + } + if !strings.Contains(string(base), secretInterpolationPlaceholder) { + t.Fatalf("missing harmless runtime placeholder: %s", base) + } + release, err := runCompose(ctx, docker+" compose", dir, nil, "config", "--no-interpolate") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(release), "${RUNTIME_SECRET}") || strings.Contains(string(release), secretInterpolationPlaceholder) || strings.Contains(string(release), "network: host") { + t.Fatalf("release runtime references changed: %s", release) + } +} diff --git a/packages/vm-agent/internal/publish/build_test.go b/packages/vm-agent/internal/publish/build_test.go index 8907e8ace0..6f576b4efc 100644 --- a/packages/vm-agent/internal/publish/build_test.go +++ b/packages/vm-agent/internal/publish/build_test.go @@ -263,6 +263,7 @@ func TestBuildAllowsSafeComposeVolumesBeforeBuild(t *testing.T) { t.Fatalf("write fake compose: %v", err) } + beforeExecution := ExecutionCounters() _, _ = Build(context.Background(), BuildOptions{ WorkspaceDir: dir, ComposeCmd: compose, @@ -270,6 +271,9 @@ func TestBuildAllowsSafeComposeVolumesBeforeBuild(t *testing.T) { if _, statErr := os.Stat(buildMarker); statErr != nil { t.Fatalf("compose build should run after safe named volume validation, stat err: %v", statErr) } + if ExecutionCounters().ComposeBuildAttempts != beforeExecution.ComposeBuildAttempts+1 { + t.Fatal("node publisher build attempt not observed") + } } func TestBuildComposeCommandEnvAddsSecretPlaceholders(t *testing.T) { diff --git a/packages/vm-agent/internal/publish/contextcollect/collect.go b/packages/vm-agent/internal/publish/contextcollect/collect.go index 106c9c9566..2bb232f8c2 100644 --- a/packages/vm-agent/internal/publish/contextcollect/collect.go +++ b/packages/vm-agent/internal/publish/contextcollect/collect.go @@ -32,9 +32,10 @@ type Options struct { Timeout time.Duration } type Result struct { - Bytes int64 `json:"sizeBytes"` - SHA256 string `json:"sha256"` - DurationMs int64 `json:"durationMs"` + ProjectName string `json:"projectName"` + Bytes int64 `json:"sizeBytes"` + SHA256 string `json:"sha256"` + DurationMs int64 `json:"durationMs"` } type budgetWriter struct { ctx context.Context @@ -142,7 +143,7 @@ func Collect(parent context.Context, opts Options, output io.Writer) (*Result, e if err := encoder.Close(); err != nil { return nil, err } - return &Result{Bytes: compressed.n, SHA256: hex.EncodeToString(hash.Sum(nil)), DurationMs: time.Since(started).Milliseconds()}, nil + return &Result{ProjectName: plan.projectName, Bytes: compressed.n, SHA256: hex.EncodeToString(hash.Sum(nil)), DurationMs: time.Since(started).Milliseconds()}, nil } func writeEntry(ctx context.Context, tw *tar.Writer, safe *os.Root, plan *collectionPlan, path, rel string) error { if err := plan.validatePath(path); err != nil { diff --git a/packages/vm-agent/internal/publish/contextcollect/collect_test.go b/packages/vm-agent/internal/publish/contextcollect/collect_test.go index 2a53c6d956..d3a633e37d 100644 --- a/packages/vm-agent/internal/publish/contextcollect/collect_test.go +++ b/packages/vm-agent/internal/publish/contextcollect/collect_test.go @@ -350,3 +350,36 @@ func TestCollectMonorepoScale(t *testing.T) { } t.Logf("100000 files, %d payload bytes, %d compressed bytes, collection %s (reported %dms)", 100000*len(payload), result.Bytes, time.Since(start), result.DurationMs) } + +func TestCollectorRetainsComposeProjectIdentity(t *testing.T) { + for _, name := range []string{"", "explicit-name"} { + t.Run(name, func(t *testing.T) { + root := filepath.Join(t.TempDir(), "Original-Project") + if err := os.Mkdir(root, 0700); err != nil { + t.Fatal(err) + } + compose := "services:\n web:\n build: .\n" + if name != "" { + compose = "name: " + name + "\n" + compose + } + if err := os.WriteFile(filepath.Join(root, "compose.yaml"), []byte(compose), 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "Dockerfile"), []byte("FROM scratch"), 0600); err != nil { + t.Fatal(err) + } + var out bytes.Buffer + result, err := Collect(context.Background(), Options{Root: testRoot(t, root)}, &out) + if err != nil { + t.Fatal(err) + } + expected := name + if expected == "" { + expected = "original-project" + } + if result.ProjectName != expected { + t.Fatalf("project=%q expected%q", result.ProjectName, expected) + } + }) + } +} diff --git a/packages/vm-agent/internal/publish/contextcollect/plan.go b/packages/vm-agent/internal/publish/contextcollect/plan.go index a6b5e78eef..95b4c054ad 100644 --- a/packages/vm-agent/internal/publish/contextcollect/plan.go +++ b/packages/vm-agent/internal/publish/contextcollect/plan.go @@ -20,6 +20,7 @@ type buildContext struct { matchers []*patternmatcher.PatternMatcher } type collectionPlan struct { + projectName string root string source *os.Root contexts []buildContext @@ -74,6 +75,7 @@ func makePlan(ctx context.Context, opts Options) (*collectionPlan, error) { if err != nil { return nil, fmt.Errorf("load Compose build context: %w", err) } + p.projectName = project.Name for _, path := range project.ComposeFiles { if original, ok := graph.originals[path]; ok { path = original diff --git a/packages/vm-agent/internal/publish/docker.go b/packages/vm-agent/internal/publish/docker.go index 814bbc975f..1de44cba0f 100644 --- a/packages/vm-agent/internal/publish/docker.go +++ b/packages/vm-agent/internal/publish/docker.go @@ -24,6 +24,7 @@ func NewHostDocker() *HostDocker { return &HostDocker{} } // Save exports a source image to a docker-save archive path. func (d *HostDocker) Save(ctx context.Context, source, archivePath string) error { cmd := exec.CommandContext(ctx, container.DockerCLIPath(), "save", "-o", archivePath, source) + dockerSaveAttempts.Add(1) if out, err := cmd.CombinedOutput(); err != nil { return fmt.Errorf("docker save %s: %w: %s", source, err, strings.TrimSpace(string(out))) } diff --git a/packages/vm-agent/internal/publish/execution.go b/packages/vm-agent/internal/publish/execution.go new file mode 100644 index 0000000000..97ae066784 --- /dev/null +++ b/packages/vm-agent/internal/publish/execution.go @@ -0,0 +1,30 @@ +package publish + +import ( + "crypto/rand" + "sync/atomic" +) + +var ( + processIncarnation = rand.Text() + composeBuildAttempts atomic.Uint64 + dockerSaveAttempts atomic.Uint64 +) + +// ExecutionSnapshot counts attempted publish-path host commands, including +// failed executions. It does not describe unrelated processes on the node. +type ExecutionSnapshot struct { + ProcessIncarnation string `json:"processIncarnation"` + ComposeBuildAttempts uint64 `json:"composeBuildAttempts"` + DockerSaveAttempts uint64 `json:"dockerSaveAttempts"` +} + +// ExecutionCounters is uncached and safe to call concurrently with publishing. +// Consumers must compare process incarnations before interpreting count deltas. +func ExecutionCounters() ExecutionSnapshot { + return ExecutionSnapshot{ + ProcessIncarnation: processIncarnation, + ComposeBuildAttempts: composeBuildAttempts.Load(), + DockerSaveAttempts: dockerSaveAttempts.Load(), + } +} diff --git a/packages/vm-agent/internal/publish/execution_test.go b/packages/vm-agent/internal/publish/execution_test.go new file mode 100644 index 0000000000..56bed4a064 --- /dev/null +++ b/packages/vm-agent/internal/publish/execution_test.go @@ -0,0 +1,125 @@ +package publish + +import ( + "context" + "os" + "path/filepath" + "sync" + "testing" +) + +func TestExecutionCountersObserveActualBuildAndSaveAttempts(t *testing.T) { + dir := t.TempDir() + binary := filepath.Join(dir, "docker") + if err := os.WriteFile(binary, []byte("#!/bin/sh\nexit 0\n"), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("SAM_DOCKER_CLI_PATH", binary) + before := ExecutionCounters() + if before.ProcessIncarnation == "" { + t.Fatal("missing process identity") + } + if _, err := runCompose(context.Background(), binary+" compose", dir, nil, "config"); err != nil { + t.Fatal(err) + } + if after := ExecutionCounters(); after != before { + t.Fatal("config must not count as build/save") + } + if _, err := buildComposeServices(context.Background(), binary+" compose", BuildOptions{WorkspaceDir: dir}, nil, nil); err != nil { + t.Fatal(err) + } + if after := ExecutionCounters(); after.ComposeBuildAttempts != before.ComposeBuildAttempts+1 || after.DockerSaveAttempts != before.DockerSaveAttempts { + t.Fatalf("build attempt not observed: %+v -> %+v", before, after) + } + if err := NewHostDocker().Save(context.Background(), "fixture", filepath.Join(dir, "image.tar")); err != nil { + t.Fatal(err) + } + after := ExecutionCounters() + if after.ProcessIncarnation != before.ProcessIncarnation || after.ComposeBuildAttempts != before.ComposeBuildAttempts+1 || after.DockerSaveAttempts != before.DockerSaveAttempts+1 { + t.Fatalf("save attempt not observed: %+v -> %+v", before, after) + } + // Failed execution attempts must count too: success-only counters could hide a + // source build/save that failed before producing an image. + t.Setenv("SAM_DOCKER_CLI_PATH", filepath.Join(dir, "missing")) + if err := NewHostDocker().Save(context.Background(), "fixture", "unused"); err == nil { + t.Fatal("expected exec failure") + } + if ExecutionCounters().DockerSaveAttempts != after.DockerSaveAttempts+1 { + t.Fatal("failed save not observed") + } + if _, err := buildComposeServices(context.Background(), filepath.Join(dir, "missing"), BuildOptions{WorkspaceDir: dir}, nil, nil); err == nil { + t.Fatal("expected build exec failure") + } + if ExecutionCounters().ComposeBuildAttempts != after.ComposeBuildAttempts+1 { + t.Fatal("failed build not observed") + } +} + +func TestExecutionCountersConcurrentReadsDuringBuild(t *testing.T) { + dir := t.TempDir() + binary := filepath.Join(dir, "compose") + if err := os.WriteFile(binary, []byte("#!/bin/sh\nexit 0\n"), 0700); err != nil { + t.Fatal(err) + } + before := ExecutionCounters() + var readers sync.WaitGroup + done := make(chan struct{}) + readers.Go(func() { + for { + select { + case <-done: + return + default: + _ = ExecutionCounters() + } + } + }) + for range 8 { + if _, err := buildComposeServices(context.Background(), binary, BuildOptions{WorkspaceDir: dir}, nil, nil); err != nil { + close(done) + readers.Wait() + t.Fatal(err) + } + } + close(done) + readers.Wait() + if ExecutionCounters().ComposeBuildAttempts != before.ComposeBuildAttempts+8 { + t.Fatal("writer did not execute") + } +} + +func TestGenericComposeRefusesUncountedBuild(t *testing.T) { + dir := t.TempDir() + binary := filepath.Join(dir, "compose") + if err := os.WriteFile(binary, []byte("#!/bin/sh\nexit 0\n"), 0700); err != nil { + t.Fatal(err) + } + before := ExecutionCounters() + for _, args := range [][]string{{"build"}, {"build", "web"}, {"build", "--pull"}} { + if _, err := runCompose(context.Background(), binary, dir, nil, args...); err == nil { + t.Fatalf("uncounted build allowed: %v", args) + } + } + if _, err := runCompose(context.Background(), binary+" build", dir, nil, "web"); err == nil { + t.Fatal("embedded uncounted build allowed") + } + if after := ExecutionCounters(); after != before { + t.Fatal("refused commands must not execute") + } +} + +func TestCountedComposeBuildIncludesTrailingServiceAndOptions(t *testing.T) { + dir := t.TempDir() + binary := filepath.Join(dir, "compose") + script := "#!/bin/sh\n[ \"$1\" = --project-directory ] && [ \"$3\" = build ] && [ \"$4\" = --pull ] && [ \"$5\" = web ]\n" + if err := os.WriteFile(binary, []byte(script), 0700); err != nil { + t.Fatal(err) + } + before := ExecutionCounters() + if _, err := runComposeBuild(context.Background(), binary, dir, nil, []string{"--project-directory", dir}, "--pull", "web"); err != nil { + t.Fatal(err) + } + if after := ExecutionCounters(); after.ComposeBuildAttempts != before.ComposeBuildAttempts+1 || after.DockerSaveAttempts != before.DockerSaveAttempts { + t.Fatalf("trailing service build not counted: %+v -> %+v", before, after) + } +} diff --git a/packages/vm-agent/internal/server/mcp_build_context.go b/packages/vm-agent/internal/server/mcp_build_context.go index 5183ea6ac3..f2e40a461e 100644 --- a/packages/vm-agent/internal/server/mcp_build_context.go +++ b/packages/vm-agent/internal/server/mcp_build_context.go @@ -118,7 +118,7 @@ func (s *Server) runAcceptedContextCollection(ctx context.Context, cancel contex event.Terminal = true } if result != nil { - event.Detail = map[string]any{"sizeBytes": result.Bytes, "sha256": result.SHA256, "durationMs": result.DurationMs} + event.Detail = map[string]any{"sizeBytes": result.Bytes, "sha256": result.SHA256, "durationMs": result.DurationMs, "projectName": result.ProjectName} } reportTimeout := s.config.HTTPCallbackTimeout if reportTimeout <= 0 { @@ -158,7 +158,7 @@ func (s *Server) collectAndUploadBuildContext(ctx context.Context, workspaceID, } collectCancel() callbackPath := "/api/projects/" + url.PathEscape(projectID) + "/deployment-publish-jobs/" + url.PathEscape(jobID) + "/context/" - body := map[string]any{"attempt": req.Attempt, "sizeBytes": result.Bytes, "sha256": result.SHA256, "durationMs": result.DurationMs} + body := map[string]any{"attempt": req.Attempt, "sizeBytes": result.Bytes, "sha256": result.SHA256, "durationMs": result.DurationMs, "projectName": result.ProjectName} var slot struct { UploadURL string `json:"uploadUrl"` } diff --git a/packages/vm-agent/internal/server/mcp_build_context_test.go b/packages/vm-agent/internal/server/mcp_build_context_test.go index 28e75fa5e4..f0d74467d8 100644 --- a/packages/vm-agent/internal/server/mcp_build_context_test.go +++ b/packages/vm-agent/internal/server/mcp_build_context_test.go @@ -29,6 +29,7 @@ func TestBuildContextCollectRouteBothRuntimesLarge(t *testing.T) { }{{"VM", false, false, false}, {"Instant", true, false, false}, {"VMShadow", false, true, false}, {"InstantShadow", true, true, false}, {"CancelShadowUpload", false, true, true}} { instant, shadow, cancelUpload := tc.instant, tc.shadow, tc.cancel t.Run(tc.name, func(t *testing.T) { + beforeExecution := publish.ExecutionCounters() temp := t.TempDir() t.Setenv("TMPDIR", temp) s, key := mcpBuildTestServer(t) @@ -199,6 +200,11 @@ func TestBuildContextCollectRouteBothRuntimesLarge(t *testing.T) { } mu.Lock() defer mu.Unlock() + // The Cloudflare source path collects context instead of running the + // host publisher. Config/discovery Docker calls do not count as builds. + if after := publish.ExecutionCounters(); after != beforeExecution { + t.Fatalf("context collection ran host build/save: %+v -> %+v", beforeExecution, after) + } if finalEvent.Status != expected || finalEvent.Terminal != (shadow || cancelUpload) { t.Fatalf("wrong final callback: %+v", finalEvent) } diff --git a/packages/vm-agent/internal/server/system_info.go b/packages/vm-agent/internal/server/system_info.go index 9e2f34fd4f..b13f2574d7 100644 --- a/packages/vm-agent/internal/server/system_info.go +++ b/packages/vm-agent/internal/server/system_info.go @@ -3,6 +3,9 @@ package server import ( "log/slog" "net/http" + + "github.com/workspace/vm-agent/internal/publish" + "github.com/workspace/vm-agent/internal/sysinfo" ) // handleSystemInfo returns full system metrics for the node. @@ -24,5 +27,11 @@ func (s *Server) handleSystemInfo(w http.ResponseWriter, r *http.Request) { return } - writeJSON(w, http.StatusOK, info) + // The collector caches slow Docker/system metrics. Read execution counters + // separately so before/after observations cannot reuse that cached snapshot. + w.Header().Set("Cache-Control", "no-store") + writeJSON(w, http.StatusOK, struct { + *sysinfo.SystemInfo + PublishExecution publish.ExecutionSnapshot `json:"publishExecution"` + }{info, publish.ExecutionCounters()}) } diff --git a/packages/vm-agent/internal/server/system_info_execution_test.go b/packages/vm-agent/internal/server/system_info_execution_test.go new file mode 100644 index 0000000000..9fdea6bafa --- /dev/null +++ b/packages/vm-agent/internal/server/system_info_execution_test.go @@ -0,0 +1,65 @@ +package server + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/workspace/vm-agent/internal/publish" +) + +func TestSystemInfoExecutionSnapshotIsAuthenticatedAndUncached(t *testing.T) { + fx := newDiagnosticAuthFixture(t) + defer fx.stop() + fx.server.sysInfoCollector = stubCollector(1, 20, 30) + dir := t.TempDir() + binary := filepath.Join(dir, "docker") + if err := os.WriteFile(binary, []byte("#!/bin/sh\nexit 1\n"), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir) + t.Setenv("SAM_DOCKER_CLI_PATH", binary) + read := func(token string) (*httptest.ResponseRecorder, publish.ExecutionSnapshot) { + t.Helper() + req := httptest.NewRequest(http.MethodGet, "/system-info", nil) + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + rec := httptest.NewRecorder() + fx.server.handleSystemInfo(rec, req) + var body struct { + PublishExecution publish.ExecutionSnapshot `json:"publishExecution"` + } + if rec.Code == http.StatusOK { + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + if rec.Header().Get("Cache-Control") != "no-store" { + t.Fatal("diagnostics can be cached") + } + } + return rec, body.PublishExecution + } + for _, token := range []string{"", fx.workspaceMgmtA} { + rec, _ := read(token) + if rec.Code == http.StatusOK { + t.Fatal("execution counters exposed without node authorization") + } + } + rec, before := read(fx.nodeToken) + if rec.Code != http.StatusOK || before.ProcessIncarnation == "" { + t.Fatalf("snapshot unavailable: %d", rec.Code) + } + // A failed actual Save must be visible even while system metrics are cached. + if err := publish.NewHostDocker().Save(context.Background(), "fixture", "unused"); err == nil { + t.Fatal("expected failed save") + } + rec, after := read(fx.nodeToken) + if rec.Code != http.StatusOK || after.ProcessIncarnation != before.ProcessIncarnation || after.DockerSaveAttempts != before.DockerSaveAttempts+1 { + t.Fatalf("stale snapshot: %+v -> %+v", before, after) + } +} diff --git a/packages/worker-core/src/schema.ts b/packages/worker-core/src/schema.ts index 109cb5cba2..643a35716e 100644 --- a/packages/worker-core/src/schema.ts +++ b/packages/worker-core/src/schema.ts @@ -5358,10 +5358,14 @@ export const deploymentPublishJobs = sqliteTable( errorCode: text('error_code'), retryable: integer('retryable', { mode: 'boolean' }).notNull().default(false), executor: text('executor').notNull().default('node'), + executorInstanceId: text('executor_instance_id'), + executorDeadlineAt: text('executor_deadline_at'), + executorNotBefore: text('executor_not_before'), contextShadow: integer('context_shadow', { mode: 'boolean' }).notNull().default(false), contextR2Key: text('context_r2_key'), contextBytes: integer('context_bytes'), contextSha256: text('context_sha256'), + contextProjectName: text('context_project_name'), queuedAt: text('queued_at'), attempt: integer('attempt').notNull().default(1), lastEventAt: text('last_event_at'), diff --git a/scripts/deploy/installer-build-cache.mjs b/scripts/deploy/installer-build-cache.mjs index 36b8f73226..8b10c5d2c6 100644 --- a/scripts/deploy/installer-build-cache.mjs +++ b/scripts/deploy/installer-build-cache.mjs @@ -46,6 +46,7 @@ export const VM_AGENT_OUTPUTS = [ 'packages/vm-agent/bin/vm-agent-darwin-amd64', 'packages/vm-agent/bin/vm-agent-darwin-arm64', 'apps/api/container-artifacts/vm-agent-linux-amd64', + 'apps/api/container-artifacts/sam-builder-linux-amd64', 'apps/api/container-artifacts/install-opencode.sh', 'apps/api/container-artifacts/vm-agent-version.json', ]; diff --git a/scripts/deploy/installer-engine-ci-env.json b/scripts/deploy/installer-engine-ci-env.json index 4dbd6bf659..40ac71acaf 100644 --- a/scripts/deploy/installer-engine-ci-env.json +++ b/scripts/deploy/installer-engine-ci-env.json @@ -569,7 +569,9 @@ "SETUP_SESSION_SWEEP_MAX_CANDIDATES": "${{ vars.SETUP_SESSION_SWEEP_MAX_CANDIDATES }}", "POOL_LEASE_BUFFER_MS": "${{ vars.POOL_LEASE_BUFFER_MS }}", "SANDBOX_EXEC_TIMEOUT_MS": "${{ vars.SANDBOX_EXEC_TIMEOUT_MS }}", - "SANDBOX_VM_AGENT_PORT": "${{ vars.SANDBOX_VM_AGENT_PORT }}" + "SANDBOX_VM_AGENT_PORT": "${{ vars.SANDBOX_VM_AGENT_PORT }}", + "DEPLOY_BUILDER_MAX_INSTANCES": "${{ vars.DEPLOY_BUILDER_MAX_INSTANCES }}", + "DEPLOY_BUILDER_INSTANCE_TYPE": "${{ vars.DEPLOY_BUILDER_INSTANCE_TYPE }}" } }, { diff --git a/scripts/deploy/installer-engine.test.ts b/scripts/deploy/installer-engine.test.ts index 8b44001f7e..dd6575a113 100644 --- a/scripts/deploy/installer-engine.test.ts +++ b/scripts/deploy/installer-engine.test.ts @@ -110,6 +110,7 @@ const BUILT_FILES: Record = { 'prepare-container': [ 'packages/vm-agent/bin/vm-agent-linux-amd64', 'apps/api/container-artifacts/vm-agent-linux-amd64', + 'apps/api/container-artifacts/sam-builder-linux-amd64', 'apps/api/container-artifacts/install-opencode.sh', ], 'vm-agent build-all': [ diff --git a/scripts/deploy/sync-wrangler-config.ts b/scripts/deploy/sync-wrangler-config.ts index 5b65974a5f..c3c3afce89 100644 --- a/scripts/deploy/sync-wrangler-config.ts +++ b/scripts/deploy/sync-wrangler-config.ts @@ -179,6 +179,7 @@ const CONTAINER_MAX_INSTANCE_CONFIG = { envVar: 'SANDBOX_CONTAINER_MAX_INSTANCES', defaultValue: DEFAULT_SANDBOX_CONTAINER_MAX_INSTANCES, }, + ComposeBuilderContainer: { envVar: 'DEPLOY_BUILDER_MAX_INSTANCES', defaultValue: 6 }, VmAgentContainer: { envVar: 'VM_AGENT_CONTAINER_MAX_INSTANCES', defaultValue: DEFAULT_VM_AGENT_CONTAINER_MAX_INSTANCES, @@ -310,6 +311,13 @@ export function containerImageOverrides( return parsed as Record; } +function getBuilderInstanceType(): string { + const value = process.env.DEPLOY_BUILDER_INSTANCE_TYPE?.trim() || 'standard-4'; + if (!['lite', 'basic', 'standard-1', 'standard-2', 'standard-3', 'standard-4'].includes(value)) + throw new Error('DEPLOY_BUILDER_INSTANCE_TYPE must name a supported Cloudflare instance type'); + return value; +} + function generateContainerBindings( containers: ContainerBinding[] | undefined ): ContainerBinding[] | undefined { @@ -317,6 +325,9 @@ function generateContainerBindings( return containers?.map((container) => ({ ...container, image: overrides[container.class_name] ?? container.image, + ...(container.class_name === 'ComposeBuilderContainer' + ? { instance_type: getBuilderInstanceType() } + : {}), max_instances: getConfiguredContainerMaxInstances( container.class_name, container.max_instances @@ -644,6 +655,9 @@ export function getApiWorkerVars( ...(process.env.PREVIEW_URL_TTL_SECONDS ? { PREVIEW_URL_TTL_SECONDS: process.env.PREVIEW_URL_TTL_SECONDS } : {}), + DEPLOY_BUILDER_CLASS_MAX_INSTANCES: String( + parseContainerMaxInstances('DEPLOY_BUILDER_MAX_INSTANCES', 6) + ), VERSION: DEPLOYMENT_CONFIG.version, PAGES_PROJECT_NAME: outputs.pagesName, SAM_INSTALLATION_ID: outputs.installationId, diff --git a/scripts/quality/dependency-governance.test.ts b/scripts/quality/dependency-governance.test.ts index 6a55b3455a..4dc55217c9 100644 --- a/scripts/quality/dependency-governance.test.ts +++ b/scripts/quality/dependency-governance.test.ts @@ -1,5 +1,6 @@ -import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; -import { join, posix, relative } from 'node:path'; +import { execFileSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import { join, posix } from 'node:path'; import { describe, expect, it } from 'vitest'; @@ -10,22 +11,17 @@ function read(path: string): string { } function walk(dir: string, predicate: (path: string) => boolean): string[] { - const absoluteDir = join(root, dir); - if (!existsSync(absoluteDir)) return []; - - const paths: string[] = []; - for (const entry of readdirSync(absoluteDir)) { - if (entry === 'node_modules' || entry === '.git') continue; - const absolutePath = join(absoluteDir, entry); - const repoPath = posix.normalize(relative(root, absolutePath).replaceAll('\\', '/')); - const stats = statSync(absolutePath); - if (stats.isDirectory()) { - paths.push(...walk(repoPath, predicate)); - } else if (predicate(repoPath)) { - paths.push(repoPath); - } - } - return paths.sort(); + // Inventory repository inputs, including new files under review, without + // traversing ignored caches, node_modules or private agent runtime state. + const files = execFileSync( + 'git', + ['ls-files', '--cached', '--others', '--exclude-standard', '-z'], + { cwd: root, encoding: 'utf8' } + ) + .split('\0') + .filter(Boolean); + const prefix = dir === '.' ? '' : `${dir}/`; + return files.filter((path) => path.startsWith(prefix) && predicate(path)).sort(); } function extractDependabotDirectories(ecosystem: string): Set { @@ -134,6 +130,7 @@ describe('dependency governance', () => { const refs = [...dockerFromRefs(dockerfiles), ...dockerRefsInTextFiles(workflowFiles)]; expect(dockerfiles).toEqual([ + 'apps/api/Dockerfile.compose-builder', 'apps/api/Dockerfile.sandbox', 'apps/api/Dockerfile.vm-agent-container', 'scripts/e2e/workspace-mock/Dockerfile', diff --git a/scripts/quality/do-migration-compatibility.test.ts b/scripts/quality/do-migration-compatibility.test.ts index 626f71543d..30cae822a1 100644 --- a/scripts/quality/do-migration-compatibility.test.ts +++ b/scripts/quality/do-migration-compatibility.test.ts @@ -63,11 +63,11 @@ describe('resolveDurableObjectMigrations', () => { const resolved = resolveDurableObjectMigrations(history, null); - expect(history).toHaveLength(22); + expect(history).toHaveLength(23); expect(legacyCreateCount).toBe(7); expect(resolved).toHaveLength(history.length); expect(resolved.every((migration) => migration.new_classes === undefined)).toBe(true); - expect(resolved.flatMap((migration) => migration.new_sqlite_classes ?? [])).toHaveLength(23); + expect(resolved.flatMap((migration) => migration.new_sqlite_classes ?? [])).toHaveLength(24); expect(loadCheckedInMigrations()).toEqual(history); }); @@ -92,7 +92,10 @@ describe('resolveDurableObjectMigrations', () => { const history = loadCheckedInMigrations(); const created = new Set(); for (const migration of history) { - for (const name of [...(migration.new_classes ?? []), ...(migration.new_sqlite_classes ?? [])]) + for (const name of [ + ...(migration.new_classes ?? []), + ...(migration.new_sqlite_classes ?? []), + ]) created.add(name); for (const name of (migration as { deleted_classes?: string[] }).deleted_classes ?? []) created.delete(name); @@ -104,7 +107,10 @@ describe('resolveDurableObjectMigrations', () => { const exported = new Set(); for (const match of indexSource.matchAll(/^export \{([^}]*)\} from /gm)) { for (const part of match[1]!.split(',')) { - const name = part.trim().split(/\s+as\s+/).at(-1); + const name = part + .trim() + .split(/\s+as\s+/) + .at(-1); if (name) exported.add(name); } } @@ -120,7 +126,7 @@ describe('resolveDurableObjectMigrations', () => { const latestTag = history.at(-1)?.tag; vi.stubEnv('RESOURCE_PREFIX', 's123abc'); - expect(latestTag).toBe('v22'); + expect(latestTag).toBe('v23'); const resolved = resolveDurableObjectMigrations(history, latestTag ?? null); const envConfig = generateApiWorkerEnv( { migrations: history }, @@ -136,12 +142,21 @@ describe('resolveDurableObjectMigrations', () => { expect(envConfig.migrations).toEqual(history); }); + it('adds the builder SQLite class after the immutable deployed v22 prefix', () => { + const history = loadCheckedInMigrations(); + const resolved = resolveDurableObjectMigrations(history, 'v22'); + expect(resolved.slice(0, 22)).toEqual(history.slice(0, 22)); + expect(resolved.slice(22)).toEqual([ + { tag: 'v23', new_sqlite_classes: ['ComposeBuilderContainer'] }, + ]); + }); + it('appends both Reliability SQLite classes after an unchanged deployed v21 prefix', () => { const history = loadCheckedInMigrations(); const resolved = resolveDurableObjectMigrations(history, 'v21'); expect(resolved.slice(0, 21)).toEqual(history.slice(0, 21)); resolved.slice(0, 21).forEach((entry, index) => expect(entry).toBe(history[index])); - expect(resolved.slice(21)).toEqual([ + expect(resolved.slice(21, 22)).toEqual([ { tag: 'v22', new_sqlite_classes: ['McpRateCounter', 'WorkspaceBootLog'] }, ]); const clean = resolveDurableObjectMigrations(history, null); diff --git a/scripts/quality/runtime-tunables-baseline.json b/scripts/quality/runtime-tunables-baseline.json index 7beb1d2564..49ee48a84f 100644 --- a/scripts/quality/runtime-tunables-baseline.json +++ b/scripts/quality/runtime-tunables-baseline.json @@ -1315,6 +1315,7 @@ "WWW_PAGES_PROJECT_NAME" ], "bootstrapExceptions": { + "DEPLOY_BUILDER_CLASS_MAX_INSTANCES": "Deploy-generated mirror of the actual ComposeBuilderContainer max_instances, required to clamp runtime admission to the deployed class capacity. Runtime edits cannot resize the Cloudflare application. Builder admission controls remain admin settings.", "AGENT_EMAIL_WORKER_NAME": "Deploy-generated name of this Worker's own script, emitted by scripts/deploy/sync-wrangler-config.ts only together with the AGENT_EMAIL send binding. The agent email admin setup points the Email Routing rule at it, so it must not be admin-editable: another value would route agent mail to a different Worker.", "BOOTSTRAP_OWNER_EMAIL": "Installer-approved initial administrator identity, supplied as a Worker secret before first authentication and preserved across updates. Changing ownership requires an authenticated transfer, not an operational runtime setting.", "VM_AGENT_TRANSPORT": "Provisioning topology for new managed VM incarnations only. Must be selected with deployment-owned Cloudflare token permissions; persisted transport and DNS ownership remain unchanged for existing nodes. A live setting must not imply migration of running VMs.", diff --git a/scripts/quality/sync-wrangler-config.test.ts b/scripts/quality/sync-wrangler-config.test.ts index 31335a24f8..dc2c695a4c 100644 --- a/scripts/quality/sync-wrangler-config.test.ts +++ b/scripts/quality/sync-wrangler-config.test.ts @@ -1472,3 +1472,52 @@ describe('Worker vars omitted because they equal the code default', () => { expect(lines).toEqual([' Environment override: OMITTED="5" replaces code default "9"']); }); }); + +describe('dedicated Compose builder deployment settings', () => { + afterEach(() => vi.unstubAllEnvs()); + it('mirrors actual class capacity into admission and supports instance sizing overrides', () => { + vi.stubEnv('RESOURCE_PREFIX', 's123abc'); + vi.stubEnv('DEPLOY_BUILDER_MAX_INSTANCES', '4'); + vi.stubEnv('DEPLOY_BUILDER_INSTANCE_TYPE', 'standard-3'); + const generated = generateApiWorkerEnv( + { + containers: [ + { + class_name: 'ComposeBuilderContainer', + image: './Dockerfile.compose-builder', + instance_type: 'standard-4', + max_instances: 6, + }, + ], + }, + outputs, + 'staging', + false, + false, + null + ); + expect(generated.containers).toEqual([ + { + class_name: 'ComposeBuilderContainer', + image: './Dockerfile.compose-builder', + instance_type: 'standard-3', + max_instances: 4, + }, + ]); + expect(generated.vars?.DEPLOY_BUILDER_CLASS_MAX_INSTANCES).toBe('4'); + }); + it('fails closed on an invalid builder instance type', () => { + vi.stubEnv('RESOURCE_PREFIX', 's123abc'); + vi.stubEnv('DEPLOY_BUILDER_INSTANCE_TYPE', 'typo'); + expect(() => + generateApiWorkerEnv( + { containers: [{ class_name: 'ComposeBuilderContainer', image: 'image' }] }, + outputs, + 'staging', + false, + false, + null + ) + ).toThrow('DEPLOY_BUILDER_INSTANCE_TYPE'); + }); +}); diff --git a/specs/001-mvp/contracts/api.md b/specs/001-mvp/contracts/api.md index 72238f055e..2e869d4460 100644 --- a/specs/001-mvp/contracts/api.md +++ b/specs/001-mvp/contracts/api.md @@ -832,8 +832,14 @@ These internal callbacks use a live workspace callback JWT, not a browser sessio - `POST /api/projects/:id/deployment-publish-jobs/:jobId/context/init` - `POST /api/projects/:id/deployment-publish-jobs/:jobId/context/complete` -Both accept `{ attempt, sizeBytes, sha256, durationMs? }`. Identity, environment and object key come from the authorized job; the job must use `executor=cloudflare`. Init conditionally changes `queued` to `collecting`, records the descriptor, and returns a short-lived presigned R2 PUT. Complete verifies HEAD size plus recorded digest metadata and conditionally changes `collecting` to `context_ready`, setting `queued_at`. Scope/attempt/descriptor mismatch or terminal state returns 409; invalid/missing objects return 400. Successful transitions and collection timing are recorded atomically in job history. SHA metadata is a source assertion; the future builder must verify downloaded bytes. Context completion does not dispatch a build. +Both accept `{ attempt, sizeBytes, sha256, durationMs?, projectName? }`. Non-shadow Cloudflare jobs require the collected Compose project name; receipts bind it alongside size and SHA. Identity, environment and object key come from the authorized job; the job must use `executor=cloudflare`. Init conditionally changes `queued` to `collecting`, records the descriptor, and returns a short-lived presigned R2 PUT. Complete verifies HEAD size plus recorded digest metadata and conditionally changes `collecting` to `context_ready`, setting `queued_at`. Scope/attempt/descriptor mismatch or terminal state returns 409; invalid/missing objects return 400. Successful transitions and collection timing are recorded atomically in job history. SHA metadata is a source assertion; the builder verifies downloaded bytes before extraction. Non-shadow completion attempts Cloudflare admission, then cron drains queued jobs under atomic project/platform/class caps. The node-management endpoint `POST /workspaces/:workspaceId/mcp/build-and-publish-jobs/:jobId/collect` accepts a source-owned job with `202`, then collects, spools, uploads, and completes one context from the devcontainer volume (VM) or `/workspaces` (Instant). `attempt` is required; optional `workingDir`, `buildInterpolationEnv`, `secretInterpolationKeys`, `maxBytes`, and `collectTimeoutMs` are supplied by the control plane. Missing legacy routes return an explicit unsupported capability result to callers. Existing node build/start routes are unchanged. -Shadow probes (`context_shadow=1`) are internal rows only. They cannot link a release, are excluded from publish status/cancel reads and public lifecycle events/counts, and terminalize through normal source callbacks or the existing sweep. The typed collection-mode setting defaults off; shadow kickoff is bounded and does not delay the normal node path or Instant early gate. +Shadow probes (`context_shadow=1`) are internal rows only. They cannot link a release, are excluded from publish status/cancel reads and public lifecycle events/counts, and terminalize through normal source callbacks or the existing sweep. The typed collection-mode setting defaults off; shadow kickoff is bounded and does not delay the normal node path or Cloudflare execution. + +## Cloudflare publish-job callback identity + +The existing publish-job events, artifact init/complete and compose release callbacks additionally accept a `publish-job` callback JWT bound to `{jobId,projectId,environmentId,agentProfileId,attempt}`. It expires at the persisted builder deadline and is valid only for the matching nonterminal, non-shadow Cloudflare job. Source-workspace/node liveness is not required. Other callback routes (including context uploads, registry credentials and token renewal) reject this scope. + +`GET /api/projects/:id/deployment-publish-jobs/:jobId/spec` uses this job identity to return the verified context's presigned GET, size, SHA, Compose project name, non-secret build variables and secret key names. Job tokens cannot request another job or environment. Artifact keys use the exact job-and-attempt upload namespace. Release submissions from job tokens must include matching job ID, attempt, environment, profile and task; the legacy unfenced path remains workspace-token-only. Event updates fence the current attempt atomically, and event release metadata must reference the already-linked release. diff --git a/tasks/active/2026-11-14-cloudflare-build-executor.md b/tasks/active/2026-11-14-cloudflare-build-executor.md new file mode 100644 index 0000000000..356bd0859d --- /dev/null +++ b/tasks/active/2026-11-14-cloudflare-build-executor.md @@ -0,0 +1,154 @@ +# Cloudflare deployment build executor (phase 3) + +SAM task 01M7C1SRMAWR3PYFWKF03XJ273; idea 01KZ6V37D1QGDR3WN12PSDB0QD. + +## Preflight / research + +Classes: external-api-change, cross-component-change, business-logic-change, public-surface-change, docs-sync-change, security-sensitive-change, infra-change. +Read entire Nov6 implementation plan, phase0 attempt2 report (library01M6SMMAP4EHXKAGJ4G25ZXXK1), and merged phase2 #2605 body. Current main099c278d, latest DO migration v22 (use v23); portable collector and callback receipt replay already shipped. Official references: https://developers.cloudflare.com/containers/configuration/outbound-traffic/, https://developers.cloudflare.com/containers/api/durable-object-container/, https://developers.cloudflare.com/sandbox/sdk/guides/docker-in-docker/. Use installed containers0.3.7 API/types; avoid unrelated SDK migration. + +Data flow: MCP compose-publish-tools → app-deployment job/executor selection → existing source collect route → existing context callback → atomic admission → ComposeBuilderContainer(jobId) → sam-builder → internal/publish → existing artifact/events/release callbacks → existing deployment VM apply. Builder identity never depends on source liveness. Keep node_id source meaning and existing node cascade limitation. + +Spike: standard-4 only demonstrated, overlayfs, root dockerd/cgroupfs, /tmp mount, build.network host required. Keep20min deadline and60s readiness. >100MiB real R2 PUT/GET not measured; mandatory here. Root RUN can access builder-local state: no broad credentials, job token scope exactly one job. The original deny-default egress proposal was superseded by Raphaël’s November 15 unrestricted-egress approval. No runtime secret values supplied. + +## Implementation + +- [x] Publish-job JWT and dual callback authorization; atomically fence attempt; env/profile/job artifact identity. +- [x] Atomic D1 admission, project2/platform6 clamped class maximum; queue/backoff/drain, no silent source fallback. +- [x] Builder Go supervisor: safe bounded download/hash/extraction, daemon startup/readiness, host network augmentation, existing publish engine, signals/heartbeats. +- [x] ComposeBuilderContainer alarm/terminal lifecycle; image, env instance type, max config, v23 SQLite migration and allowlist. +- [x] Runtime admin executor selection, Instant cloudflare, VM node default, old-agent compatibility. +- [x] Guide/config/self-host docs and contract updates. +- [x] Local meaningful regression/contract/admission tests, lint/type/build gates (new fix exact-head CI pending). +- [ ] Independent security/domain/completion reviews resolved. +- [ ] Explicit staging slot;100% rollout plus node AND builder version proof. +- [ ] Real Instant publish then source sleep/app serving; VM cloudflare source no build/save; >100MiB presigned GET and PUT. +- [ ] Clean tasks/chats/nodes; immediate and >5min D1 audits. +- [ ] Draft PR needs-human-review, CI, CodeRabbit request/wait; send URL/full SHA/gates to coordinator then STOP. + +Never commit to main. Preserve .codex/config.toml environment change. Staging Claude VMs0.2CPU/0.5GB. Known archive flake retry at most once. No merge absent coordinator exact-SHA approval. + +## Implementation validation state — 2026-11-14 + +Auth/admission and Go supervisor pushed in fe4ffa848 /27fda1536. Container/cron/admin/config integration now uses durable alarm kickoff (HTTP callback returns promptly), idempotent acceptance across SDK healthy state, stop-confirmed capacity backoff, destruction before database deadline verdict, and explicit retry of failed deadline destruction. Root lint and typecheck passed; focused executor tests85PASS and Go race builder/publish/contextcollector PASS. Full root tests hit unrelated archive/UI timing failures under concurrent load; bounded isolated retries pending. Migration/config tests91PASS. Network allowlist remains a known unvalidated placeholder: SDK outbound handler100MiB limit and CA propagation into arbitrary RUN images conflict with required transfer/build semantics. Coordinator requested human approval for open egress; not granted yet. Draft PR #2721 is open with needs-human-review. A staging slot has been requested but not granted; no staging resources have been used. +Adjacent fixes logged: Compose project-name provenance01M7C3V7PQWQFXX8H3Y6J9A59Q; self-host build-cache binary manifest01M7C5YZ354D72XZX7K6F70HHE. Cache/prebuilt manifest must include new builder binary or skip-compile restore cannot build its image. Callback/bootstrap operational budgets are configurable; context GET reuses existing configured URL TTL. + +## Migration coordination — 2026-11-14 05:40 UTC + +Merged current main `8409636ec` without conflicts; DO migration tag remains v22 on main, so builder adds v23. Renumbered the unapplied builder D1 migration to `0240_cloudflare_build_executor.sql`: PR #2693 already owns 0239. Checked other open PR migration paths before choosing 0240. Migration safety and ordering both pass. The main merge touches none of Deploy Installer’s push path filters. Egress decision and explicit staging grant remain pending; no staging deployment or migration has run. + +## CI regression fixes — 2026-11-14 + +The complete API test run exposed stale phase-2 shadow fixtures and the central JWT verifier inventory guard. Signature and claim verification now lives in `services/jwt.ts`; `publish-job-token.ts` retains exact live job-row and attempt binding. Generic callback sinks still reject publish-job tokens. The shadow fixture explicitly selects the node default and resets its deferred fetch mock; Instant asserts a real nonshadow Cloudflare job. Focused fixture/JWT tests: 26 passed. Independent security review passed the verifier move with no new trust-boundary blocker. Logged as idea `01M7CAY9AC980PT4AB9DV0B45M`. + +## Approved egress and current-main refresh — 2026-11-15 + +Raphaël approved unrestricted internet access for Cloudflare deployment builds, like VM workspaces, with direct presigned transfers (knowledge `CloudflareDeploymentBuilds`, observation `d00e0407-5a12-431a-aeff-5d35a7694e5e`). Removed the provisional host allowlist, HTTPS interception and CA installer. Security architecture, deployments guide, configuration reference and self-hosting note describe arbitrary root RUN authority, in-memory job token, callback revocation, object-URL expiry and microVM deadline destruction with code paths. + +Merged main `fd0be69bd` without conflicts, preserving published history. The merge touches no Deploy Installer trigger paths. Main’s newest D1 migration is 0241; renamed the never-applied builder migration to `0242_cloudflare_build_executor.sql` at the coordinator’s request. Manually checked all ten other open PR migration lists: no 0242 collision. DO tag remains v23 after main’s v22. Migration safety, ordering and DO safety pass. + +Fresh security code review passed. Cloudflare review identified an SDK 0.3.7 reconstruction dependency: a running guest requires the Worker’s standard `ContainerProxy` export even without outbound handlers. Added the export and exercised the installed SDK through two reconstructions, including persisted empty config: no HTTP, HTTPS or catch-all interception is registered. This helper is a named internal entrypoint, not an API route. Logged and fixed adjacent idea `01M7FF41HK2PP2311HKJ9N9MB1`. Runtime egress, transfer and isolation proof remain pending an explicit staging slot grant; no staging resources or deployment have been created. + +## Source execution proof — 2026-11-15 + +Coordinator and Shepherd accepted process-local publish-path execution counters for the VM source gate. Atomic counters increment immediately before actual Compose build and HostDocker.Save execution, including failures. Authenticated system-info returns a fresh snapshot outside the cached collector, with an immutable random process incarnation and no-store on both agent and API. Shared response fields are optional for old-agent compatibility. Compare the same source node, exact version and incarnation before/after the owned job; any restart, missing fields or positive delta is NOT_MET. This proves no vm-agent publish-path source build/save, not surveillance of unrelated host processes. Pair it with executor=cloudflare, matching builder attempt/upload digest and served release. + +Tests cover normal and host-network builds, save/build failure attempts, concurrent atomic getters, auth/cache and zero build/save delta for the actual VM/Instant context-collection routes. Discrimination checks removed each increment separately: both produced the expected scenario failure, and restored code passes. Fresh Go and security reviews PASS; focused race suites, shared typecheck and affected TypeScript lint PASS. This is a new release input and requires new full-SHA CI and node/builder rollout evidence; older48da receipts are retained as historical evidence only. + +Staging remains ungranted. Planning now budgets two owned cx23 VMs (target reused across both proofs, source after Instant passes), two builders and one Instant; actual catalog quote EUR0.0088/hour per2CPU4GB VM, conservative totalUSD1.238/reserve1.30 under coordinator+ShepherdUSD2 ceiling. Provisional17:55–19:40UTC requires strictFREE/direct grant. Latest auth clarification permits one scoped0600 same-session Playwright cache for bounded stages and ledger-driven recovery; never print/publish it, delete at sign-out. No live login/cache/guards/resources have been created. + +Coordinator review found a future false-zero risk in the first counter implementation: checking the last argument misses a future `build web` or `build --pull`. Replaced inference with a dedicated counted Compose build helper, routing both normal and host-network builds through it. Generic Compose execution refuses build tokens, including embedded command tokens. Tests cover refusal and counted trailing options/service; the refusal scenario failed before the fix, and deleting the new helper's increment makes the trailing-service test fail. Restored full publish race suite and focused server race checks PASS. Fresh Go/security delta reviews PASS. Logged adjacent review finding as SAM idea `01M7FMFARDXSK7NHY83T0RWKJ5`. + +Staging recipe inspection also found the MCP deployment guide still claimed Instant could not publish and builds always ran on a SAM VM. Updated the agent-facing guide to match executor selection and the observable source-sleep boundary (`context_ready` or subsequent builder progress). Existing deployment-guide response test and affected lint PASS; doc review confirmed the contract and identified both stale sentences, now addressed. Logged idea `01M7FPJ6Z5TH60BX2EWE13AQM8`. + +## First live staging trial — 2026-11-15 + +Coordinator grant fddf750e + correction8139c4f8 authorized primary staging with two VMs/two builders/one Instant and USD2 caps, 135 minutes from acquisition. Exact4548 deployed successfully via43769794086; own lease7811054792 lasts22:32:09–00:47:09UTC. VmAgent rollout1656 completed100%; ComposeBuilder direct-createdv1/no old instances. Migration0242 applied. One login and one owned Instant session; zero physical VMs. + +Real publishjob01M7GQDZYZY1CE8TQQA9MPCV2X verified125833246-byte context with hashreceipt. Source prompt ended and source slept23:08:21; CF source inactive23:08:33. **Capability trial FAIL:** source publish.context.collected raced admission: context_ready23:07:22.250→admittedstarting23:07:22.345→collectorcontext_ready23:07:22.872. Builder inactive/no acceptance or release. Reported coordinator immediately; bug idea01M7GQKYJJB2EK5XFTFF4VE0PS. VM proof and image transfer not attempted; no retry authorized. + +Fix treats the workspace collector receipt as diagnostic history for nonshadow Cloudflare builds, preserving job status/current step and shadow completion. Real SQLite route tests reproduce admission before and between read/fence (four RED cases before fix), builder progress, verification bypass and terminal protection. Focused26testsPASS before final added terminal case; independent Cloudflare/security delta reviewsPASS. No Go/binary change. Cleanup still OCCUPIED: source actions canceled, executor default unchanged; wait original20min deadline23:27:22 plus confirmed builder stop before relationship cascades, exact context deletion, signout and immediate/+5min audits. No new staging run or publish. + +Coordinator eventb811f1f4 requested database-level monotonic progress guards and reserved-row recovery, and pre-approved one new exact-head/green-CI trial with the same caps (USD2 additional), after first cleanup/audits/release. Expanded fix guards the history/UPDATE predicates against backward Cloudflare phases/steps, preserving node/shadow protocol and repeated per-service export/upload. Builder readiness now reports starting before validation. Reserved context_ready recovery CAS preserves attempt, ownership, capacity and deadline; refreshes liveness once; runs before accepted-DO short-circuit without guest contact. Acceptance receipt is diagnostic-only. Real heartbeat/null/prototype-key and recovery-negative tests included. Focused77testsPASS, Go builder/publish racePASS, final security/Cloudflare/Go reviewsPASS. Removing the compiled SQL predicate made the controlled late-collector→launch test RED; restoring it made that test PASS. First-trial cleanup remains pending originaldeadline; second trial not started. + +First-trial cleanup completed: original hard deadline failed the job at23:27:24 and cleared its reservation; both actual Cloudflare instances inactive. Normal task/environment/profile/project deletion and signout/sessionNULL/cache removal completed. Immediate23:32 and late23:37 D1 audits show no owned live resources or provisioning leases, zero physical VMs and a retained deleted Instant node with termination proof. Coordinator event93d6c6bc explicitly accepts one retained125,833,246-byte context object for the normal >=48h retention cleanup (token has read but no delete permission); do not claim immediate object absence. Release workflow43776522530 succeeded; authoritative primary lease7811958441 released23:45:49UTC. Second trial remains unstarted. + +Full CI43775012754 found one API fixture regression: createSchemaTables intentionally omits defaults, leaving executor/context_shadow NULL unlike production's node/0 defaults. The real-SQLite legacy callback test reproduced RED; explicitly seeding node/0 fixes the fixture without relaxing the SQL guard. All63 tests across the full18-case callback suite, collector handoff and job hardening pass; independent Cloudflare review PASS. This test-only commit needs fresh full CI; builder binary input remains733310144970e2008f298fc2a3b39f98961d7a67. + +## Second trial and review corrections — 2026-11-16 + +The c577 trial passed remote context (125,833,206 bytes), build/export/upload (147,403,264 bytes) and release creation. The app failed because the fixture called missing `httpd`; the final trial uses Python's HTTP server. The source sleep request exceeded the helper's 15-second timeout, and authoritative sleep completed after the build; source-sleep-before-build and VM-source counter proof remain incomplete. Sleep investigation: idea `01M7GYE30M20QAC7N1K10FK6F0`. A completed builder briefly became running again at its old hard deadline and self-stopped; merge-blocking runtime investigation: `01M7GYR3VCTK0G72HBHJJ000G5`. + +Normal resource cleanup, logout/session NULL/cache deletion and immediate/+5-minute D1 audits passed. Source and builder inactive; target termination gate confirmed provider removal (no independent provider inventory). Coordinator permits the exact context/image objects to remain for normal >=48-hour cleanup. Primary lease release workflow43785339457 succeeded; lease7813101248 released01:18:04.832. No more trial resources remain. Coordinator preapproved one final post-review focused run <=USD2 with corrected fixture, >=60-second sleep timeout, VM counter proof, and builder inactivity through its original hard deadline+2 minutes. + +CodeRabbit returned9 inline and1 outside finding. First correction unit: extraction now restores explicit directory permissions only after successful extraction, deepest-first, and gives implicit parents0755; build-network augmentation interpolates the safe build environment before Compose path normalization. Both controlled tests failed before the fix and pass afterward. RealCompose5.7.1 config-only regression passed without a daemon and preserves runtime secret references in release YAML. Builder/publish race suites pass; independent Go specialist review found no blockers. Remaining review/runtime fixes pending; draft/human exact-SHA hold remains. + +Second correction unit bounds actual callback bytes after authentication, parses once and shares the result across events/artifacts/releases for both scopes. Runtime setting `deployments.publishCallbackMaxBodyBytes` defaults to1MiB (1KiB–16MiB); environment-variable work was replaced by the existing admin registry. Source collector terminal writes now have a final SQL handoff fence; late MCP acceptance failures return the same advanced job instead of failing or stopping it. Cloudflare requests lacking an agent profile fail before job creation; node behavior remains compatible. Controlled removal of body cap and source SQL fence made the new tests RED, then restoration passed. Combined126 route/job/MCP cases passed before the registry move; updated real-setting body tests and legacy route fixtures passed afterward. Security review independently passed78 tests; config review and runtime-tunable ratchet passed. Full final-head CI and final staging remain pending. + +Third correction unit fixes deadline wake/shutdown (idea01M7GYR3VCTK0G72HBHJJ000G5) and awaited diagnostic publication. Persisted `launchBuilder` alarm callbacks now return immediately; acceptance diagnostics run outside the awaited startup/alarm path. Deadline destruction bypasses startup/D1, skips inactive guests and clears obsolete schedules. SDK startup can resume after abort, so local shutdown reconciliation runs before any D1 failure handling and retains deadline retries until startup settles. Bootstrap uses the SDK's underlying raw private port with synchronous signal/running checks, avoiding implicit restarts. Previous stop notifications cannot revoke current startup. Original three regressions and deferred-start case reproduced RED before fixes;21 lifecycle tests, typecheck/lint and independent Cloudflare review pass. Final live verification must keep completed builders inactive through the original hard deadline+2 minutes. + +Fourth correction unit fences stale startup/capacity outcomes using the existing `executorNotBefore` value as a strictly advancing reservation epoch. Failure CAS requires original attempt, reservation ID, epoch and `starting`; losing callbacks neither stop guests nor publish failure. Capacity stop/release share the DO serialization boundary and check epoch before aborting. Startup state, scheduled identities and acceptance markers carry the epoch; no extra capacity ledger or migration is needed. Queue filtering excludes capped projects and invalid/expired contexts before the drain limit; final atomic admission remains authoritative. Five controlled regressions failed before the fix;94 SQL/lifecycle/hardening tests and23 focused DO cases pass. Package build, API typecheck/lint and independent Cloudflare review pass. Deletion-reservation fence remains next, followed by full final-head gates. + +Fifth correction unit preserves the sole D1 capacity ledger across deletion: migration0244 rejects deletion/cascades while a nonshadow Cloudflare reservation is held, even after a terminal verdict. Owner/manual/shared Operations node deletion, project and environment deletion preflight after authorization and before physical effects; the global handler maps wrapped trigger conflicts to safe409. Source teardown can race admission after preflight, but the atomic trigger retains capacity/job state. Workspace-only deletion already retains the job (no FK). Actual shipped SQLite migrations prove direct/node/project/environment/user cascades, both admission/delete orders, terminal release and legacy/shadow behavior. Owner/manual/Ops and project route tests plus safe409 tests pass;89 related tests across8files pass. Independent security review reran22 tests PASS. Two exact SonarS5332 private workerd-port URL findings are narrowly suppressed with transport explanations; no public HTTP downgrade. Bug01M7H1M9V1KHWC5DXDRP3DBVM6 records the deletion finding. Final-head CI/review/staging remain pending. + +Final docs review corrected the old source-deletion/deadline description. The unapplied deletion guard moved from0243 to0244 because open PRs2772 and2691 also propose0243; applied0242 remains unchanged. No schema semantics changed. + +Final CI76f3 exposed four older test fixtures still assuming pre-correction interfaces: full Drizzle mocks hid schema exports, node deletion mocks consumed proof rows for reservation preflights, and collector-handoff auth mocks omitted the new parse-once body contract. Fixtures now retain original Drizzle exports, route reservation table reads separately, and return the parsed callback body.48 cases across6 affected/real-SQLite suites pass; no production code changed. Fresh exact-head CI and a refreshed exact-head staging grant/packet remain required before any final trial; the previous76f3 conditional grant cannot authorize a different head. + +## Final staging proof and VM opt-in qualification — 2026-11-16 + +Full CI43792773359 and final deployment43797294053 (including smoke) passed on83febdf0ac72bec2c2544e6862f542635b14ca38. Actual builder rolloutd6bf52b1 and source rollout1312ee3f completed100%; Worker served that SHA100%, both binaries report e1ed097d8d345f241d1205dd47a4168cbfc1e5f4, and D10244 applied. + +Real Instant job01M7H7SF0DT0K3AR47CEZD49WW accepted context03:53:14 and builder03:53:18. Source was inactive03:54:01 while the remote job remained building03:55:10. The job succeeded03:55:57, release01M7H7YJQDJ854EAWQKEKHSZA4 applied, and unauthenticated GET returned200 with the exact marker. Context125833194 bytes and image147402752 bytes have matching SHA256/size receipts. Independent security/domain reviews passed; approved open egress remains the documented trust model. + +Sleep POST returned500 after the prompt had already ended. The source also entered unexpected recovery. These sleep/recovery/turn paths have zero diff against refreshed main; follow-up idea01M7H8B03VCYXQ9DGYC4BPY1QX records the observations. Exact claim-cleared plus source-inactive evidence and coordinator7a0f804a permit a truthful failed-and-settled status500 receipt; no successful sleep HTTP response was fabricated and no request was retried. A precautionary cancel later returned404 because no RUNNING agent remained; coordinator95e72dbf/f19fa2de permits separate failed-and-settled reconciliation based on STOPPED workspace, idle/null prompt and succeeded sole job. The cancel route exists; there is no missing-route claim. + +VM-source Cloudflare capability remains UNVERIFIED. The second/final physical VM became ready too near the hard first-VM+10min acceptance cutoff04:05:56.883; no VM task or publish job was submitted. Baseline source counters were0/0 only, which does not establish a zero delta. Coordinatorfd5b97c3 directed skipping this proof without another trial, retaining default deployments.buildExecutor=node, filing idea01M7H8GCR5FFDEXA70DNMEF8BW, adding its setting comment, and qualifying docs. Before an admin enables Cloudflare for VMs, that idea requires a real served release and same-process build/save zero-delta proof. The setting was restored to its original unconfigured node default with CAS revision82. This is a documented acceptance deferral, not a passed VM test. + +The final comment/docs-only qualification changes no runtime behavior or binary. Builder no-wake observation through original04:13:14.669 deadline+2min, normal cleanup, immediate/+5min audits, logout and lease release remain in flight. Exact-instance manifest survives job-row deletion; do not infer inactivity from empty job-derived filters. Keep PR2721 draft/needs-human-review and send the final full-SHA gate handoff before stopping. No merge without coordinator approval of that SHA. + + +## Native alarm cleanup correction — 2026-11-16 + +The latest Instant capability succeeded, but the original hard deadline still activated the stopped builder DO and created a new placement. This is a failed no-wake gate, not proof of guest boot or billing. Recorded on idea `01M7GYR3VCTK0G72HBHJJ000G5`. All trial resources were cleaned up; immediate/+5-minute audits and exact source/builder inactivity checks passed, then PRIMARY lease release workflow43804351115 succeeded (authoritative7815554552 RELEASED). Exact context/image objects remain under the approved retention exception. + +The installed Containers SDK0.3.7 owns a native alarm independently of its SQL schedules, rearms during reconstruction, and can rearm a pre-stop schedule snapshot after delivering onStop. Confirmed-stop cleanup now removes both named schedules and the native alarm and persists a quiescent marker. Constructor renewal/scheduling and terminal alarm delivery honor that marker before entering SDK activity paths. Fresh capacity admission clears it; unsettled startup retains its deadline retry and verdict delivery. Natural-stop events and reservation release are fenced to the reservation epoch. + +A new test runs the application subclass through the actual installed SDK with real SQLite schedules. The original implementation produced six failing cases and one passing capacity-retry control. Expanded coverage includes controlled delayed SDK sync and old-stop/D1-read races across readmission. Removing only the production native-alarm deletion reproduced the explicit-stop failure; restoring it passes. Independent Cloudflare/lifecycle and security reviews passed. Live no-wake proof remains pending the approved single <=USD1 Instant-only short-deadline rerun on the new exact SHA after CI and normal lease/rollout gates. VM proof remains explicitly deferred, with the default node executor unchanged. PR remains draft/needs-human-review; no merge without exact-SHA approval. + + +## Focused native-alarm staging verification — 2026-11-16 + +Runtime tested at `018a56f1acb78755a959ea053f18e5dad3338f64`, immutable agent/builder `e1ed097d8d345f241d1205dd47a4168cbfc1e5f4`. Full CI43805600123 attempt2 passed after exactly one retry of an unchanged runtime-secret overlapping-submit test (idea01M7HB8YEFM9YTZWFH31PQ0DX0). Trusted incremental CodeRabbit43805627532 ended rate-limited; wait ended without retrigger. Deployment43807052699 and smoke passed; actual source and builder rollouts completed100% before either fixture. + +The first fixture job01M7HCZC8WS4E7VJ88ST2FTA3Z failed because its generated Python probe was invalid. Verified context and compile-only reproduction establish the fixture defect, tracked01M7HDH4BFZ77B0XKREE33JNTT. No-wake on FAILED terminal is separately PASS: exact builder inactive through original deadline05:27:46.484 plus2min; final unsampled full-count telemetry after309seconds ingestion wait has native-alarm controls, no deadline alarm and no new placement/workload. This job does not establish served release. Its original source was deleted normally, with runtime termination confirmed05:39:27.348. + +Coordinator e526f826/43cd011b explicitly approved ONE corrected replacement Instant in the same lease and USD1 aggregate ceiling. Reviewed source-only packet library01M7HDVC7E4FQJR43DDMV9Y5F8,11872bytes,SHA2568cbcecca99e485fa2e50917b52f4b272b63f2b69d9632017ac0327ec10c14a20. Literal Python probe compilation, working positive control, closed/open8080, timeout/error controls, CAS, single-start and both cleanup paths passed independent review. No further publish is allowed. + +Replacement job01M7HDZ456E5C8BJ91ZW4NDW07 succeeded05:43:39.270. Source exact CF instance was inactive05:42:23 while the job remained building at05:42:34; no manual sleep or cancel. Release01M7HE3RQ41M15X3MC5870XKCC applied; unauthenticated no-redirect GET05:49:32 returned200 and exact marker. Context1049708bytes/SHA2567f5276c169260cf0d917de67664497c8b01b0fb1a0adf054fdb656ff2ada9dde; image22585856bytes/SHA25610481734d6bd0698c365775827c2970a1b00a9a8a13a30300acdac38795334d4. Earlier125MB/147MB transfer remains the >100MiB proof. One targetcx23,2CPU/4GB,reportse1ed; no VM-source publishing trial, explicitly deferred01M7H8GCR5FFDEXA70DNMEF8BW. + +Replacement builder inactive since05:43:42 through original deadline05:45:07.183 plus2min exact GET05:47:15. Final >=5minute ingestion-lag reread and cleanup/immediate/+5minute audits remain in flight. Short deadline override restored to original absence at revision86; VM executor remains unconfigured node. + +Cloudflare build errors currently discard detail preserved by the node executor. Coordinator12a63653 permits deferral to high-priority idea01M7HDK9DV8G2JPBK1KTVNY6JN, first follow-up after merge, with a code TODO and explicit deployments-guide limitation. Coordinator65b71ec2 accepts the final comment/doc/task-only diff without another runtime trial, even though the Go comment changes the release identity. Final handoff must list files and verify Go added/removed lines are comments only; runtime evidence remains pinned018a/e1ed. PR stays draft/needs-human-review, no merge without exact final SHA approval. + + +## Focused verification cleanup complete — 2026-11-16 + +Success-terminal no-wake is PASS: final exact-window telemetry at05:52:15 completed4/4 native alarms, explicitABR1/all sampleInterval1, after308seconds ingestion wait. Initial native-alarm and workload/placement controls are present; no alarm at the original05:45:07.183 deadline and no new placement/workload through deadline+2. Exact builder remained inactive unchanged since05:43:42 through05:58:09. No guest-boot or billing inference. Failed-terminal no-wake remains separately PASS. + +Both trial tasks/workspaces, shared environment/profile/project were deleted with normal200 receipts. Source termination confirmations05:39:27.348 and05:51:00.392; target VM termination confirmed05:51:19.776. Logout05:52:57 returned null session and removed the private cache. Immediate audit05:52:59 and late05:58:08 are clear: project/tasks/workspaces/environment/jobs/leases/volumes0, three DELETED node tombstones with runtime termination proof, no late allocations, restored settings absent, DNS/release records0, exact source/builder instances inactive. Counts of the retained deleted VM row do not imply a live VM. Exact current context/image objects total24,685,137bytes and remain under approved retention; no independent provider-inventory or zero-R2 claim. Aggregate estimateUSD0.914512/reserveUSD0.95 belowUSD1, not a billing assertion. + +Normal PRIMARY release workflow43813679472 succeeded. Authoritative environment-keyed lease record7816727391 is RELEASED at05:59:18.866, same task/branch; slot reported FREE to coordinator. No further staging actions. Independent final qualification review passed; diff from runtime-tested018a contains only runner.go two TODO comments, deployments-guide limitation and this task evidence. Executable Go diff check reports zero non-comment changed lines. Runtime is tested at018a/e1ed; final comment changes release identity as explicitly accepted by coordinator65b71ec2 without another runtime trial. Final-head CI and exact-SHA handoff/STOP remain mandatory; no merge authorization is inferred. + + +## Coordinator final correction — bounded reservation liveness (2026-11-16) + +Coordinator event f93c3264-f764-4027-a446-50c5737afc03 requested a main merge and deadline-plus-grace escape before approval, explicitly waiving another staging trial. Main merge b741106cd77d387b54696d0d60ad49d799e9772b retained both adjacent handler imports; applied0242 and guard0244 remain unchanged, no new migration or duplicate prefix, builder DOv23 follows mainv22. + +New `deployments.builderReservationGraceMs` defaults to300000 via a named constant. Cron checks immutable executor deadlines before any DO RPC; after grace an exact attempt/epoch/instance/deadline-fenced UPDATE revokes ownership and atomically terminalizes unfinished jobs as unknown. Existing terminal verdicts remain. Structured error and dedicated alert-level job event report physicalStopConfirmed=false; failed alert persistence is logged and cannot restore ownership or block later candidates. This consciously permits temporary accounting error while Cloudflare may still hold physical capacity, instead of permanent deletion/admission failure. Actual shipped SQLite/FK tests prove deletion blocked inside grace, permitted after expiry, stale reservations cannot release replacements, late callbacks cannot mutate, and per-item mutation/journal failures do not suppress later work. + +Deletion audit: owner node DELETE preflights reservations before provider destruction and again before final D1 deletion; the trigger atomically fences racing cascades. A raced admission can retain a D1 tombstone after provider destruction; strict termination proof permits safe retry. Teardown cron and warm-pool handoff update/tombstone node records, so do not fire this DELETE trigger. Per-node teardown already catches errors, but fallible diagnosis could escape that catch; fixed its guard with a discriminating regression (guard removal skips the next node). Bug idea01M7HHXGHRBG8T97K1M357ESMN. User self-delete is disabled (BetterAuth deleteUser not enabled); direct operator user deletion is atomically blocked by held reservations until confirmed or forced release. No new account-delete route. + +Independent security/correctness review and config/docs/constitution review PASS. Existing staging proof/cleanup stands; new correction requires full new-head CI and exactSHA coordinator handoff, then STOP. Coordinator will approve and merge; PR remains DRAFT with needs-human-review. + +Local correction validation: real-FK deletion suite23/23; queue suite11/11; node-cleanup14/14 (48 total, last extra isolation case run in deletion suite). API typecheck passes after rebuilding stale dependency dist from main. App-deployment build/lint, changed API lint, docs build291pages, source-contract tests, runtime-tunable ratchet, migration ordering and DO migration safety all PASS. No Go executable changes in this unit.