Skip to content
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
ecaf069
test(cloud): cover the reads that find a Cloud machine gone
teamleaderleo Sep 28, 2026
fa6b69c
fix(cloud): finish the destroy work where a machine is first found gone
teamleaderleo Sep 28, 2026
c7da06f
fix(cloud): derive the observed status inside the shared destroy path
teamleaderleo Sep 28, 2026
9b2facb
vm: say what a paused 404 row means for credentials
teamleaderleo Sep 28, 2026
6a32750
test(cloud): reproduce lost destroy ledger retry
teamleaderleo Sep 28, 2026
1e8f7b7
fix(cloud): retire missing provider compute durably
teamleaderleo Sep 28, 2026
8023b39
fix(cloud): durably drain observed destroy cleanup
teamleaderleo Sep 28, 2026
dbddeef
fix(cloud): keep destroy cleanup queue fair and indexed
teamleaderleo Sep 28, 2026
561cbb0
fix(vm): make observed cleanup retries index-safe
teamleaderleo Sep 28, 2026
e974728
test(cloud): reproduce account deletion cleanup loss
teamleaderleo Sep 28, 2026
b274a2f
fix(cloud): retain pending destroy cleanup on account deletion
teamleaderleo Sep 28, 2026
a6f3b0b
fix(cloud): transfer account cleanup to durable outbox
teamleaderleo Sep 28, 2026
9476171
fix(cloud): reject malformed cleanup outbox rows
teamleaderleo Sep 28, 2026
c88cab9
fix(cloud): validate cleanup outbox shape
teamleaderleo Sep 28, 2026
7d38261
Merge commit '5663c1354b7af3d13aa73f11ccd2486893de2c20' into repair/p…
teamleaderleo Sep 28, 2026
38aab80
Persist explicit destroy cleanup for retry
teamleaderleo Sep 28, 2026
97ea8f2
Merge remote-tracking branch 'mf/main' into repair/pr15359-lifecycle
teamleaderleo Sep 28, 2026
14ecc77
fix cloud observed cleanup retries and concurrent migration
teamleaderleo Sep 30, 2026
e6d35b1
fix migration retry for invalid concurrent indexes
teamleaderleo Sep 30, 2026
563b960
Merge origin/main into fix/cloud-cleanup-outbox-followup
teamleaderleo Sep 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions web/app/api/account/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
cloudVmLeases,
cloudVmNotificationDeliveries,
cloudVmNotificationEvents,
cloudVmObservedDestroyCleanups,
cloudVmSessions,
cloudVmUsageEvents,
cloudVms,
Expand Down Expand Up @@ -75,6 +76,7 @@ import {
createLegacySubrouterRetirementClient,
legacySubrouterRetirementConfig,
} from "../../../services/subrouter/legacyRetirementClient";
import { OBSERVED_DESTROY_CLEANUP_METADATA_KEY } from "../../../services/vms/repository";
import {
destroyVm,
listUserVms,
Expand Down Expand Up @@ -1459,7 +1461,9 @@ async function deleteCmuxOwnedAccountRows(userId: string, accountTeamIds: readon
.select({
id: cloudVms.id,
billingTeamId: cloudVms.billingTeamId,
provider: cloudVms.provider,
providerVmId: cloudVms.providerVmId,
providerMetadata: cloudVms.providerMetadata,
status: cloudVms.status,
})
.from(cloudVms)
Expand All @@ -1484,6 +1488,24 @@ async function deleteCmuxOwnedAccountRows(userId: string, accountTeamIds: readon
`Personal cloud VM provider teardown or creation is still pending for ${unsafePersonalVmRows.length} row${unsafePersonalVmRows.length === 1 ? "" : "s"}`,
);
}
const pendingExternalCleanupRows = personalVmRows.flatMap((vm) => {
if (vm.status !== "destroyed") return [];
const cleanup = observedDestroyCleanupFromMetadata(vm.providerMetadata);
return cleanup ? [{ vmId: vm.id, provider: vm.provider, cleanup }] : [];
});
if (pendingExternalCleanupRows.length > 0) {
await tx
.insert(cloudVmObservedDestroyCleanups)
.values(pendingExternalCleanupRows)
.onConflictDoUpdate({
target: cloudVmObservedDestroyCleanups.vmId,
set: {
provider: sql`excluded.provider`,
cleanup: sql`${cloudVmObservedDestroyCleanups.cleanup} || excluded.cleanup`,
updatedAt: now,
},
});
}
const personalVmIds = personalVmRows.map((vm) => vm.id);
const phonePushLeases = await tx
.select({ deliveryLeaseUntil: deviceTokens.deliveryLeaseUntil })
Expand Down Expand Up @@ -1633,6 +1655,26 @@ async function deleteCmuxOwnedAccountRows(userId: string, accountTeamIds: readon
});
}

