Skip to content

Commit 173ab20

Browse files
ericallamTrigger.dev RepoOps
authored andcommitted
feat(webapp,run-engine): compute-only deploys keep an org's runs on microVM compute
Mono-RevId: 489ffda4783816a82f5d275cc52818163b38b076
1 parent a5b0654 commit 173ab20

24 files changed

Lines changed: 813 additions & 47 deletions

‎apps/supervisor/src/index.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ import {
2727
settleRestoreFailure,
2828
type RunnerStartFailure,
2929
} from "./workloadManager/runCrd.js";
30-
import { workerLaneFor, type WorkloadManagerBackend } from "./workerLane.js";
30+
import { mayWarmStart, workerLaneFor, type WorkloadManagerBackend } from "./workerLane.js";
3131
import { RestoreWatcher, type RestoreFailure } from "./services/restoreWatcher.js";
3232
import {
3333
ColdStartHeartbeats,
@@ -1179,8 +1179,7 @@ class ManagedSupervisor {
11791179
dequeuedMessage: DequeuedMessage,
11801180
traceparent: string | undefined
11811181
): Promise<boolean> {
1182-
// A sandbox never reuses a process or VM another run has used.
1183-
if (!this.warmStartUrl || dequeuedMessage.run.annotations?.executionMode === "SANDBOX") {
1182+
if (!this.warmStartUrl || !mayWarmStart(dequeuedMessage.run.annotations)) {
11841183
return false;
11851184
}
11861185

‎apps/supervisor/src/workerLane.test.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, it } from "vitest";
2-
import { workerLaneFor } from "./workerLane.js";
2+
import { mayWarmStart, workerLaneFor } from "./workerLane.js";
33

44
describe("workerLaneFor", () => {
55
it("follows the configured runtime on the run-crd backend", () => {
@@ -12,3 +12,16 @@ describe("workerLaneFor", () => {
1212
expect(workerLaneFor("docker", "microvm")).toBe("container");
1313
});
1414
});
15+
16+
describe("mayWarmStart", () => {
17+
it("lets an ordinary run warm start", () => {
18+
expect(mayWarmStart(undefined)).toBe(true);
19+
expect(mayWarmStart({ triggerSource: "api" })).toBe(true);
20+
});
21+
22+
// Catches: a compute-only run handed by firestarter to a long-polling container runner of the same version
23+
it("never warm starts a sandbox or a compute-only run", () => {
24+
expect(mayWarmStart({ executionMode: "SANDBOX" })).toBe(false);
25+
expect(mayWarmStart({ computeOnly: true })).toBe(false);
26+
});
27+
});

‎apps/supervisor/src/workerLane.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { computeOnlyReason } from "@trigger.dev/core/v3";
12
import type { RunnerRuntime } from "./workloadManager/runCrd.js";
23

34
export type WorkloadManagerBackend = "kubernetes" | "run-crd" | "docker";
@@ -15,3 +16,12 @@ export function workerLaneFor(
1516
return "container";
1617
}
1718
}
19+
20+
/**
21+
* Whether a dequeued run may be handed to a warm runner. A sandbox never reuses a process or VM
22+
* another run has used, and a compute-only run always cold starts: the warm-start key has no
23+
* runtime, so a container runner of the same version and machine could otherwise take it.
24+
*/
25+
export function mayWarmStart(annotations: unknown): boolean {
26+
return computeOnlyReason(annotations) === undefined;
27+
}

‎apps/webapp/app/runEngine/services/triggerTask.server.ts‎

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ import {
5454
} from "~/v3/workerRegions.server";
5555
import { globalFlagsRegistry } from "~/v3/globalFlagsRegistry.server";
5656
import { sandboxTasksEnabled } from "~/v3/sandboxTasksFlag.server";
57+
import { computeOnlyEnabled } from "~/v3/computeOnlyFlag.server";
5758
import {
5859
publishClaim as publishMollifierClaim,
5960
releaseClaim as releaseMollifierClaim,
@@ -544,6 +545,11 @@ export class RunEngineTriggerTaskService {
544545
environmentId: environment.id,
545546
environmentType: environment.type,
546547
});
548+
// Deployed runs of a compute-only org run only on microVMs, like sandboxes, whatever
549+
// the env or org worker queue overrides say.
550+
const computeOnly =
551+
environment.type !== "DEVELOPMENT" && computeOnlyEnabled(orgFeatureFlags);
552+
const pinnedToCompute = !!executionPolicy || computeOnly;
547553
const migrated = resolveComputeMigration({
548554
baseWorkerQueue,
549555
baseEnableFastPath: enableFastPath,
@@ -555,7 +561,7 @@ export class RunEngineTriggerTaskService {
555561
flags: globalFlagsRegistry.current(),
556562
envType: environment.type,
557563
// Sandboxes only run on microVMs, whatever the org's migration state.
558-
environmentCompat: executionPolicy ? "compute" : environmentOverride.compat,
564+
environmentCompat: pinnedToCompute ? "compute" : environmentOverride.compat,
559565
templateKey,
560566
});
561567

@@ -570,15 +576,27 @@ export class RunEngineTriggerTaskService {
570576
workerGroups.find((group) => group.masterQueue === baseWorkerQueue)?.workloadType ===
571577
"MICROVM";
572578
if (
573-
executionPolicy &&
579+
pinnedToCompute &&
574580
environment.type !== "DEVELOPMENT" &&
575581
!migrated.compute &&
576582
!(onMicrovmGroup && templateKey)
577583
) {
584+
if (executionPolicy) {
585+
throw new ServiceValidationError(
586+
`Task "${taskId}" is a sandbox and needs microVM compute, which is not available ${
587+
templateKey ? "in this region" : "for this deployment (no compute template)"
588+
}.`
589+
);
590+
}
591+
// The reason stays in the log: the caller only learns what to do next.
592+
logger.warn("Trigger refused: compute-only run has nowhere to start", {
593+
organizationId: environment.organizationId,
594+
environmentId: environment.id,
595+
taskId,
596+
reason: templateKey ? "no_compute_in_region" : "no_template",
597+
});
578598
throw new ServiceValidationError(
579-
`Task "${taskId}" is a sandbox and needs microVM compute, which is not available ${
580-
templateKey ? "in this region" : "for this deployment (no compute template)"
581-
}.`
599+
"This task can't run on its current version. Deploy again and trigger the new version, or contact support if it keeps failing."
582600
);
583601
}
584602

@@ -604,6 +622,7 @@ export class RunEngineTriggerTaskService {
604622
...(executionPolicy
605623
? { executionMode: "SANDBOX" as const, executionPolicy, sessionId: options.sessionId }
606624
: {}),
625+
...(computeOnly && { computeOnly: true as const }),
607626
};
608627

609628
const workerQueue =
@@ -615,7 +634,7 @@ export class RunEngineTriggerTaskService {
615634
orgFeatureFlags,
616635
v2Enabled: env.TRIGGER_WORKER_QUEUE_V2_ENABLED === "1",
617636
splitEnabled: env.TRIGGER_WORKER_QUEUE_SCHEDULED_SPLIT_ENABLED === "1",
618-
environmentOverride: executionPolicy
637+
environmentOverride: pinnedToCompute
619638
? { ...environmentOverride, compat: "compute" }
620639
: environmentOverride,
621640
workerGroups,
@@ -1003,6 +1022,7 @@ export class RunEngineTriggerTaskService {
10031022
rootScheduleId?: string | undefined;
10041023
externalDeploymentId?: string | undefined;
10051024
executionMode?: "SANDBOX";
1025+
computeOnly?: true;
10061026
secretProxyRequired?: true;
10071027
executionPolicy?: RunExecutionPolicy;
10081028
sessionId?: string;
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import type { DeploymentAccessDecision } from "@trigger.dev/plugins";
2+
import type { PrismaClientOrTransaction } from "~/db.server";
3+
import { logger } from "~/services/logger.server";
4+
import { FEATURE_FLAG, isPlainFlagObject } from "~/v3/featureFlags";
5+
6+
/** Whether the org's deployed runs must execute only on compute lanes. Runs on every trigger. */
7+
export function computeOnlyEnabled(orgFeatureFlags: unknown): boolean {
8+
return isPlainFlagObject(orgFeatureFlags) && orgFeatureFlags[FEATURE_FLAG.computeOnly] === true;
9+
}
10+
11+
/**
12+
* The org's `featureFlags`, read by primary key from `client`. Finalize passes the primary: the
13+
* initialize call just before it may have set `computeOnly`, and a replica can still miss that.
14+
*/
15+
export async function loadOrgFeatureFlags(
16+
client: PrismaClientOrTransaction,
17+
organizationId: string
18+
): Promise<unknown> {
19+
const organization = await client.organization.findFirst({
20+
where: { id: organizationId },
21+
select: { featureFlags: true },
22+
});
23+
return organization?.featureFlags ?? null;
24+
}
25+
26+
/**
27+
* Mirrors an allowed deploy's placement into the org's `computeOnly` flag, so the trigger path can
28+
* read it from flags it already loads. Sets it for a compute-only placement and removes it
29+
* otherwise. `currentFlags` is the org's `featureFlags` as the caller loaded them (undefined when
30+
* it didn't), usually from a replica: when a plain placement finds no flag there, no statement is
31+
* sent, so a plain deploy costs nothing. A compute-only placement always sends its statement,
32+
* because a stale read that still shows the flag must never leave the org without it. The
33+
* conditional `WHERE` keeps that statement from rewriting a row that already has the flag. A
34+
* statement that changed the row logs `computeOnly set` or `computeOnly cleared` with `context`.
35+
*/
36+
export async function syncComputeOnlyFlag(
37+
client: PrismaClientOrTransaction,
38+
organizationId: string,
39+
decision: Extract<DeploymentAccessDecision, { allowed: true }>,
40+
currentFlags?: unknown,
41+
context: Record<string, string | undefined> = {}
42+
): Promise<void> {
43+
const wanted = decision.placement === "microvm";
44+
if (!wanted && currentFlags !== undefined && !computeOnlyEnabled(currentFlags)) return;
45+
const changed = wanted
46+
? await client.$executeRaw`
47+
UPDATE "Organization"
48+
SET "featureFlags" = jsonb_set(COALESCE("featureFlags", '{}'::jsonb), '{computeOnly}', 'true'::jsonb)
49+
WHERE id = ${organizationId}
50+
AND ("featureFlags" IS NULL OR "featureFlags"->'computeOnly' IS DISTINCT FROM 'true'::jsonb)`
51+
: await client.$executeRaw`
52+
UPDATE "Organization"
53+
SET "featureFlags" = "featureFlags" - 'computeOnly'
54+
WHERE id = ${organizationId} AND "featureFlags" ? 'computeOnly'`;
55+
if (changed > 0) {
56+
logger.info(wanted ? "computeOnly set" : "computeOnly cleared", { organizationId, ...context });
57+
}
58+
}

‎apps/webapp/app/v3/deploymentAccess.server.ts‎

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,15 @@ import { logger } from "~/services/logger.server";
1414
import { isCloud } from "~/services/platform.v3.server";
1515
import { createRedisRateLimitClient, RateLimiter } from "~/services/rateLimiterCore.server";
1616
import { singleton } from "~/utils/singleton";
17+
import { syncComputeOnlyFlag } from "./computeOnlyFlag.server";
18+
import { globalFlagsRegistry } from "./globalFlagsRegistry.server";
1719
import { resolvePlanState } from "./freeSchedulePolicy.server";
1820
import { ServiceValidationError } from "./services/common.server";
1921

2022
const MODULE_NAME = "@triggerdotdev/plugins/deployment-access";
2123

2224
const DEFAULT_DENIED_MESSAGE = "Deployments are not available for this organization.";
25+
const FLAG_SYNC_FAILED_MESSAGE = "We couldn't prepare this deploy. Try deploying again.";
2326

2427
/** Null when no deployment access plugin is loaded: every check allows. */
2528
export function getDeploymentAccessController(): Promise<DeploymentAccessController | null> {
@@ -76,15 +79,59 @@ async function resolveController({
7679
/**
7780
* Asks the plugin whether a deploy may go ahead. Without a plugin everything is allowed. A plugin
7881
* that throws denies: a check that can't run must not open the door.
82+
*
83+
* The global `computeOnlyDeploys` flag goes with every check, read from the global flag snapshot
84+
* (reloaded every GLOBAL_FLAGS_RELOAD_INTERVAL_MS). A cold snapshot reads as off.
85+
*
86+
* Placement is decided once, at initialize: an allowed decision there is mirrored into the org's
87+
* `computeOnly` flag. Pass the org's loaded `featureFlags` as `organizationFeatureFlags` so the
88+
* write only happens when the flag changes. A flag that can't be written denies too, so a
89+
* compute-only org never deploys without it. A denied decision leaves the flag alone: an org
90+
* already on compute keeps running there. Preflight and register_worker never touch the flag.
7991
*/
8092
export async function checkDeployAccess(
81-
check: DeploymentAccessCheck,
82-
source: ControllerSource = {}
93+
request: Omit<DeploymentAccessCheck, "computeOnlyDeploys">,
94+
{
95+
client = prisma,
96+
computeOnlyDeploys = globalFlagsRegistry.current()?.computeOnlyDeploys ?? false,
97+
organizationFeatureFlags,
98+
...source
99+
}: ControllerSource & {
100+
client?: PrismaClientOrTransaction;
101+
computeOnlyDeploys?: boolean;
102+
organizationFeatureFlags?: unknown;
103+
} = {}
83104
): Promise<DeploymentAccessDecision> {
105+
const check: DeploymentAccessCheck = { ...request, computeOnlyDeploys };
84106
try {
85107
const controller = await resolveController(source);
86108
if (!controller) return { allowed: true };
87-
return await controller.checkDeploy(check);
109+
const decision = await controller.checkDeploy(check);
110+
if (decision.allowed && check.stage === "initialize") {
111+
try {
112+
await syncComputeOnlyFlag(
113+
client,
114+
check.organizationId,
115+
decision,
116+
organizationFeatureFlags,
117+
{
118+
stage: check.stage,
119+
projectId: check.projectId,
120+
environmentId: check.environmentId,
121+
}
122+
);
123+
} catch (error) {
124+
// Still refused (a compute-only org must never deploy without its flag), but this is a
125+
// transient failure, so say to retry rather than that deploys aren't available.
126+
logger.error("Deployment access: couldn't update the computeOnly flag", {
127+
organizationId: check.organizationId,
128+
placement: decision.placement,
129+
error: error instanceof Error ? error.message : String(error),
130+
});
131+
return { allowed: false, kind: "denied", message: FLAG_SYNC_FAILED_MESSAGE };
132+
}
133+
}
134+
return decision;
88135
} catch (error) {
89136
logger.error("Deployment access check failed", {
90137
stage: check.stage,

‎apps/webapp/app/v3/featureFlags.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ export const FEATURE_FLAG = {
3030
internalApiOriginEnabled: "internalApiOriginEnabled",
3131
realtimeBackend: "realtimeBackend",
3232
computeMigrationEnabled: "computeMigrationEnabled",
33+
computeOnlyDeploys: "computeOnlyDeploys",
3334
computeMigrationFreePercentage: "computeMigrationFreePercentage",
3435
computeMigrationPaidPercentage: "computeMigrationPaidPercentage",
3536
computeTemplatePrebuildWait: "computeTemplatePrebuildWait",
@@ -67,6 +68,7 @@ export const FEATURE_FLAG = {
6768
trustedDeploysEnabled: "trustedDeploysEnabled",
6869
sessionTraceEnabled: "sessionTraceEnabled",
6970
sandboxTasks: "sandboxTasks",
71+
computeOnly: "computeOnly",
7072
auditLogsRecording: "auditLogsRecording",
7173
hasAuditLogsAccess: "hasAuditLogsAccess",
7274
} as const;
@@ -140,6 +142,9 @@ export const FeatureFlagCatalog = {
140142
// `suggested-prompts/promotedPrompt.server.ts`.
141143
[FEATURE_FLAG.promotedDashboardAgentPrompt]: z.string(),
142144
[FEATURE_FLAG.hasComputeAccess]: z.coerce.boolean(),
145+
// Set by the deploy path, never by hand: the org's deployed runs execute only on compute
146+
// (microVM) lanes, with no container fallback. Org-scoped only. Strict z.boolean().
147+
[FEATURE_FLAG.computeOnly]: z.boolean(),
143148
[FEATURE_FLAG.hasPrivateConnections]: z.coerce.boolean(),
144149
[FEATURE_FLAG.hasSso]: z.coerce.boolean(),
145150
// Gates the Interface theme setting in /account. Off by default.
@@ -168,6 +173,10 @@ export const FeatureFlagCatalog = {
168173
// way if written as a string via the admin PAT route. The admin toggle sends a real
169174
// boolean, so this only rejects the dangerous stringified case.
170175
[FEATURE_FLAG.computeMigrationEnabled]: z.boolean(),
176+
// Global only. When on, the deployment access plugin may allow an organization it would
177+
// otherwise deny, with its deployed runs limited to compute (microVM) lanes. Off: it denies as before.
178+
// Read from the global flag snapshot and sent with each deploy access check. Strict z.boolean().
179+
[FEATURE_FLAG.computeOnlyDeploys]: z.boolean(),
171180
[FEATURE_FLAG.computeMigrationFreePercentage]: z.coerce.number().int().min(0).max(100),
172181
[FEATURE_FLAG.computeMigrationPaidPercentage]: z.coerce.number().int().min(0).max(100),
173182
// When on, deploy finalisation waits (up to a timeout) for the compute template
@@ -288,6 +297,7 @@ export const GLOBAL_LOCKED_FLAGS: FeatureFlagKey[] = [
288297
FEATURE_FLAG.runOpsMintShardSetFlippedAt,
289298
FEATURE_FLAG.sandboxTasks,
290299
FEATURE_FLAG.deployCliVersionEnforcedFrom,
300+
FEATURE_FLAG.computeOnly,
291301
];
292302

293303
// Flags that are read-only on the org-level dialog.
@@ -304,6 +314,8 @@ export const ORG_LOCKED_FLAGS: FeatureFlagKey[] = [
304314
FEATURE_FLAG.runOpsMintShardOverride,
305315
// Read per dequeue from the global flag snapshot only; the org's flags aren't loaded there.
306316
FEATURE_FLAG.deploymentStatusMode,
317+
// Read per deploy access check from the global flag snapshot only.
318+
FEATURE_FLAG.computeOnlyDeploys,
307319
];
308320

309321
export type OrgLockedFlagEffect = "live" | "ignored" | "derived";
@@ -322,6 +334,7 @@ export const ORG_LOCKED_FLAG_EFFECT: Partial<Record<FeatureFlagKey, OrgLockedFla
322334
[FEATURE_FLAG.runOpsMintShardSetFlippedAt]: "ignored",
323335
[FEATURE_FLAG.runOpsMintShardOverride]: "ignored",
324336
[FEATURE_FLAG.deploymentStatusMode]: "ignored",
337+
[FEATURE_FLAG.computeOnlyDeploys]: "ignored",
325338
[FEATURE_FLAG.runOpsMintKindPrev]: "derived",
326339
[FEATURE_FLAG.runOpsMintKindFlippedAt]: "derived",
327340
};

0 commit comments

Comments
 (0)