function observedDestroyCleanupFromMetadata(
providerMetadata: unknown,
): { readonly modelPlane?: true; readonly homeVolume?: string } | null {
if (!providerMetadata || typeof providerMetadata !== "object" || Array.isArray(providerMetadata)) {
return null;
}
const cleanup = (providerMetadata as Record<string, unknown>)[OBSERVED_DESTROY_CLEANUP_METADATA_KEY];
if (!cleanup || typeof cleanup !== "object" || Array.isArray(cleanup)) return null;
const marker = cleanup as Record<string, unknown>;
const modelPlane = marker.modelPlane === true ? true : undefined;
const homeVolume = typeof marker.homeVolume === "string" && marker.homeVolume.trim().length > 0
? marker.homeVolume.trim()
: undefined;
if (!modelPlane && !homeVolume) return null;
return {
...(modelPlane ? { modelPlane } : {}),
...(homeVolume ? { homeVolume } : {}),
};
}

function assertNoActivePhonePushDeliveryLease(
rows: readonly { readonly deliveryLeaseUntil: Date | null }[],
now: Date,
Expand Down
3 changes: 3 additions & 0 deletions web/app/api/vm/[id]/attach-endpoint/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
import { setSpanAttributes } from "../../../../../services/telemetry";
import { runVmRoute } from "../../../../../services/vms/routeWorkflow";
import { openAttachEndpoint, openVmCmuxRemote } from "../../../../../services/vms/workflows";
import { vmModelPlaneRevoker } from "../../../../../services/vms/modelPlaneGateway";
import {
capabilityList,
optionalClientIdentifier,
Expand Down Expand Up @@ -72,6 +73,7 @@ export async function POST(
deviceFingerprint,
clientCapabilities,
callerPlanId: account.entitlements.planId,
modelPlane: vmModelPlaneRevoker(),
}), { request });
if (!run.ok) return run.response;
return jsonResponse(run.value);
Expand All @@ -93,6 +95,7 @@ export async function POST(
providerVmId: id,
sessionTitle,
options: { requireDaemon, sessionId, attachmentId },
modelPlane: vmModelPlaneRevoker(),
}), { request });
if (!run.ok) return run.response;
const endpoint = run.value;
Expand Down
2 changes: 2 additions & 0 deletions web/app/api/vm/[id]/exec/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
import { setSpanAttributes } from "../../../../../services/telemetry";
import { runVmRoute } from "../../../../../services/vms/routeWorkflow";
import { execVm } from "../../../../../services/vms/workflows";
import { vmModelPlaneRevoker } from "../../../../../services/vms/modelPlaneGateway";


// Exec accepts client timeouts up to 15 minutes (MAX_EXEC_TIMEOUT_MS below).
Expand Down Expand Up @@ -94,6 +95,7 @@ export async function POST(
providerVmId: id,
command,
timeoutMs,
modelPlane: vmModelPlaneRevoker(),
}), { request });
if (!run.ok) return run.response;
const result = run.value;
Expand Down
2 changes: 2 additions & 0 deletions web/app/api/vm/[id]/open-port/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
} from "../../../../../services/vms/routeHelpers";
import { setSpanAttributes } from "../../../../../services/telemetry";
import { runVmRoute } from "../../../../../services/vms/routeWorkflow";
import { vmModelPlaneRevoker } from "../../../../../services/vms/modelPlaneGateway";
import { openVmPort } from "../../../../../services/vms/workflows";
import { desktopWrapperUrl } from "../../../../../services/vms/desktopWrapper";

Expand Down Expand Up @@ -60,6 +61,7 @@ export async function POST(
billingTeamId: account.entitlements.billingTeamId,
maxActiveVms: account.entitlements.maxActiveVms,
callerPlanId: account.entitlements.planId,
modelPlane: vmModelPlaneRevoker(),
teamIds: user.teamIds,
providerVmId: id,
port,
Expand Down
2 changes: 2 additions & 0 deletions web/app/api/vm/[id]/resize/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { runVmRoute } from "../../../../../services/vms/routeWorkflow";
import { resizeVm } from "../../../../../services/vms/workflows";
import { VM_DISK_MB_MAX, VM_DISK_MB_STEP } from "../../../../../services/vms/machineSpec";
import { maxDiskMbForPlan, maxMemoryMbForPlan, maxVcpusForPlan } from "../../../../../services/vms/entitlements";
import { vmModelPlaneRevoker } from "../../../../../services/vms/modelPlaneGateway";

/** Grow a Cloud VM's resources. The workflow owns plan and grow-only checks. */
export async function POST(
Expand Down Expand Up @@ -53,6 +54,7 @@ export async function POST(
cpu: cpu as number | undefined,
memoryMb: memoryMb as number | undefined,
maxActiveVms: account.entitlements.maxActiveVms,
modelPlane: vmModelPlaneRevoker(),
}), { request });
if (!run.ok) return run.response;
const stats = run.value;
Expand Down
2 changes: 2 additions & 0 deletions web/app/api/vm/[id]/resume/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
import { setSpanAttributes } from "../../../../../services/telemetry";
import { runVmRoute } from "../../../../../services/vms/routeWorkflow";
import { resumeVm } from "../../../../../services/vms/workflows";
import { vmModelPlaneRevoker } from "../../../../../services/vms/modelPlaneGateway";

// Wake a parked machine (`cmux vm resume <id>`) through the same suspended-resume
// path every open and exec uses, so plan limits and the free window apply. A
Expand Down Expand Up @@ -36,6 +37,7 @@ export async function POST(
providerVmId: id,
maxActiveVms: account.entitlements.maxActiveVms,
callerPlanId: account.entitlements.planId,
modelPlane: vmModelPlaneRevoker(),
}), { request });
if (!run.ok) return run.response;
return jsonResponse({ id: run.value.id, status: run.value.status });
Expand Down
2 changes: 2 additions & 0 deletions web/app/api/vm/[id]/scp-endpoint/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { setSpanAttributes } from "../../../../../services/telemetry";
import { runVmRoute } from "../../../../../services/vms/routeWorkflow";
import { prepareScpEndpoint } from "../../../../../services/vms/workflows";
import { parseSshPublicKey } from "../../../../../services/vms/drivers/scp";
import { vmModelPlaneRevoker } from "../../../../../services/vms/modelPlaneGateway";

export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }): Promise<Response> {
return withAuthedVmApiRoute(request, "/api/vm/[id]/scp-endpoint", { "cmux.vm.operation": "prepare_scp" }, "/api/vm/[id]/scp-endpoint failed", async ({ user, span }) => {
Expand All @@ -22,6 +23,7 @@ export async function POST(request: Request, { params }: { params: Promise<{ id:
userId: user.id, billingTeamId: account.entitlements.billingTeamId,
callerPlanId: account.entitlements.planId, maxActiveVms: account.entitlements.maxActiveVms,
teamIds: user.teamIds, providerVmId: id, publicKey,
modelPlane: vmModelPlaneRevoker(),
}), { request });
if (!run.ok) return run.response;
return jsonResponse(run.value);
Expand Down
2 changes: 2 additions & 0 deletions web/app/api/vm/[id]/sessions/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { setSpanAttributes } from "../../../../../services/telemetry";
import { runVmRoute } from "../../../../../services/vms/routeWorkflow";
import { listVmSessions, openVmSession } from "../../../../../services/vms/workflows";
import type { CloudVmSessionRow } from "../../../../../services/vms/repository";
import { vmModelPlaneRevoker } from "../../../../../services/vms/modelPlaneGateway";
import {
optionalClientIdentifier,
optionalString,
Expand Down Expand Up @@ -78,6 +79,7 @@ export async function POST(
sessionId,
attachmentId,
title,
modelPlane: vmModelPlaneRevoker(),
}), { request });
if (!run.ok) return run.response;
const result = run.value;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
CREATE INDEX "cloud_vms_observed_destroy_cleanup_idx"
ON "cloud_vms" ("updated_at", "id")
WHERE "status" = 'destroyed'
AND "provider_metadata" ? 'cmuxObservedDestroyCleanup'
AND jsonb_typeof("provider_metadata"->'cmuxObservedDestroyCleanup') = 'object'
AND (
"provider_metadata"->'cmuxObservedDestroyCleanup' @> '{"modelPlane":true}'::jsonb
OR (
jsonb_typeof("provider_metadata"->'cmuxObservedDestroyCleanup'->'homeVolume') = 'string'
AND length(btrim("provider_metadata"->'cmuxObservedDestroyCleanup'->>'homeVolume')) > 0
)
);
Comment thread
teamleaderleo marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
CREATE TABLE "cloud_vm_observed_destroy_cleanups" (
"vm_id" uuid PRIMARY KEY NOT NULL,
"provider" "vm_provider" NOT NULL,
"cleanup" jsonb NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT "cloud_vm_observed_destroy_cleanups_pending_step" CHECK (
coalesce(
jsonb_typeof("cleanup") = 'object'
AND ("cleanup" - 'modelPlane' - 'homeVolume') = '{}'::jsonb
AND (
NOT ("cleanup" ? 'modelPlane')
OR "cleanup"->'modelPlane' = 'true'::jsonb
)
AND (
NOT ("cleanup" ? 'homeVolume')
OR (
jsonb_typeof("cleanup"->'homeVolume') = 'string'
AND length(btrim("cleanup"->>'homeVolume')) > 0
)
)
AND ("cleanup" ? 'modelPlane' OR "cleanup" ? 'homeVolume'),
false
)
)
);

CREATE INDEX "cloud_vm_observed_destroy_cleanups_updated_idx"
ON "cloud_vm_observed_destroy_cleanups" ("updated_at", "vm_id")
WHERE coalesce(
jsonb_typeof("cleanup") = 'object'
AND ("cleanup" - 'modelPlane' - 'homeVolume') = '{}'::jsonb
AND (
NOT ("cleanup" ? 'modelPlane')
OR "cleanup"->'modelPlane' = 'true'::jsonb
)
AND (
NOT ("cleanup" ? 'homeVolume')
OR (
jsonb_typeof("cleanup"->'homeVolume') = 'string'
AND length(btrim("cleanup"->>'homeVolume')) > 0
)
)
AND ("cleanup" ? 'modelPlane' OR "cleanup" ? 'homeVolume'),
false
);
59 changes: 58 additions & 1 deletion web/db/schema.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { sql } from "drizzle-orm";
import { sql, type SQL, type SQLWrapper } from "drizzle-orm";
import {
bigint,
boolean,
Expand All @@ -18,6 +18,27 @@ import {

export const vmProvider = pgEnum("vm_provider", ["freestyle"]);

/** A closed, actionable observed-destroy cleanup object. */
export function observedDestroyCleanupValidityPredicate(cleanup: SQLWrapper): SQL {
return sql`coalesce(
jsonb_typeof(${cleanup}) = 'object'
and (${cleanup} - 'modelPlane' - 'homeVolume') = '{}'::jsonb
and (
not (${cleanup} ? 'modelPlane')
or ${cleanup}->'modelPlane' = 'true'::jsonb
)
and (
not (${cleanup} ? 'homeVolume')
or (
jsonb_typeof(${cleanup}->'homeVolume') = 'string'
and length(btrim(${cleanup}->>'homeVolume')) > 0
)
)
and (${cleanup} ? 'modelPlane' or ${cleanup} ? 'homeVolume'),
false
)`;
}

export const vmStatus = pgEnum("vm_status", [
"provisioning",
"running",
Expand Down Expand Up @@ -103,6 +124,18 @@ export const cloudVms = pgTable(
index("cloud_vms_owner_team_status_idx").on(table.ownerTeamId, table.status),
index("cloud_vms_user_status_idx").on(table.userId, table.status),
index("cloud_vms_billing_team_status_idx").on(table.billingTeamId, table.status),
index("cloud_vms_observed_destroy_cleanup_idx")
.on(table.updatedAt, table.id)
.where(sql`${table.status} = 'destroyed'
and ${table.providerMetadata} ? 'cmuxObservedDestroyCleanup'
and jsonb_typeof(${table.providerMetadata}->'cmuxObservedDestroyCleanup') = 'object'
and (
${table.providerMetadata}->'cmuxObservedDestroyCleanup' @> '{"modelPlane":true}'::jsonb
or (
jsonb_typeof(${table.providerMetadata}->'cmuxObservedDestroyCleanup'->'homeVolume') = 'string'
and length(btrim(${table.providerMetadata}->'cmuxObservedDestroyCleanup'->>'homeVolume')) > 0
)
)`),
uniqueIndex("cloud_vms_billing_team_idempotency_key_unique")
.on(table.billingTeamId, table.idempotencyKey)
.where(sql`${table.billingTeamId} is not null and ${table.idempotencyKey} is not null`),
Expand All @@ -116,6 +149,30 @@ export const cloudVms = pgTable(
],
);

/**
* External teardown that must outlive its account-owned VM row. Account
* deletion moves pending terminal cleanup here in the same transaction that
* removes the VM, so no user/team foreign key may be added to this outbox.
*/
export const cloudVmObservedDestroyCleanups = pgTable(
"cloud_vm_observed_destroy_cleanups",
{
vmId: uuid("vm_id").primaryKey(),
provider: vmProvider("provider").notNull(),
cleanup: jsonb("cleanup").$type<{ modelPlane?: true; homeVolume?: string }>().notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("cloud_vm_observed_destroy_cleanups_updated_idx")
.on(table.updatedAt, table.vmId)
.where(observedDestroyCleanupValidityPredicate(table.cleanup)),
check(
"cloud_vm_observed_destroy_cleanups_pending_step",
observedDestroyCleanupValidityPredicate(table.cleanup),
),
],
);

/** Durable Hive identity. VM status and provider addresses remain owned by cloud_vms. */
export const cloudRuntimes = pgTable("cloud_runtimes", {
id: uuid("id").defaultRandom().primaryKey(),
Expand Down
9 changes: 9 additions & 0 deletions web/services/vms/productAnalytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,15 @@ export function withVmProductAnalytics(
};
return {
...repository,
markProviderObservedStatus: (input) =>
repository.markProviderObservedStatus(input).pipe(
Effect.tap((updated) => {
const usageEvent = input.usageEvent;
return updated && usageEvent
? Effect.sync(() => safeCapture(usageEvent))
: Effect.void;
}),
),
recordUsageEvent: (input) =>
repository.recordUsageEvent(input).pipe(
Effect.tap(() => Effect.sync(() => safeCapture(input))),
Expand Down
8 changes: 6 additions & 2 deletions web/services/vms/providerGateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,8 +209,12 @@ export const VmProviderGatewayLive = Layer.succeed(VmProviderGateway, {
deleteHomeVolume: (provider, volumeName) =>
providerEffect(provider, "deleteHomeVolume", async () => {
const impl = getProvider(provider);
// Providers without persistent volumes have nothing to delete.
if (!impl.deleteHomeVolume) return;
// A caller only reaches this seam with an explicitly owned volume. Do
// not report success when the current driver cannot delete legacy
// storage: durable cleanup must remain pending for retry/operator work.
if (!impl.deleteHomeVolume) {
throw new VmOperationUnsupportedError({ provider, operation: "deleteHomeVolume" });
}
await impl.deleteHomeVolume(volumeName);
}),
listVolumes: (provider, options) =>
Expand Down
Loading
Loading